primevul_valid_paired.jsonl 5.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. {"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}
  2. {"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}
  3. {"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<uint8_t> 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<BlobData>();\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}
  4. {"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<uint8_t> png_data;\n if (!ImageEncoder::Encode(&png_data, pixmap, options))\n return nullptr;\n \n auto data = std::make_unique<BlobData>();\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}
  5. {"project": "Chrome", "commit_id": "1da0daecc540238cb473f0d6322da51d3a544244", "target": 1, "func": " void VideoRendererBase::FrameReady(VideoDecoder::DecoderStatus status,\n scoped_refptr<VideoFrame> 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}
  6. {"project": "Chrome", "commit_id": "1da0daecc540238cb473f0d6322da51d3a544244", "target": 0, "func": " void VideoRendererBase::FrameReady(VideoDecoder::DecoderStatus status,\n const scoped_refptr<VideoFrame>& 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}
  7. {"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}
  8. {"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}
  9. {"project": "Chrome", "commit_id": "87190165c55bcf3eecd8824dd8d083f5e3236552", "target": 1, "func": "AudioOutputStream* AudioManagerBase::MakeAudioOutputStreamProxy(\n const AudioParameters& params) {\n DCHECK(GetMessageLoop()->BelongsToCurrentThread());\n\n scoped_refptr<AudioOutputDispatcher>& 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}
  10. {"project": "Chrome", "commit_id": "87190165c55bcf3eecd8824dd8d083f5e3236552", "target": 0, "func": "AudioOutputStream* AudioManagerBase::MakeAudioOutputStreamProxy(\n const AudioParameters& params) {\n DCHECK(GetMessageLoop()->BelongsToCurrentThread());\n\n scoped_refptr<AudioOutputDispatcher>& 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}
  11. {"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}
  12. {"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}
  13. {"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}
  14. {"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<SpeechSynthesisUtterance> 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}
  15. {"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<base::SharedMemory> shared_memory(\n new base::SharedMemory(frame_data->handle, true,\n process_handle));\n#else\n scoped_ptr<base::SharedMemory> 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<SoftwareFrame> 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}
  16. {"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<base::SharedMemory> shared_memory(\n new base::SharedMemory(frame_data->handle, true,\n process_handle));\n#else\n scoped_ptr<base::SharedMemory> 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_t> size_in_bytes_checked =\n base::CheckedNumeric<size_t>(4) *\n base::CheckedNumeric<size_t>(frame_data->size.width()) *\n base::CheckedNumeric<size_t>(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<SoftwareFrame> 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}
  17. {"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}
  18. {"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}
  19. {"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}
  20. {"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}
  21. {"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}
  22. {"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<int64_t>::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}
  23. {"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 %<unknown> */\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<char*>(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<char*>(\"nan\");\n s_len = 3;\n } else if (std::isinf(fp_num)) {\n s = const_cast<char*>(\"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<char*>(\"NAN\");\n s_len = 3;\n break;\n } else if (std::isinf(fp_num)) {\n if (fp_num > 0) {\n s = const_cast<char*>(\"INF\");\n s_len = 3;\n } else {\n s = const_cast<char*>(\"-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<char*>(\"%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 %<char> 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 %<char> (like syslog).\n * Note that we can't point s inside fmt because the\n * unknown <char> 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}
  24. {"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 %<unknown> */\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<char*>(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<char*>(\"nan\");\n s_len = 3;\n } else if (std::isinf(fp_num)) {\n s = const_cast<char*>(\"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<char*>(\"NAN\");\n s_len = 3;\n break;\n } else if (std::isinf(fp_num)) {\n if (fp_num > 0) {\n s = const_cast<char*>(\"INF\");\n s_len = 3;\n } else {\n s = const_cast<char*>(\"-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<char*>(\"%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 %<char> 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 %<char> (like syslog).\n * Note that we can't point s inside fmt because the\n * unknown <char> 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}
  25. {"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<CPlayList> 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}
  26. {"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<char>(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<CPlayList> 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}
  27. {"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<float>(input), GetTensorShape(filter),\n GetTensorData<float>(filter), GetTensorShape(bias),\n GetTensorData<float>(bias), GetTensorShape(output),\n GetTensorData<float>(output));\n } else {\n reference_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData<float>(input),\n GetTensorShape(filter), GetTensorData<float>(filter),\n GetTensorShape(bias), GetTensorData<float>(bias),\n GetTensorShape(output), GetTensorData<float>(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<float>(input), GetTensorShape(filter),\n GetTensorData<float>(filter), GetTensorShape(bias),\n GetTensorData<float>(bias), GetTensorShape(output),\n GetTensorData<float>(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<float>(input), GetTensorShape(filter),\n GetTensorData<float>(filter), GetTensorShape(bias),\n GetTensorData<float>(bias), GetTensorShape(output),\n GetTensorData<float>(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<float>(input),\n GetTensorShape(filter), GetTensorData<float>(filter),\n GetTensorShape(bias), GetTensorData<float>(bias),\n GetTensorShape(output), GetTensorData<float>(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}
  28. {"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<float>(input), GetTensorShape(filter),\n GetTensorData<float>(filter), GetTensorShape(bias),\n GetTensorData<float>(bias), GetTensorShape(output),\n GetTensorData<float>(output));\n } else {\n reference_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData<float>(input),\n GetTensorShape(filter), GetTensorData<float>(filter),\n GetTensorShape(bias), GetTensorData<float>(bias),\n GetTensorShape(output), GetTensorData<float>(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<float>(input), // Disable formatting\n filter_shape, GetTensorData<float>(filter), // Disable formatting\n bias_shape, GetTensorData<float>(bias), // Disable formatting\n output_shape, GetTensorData<float>(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<float>(input), // Disable formatting\n filter_shape, GetTensorData<float>(filter), // Disable formatting\n bias_shape, GetTensorData<float>(bias), // Disable formatting\n output_shape, GetTensorData<float>(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<float>(input),\n GetTensorShape(filter), GetTensorData<float>(filter),\n GetTensorShape(bias), GetTensorData<float>(bias),\n GetTensorShape(output), GetTensorData<float>(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}
  29. {"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}
  30. {"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}
  31. {"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}
  32. {"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}
  33. {"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}
  34. {"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}
  35. {"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}
  36. {"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}
  37. {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data);\n OpData* data = reinterpret_cast<OpData*>(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<TfLiteAffineQuantization*>(\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<TfLiteAffineQuantization*>(\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}
  38. {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data);\n OpData* data = reinterpret_cast<OpData*>(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<TfLiteAffineQuantization*>(\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<TfLiteAffineQuantization*>(\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}
  39. {"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 <hbh25y@gmail.com>\nLink: https://lore.kernel.org/r/20211209082839.33985-1-hbh25y@gmail.com\nSigned-off-by: Jakub Kicinski <kuba@kernel.org>", "target": 1, "dataset": "other", "idx": 195337}
  40. {"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 <hbh25y@gmail.com>\nLink: https://lore.kernel.org/r/20211209082839.33985-1-hbh25y@gmail.com\nSigned-off-by: Jakub Kicinski <kuba@kernel.org>", "target": 0, "dataset": "other", "idx": 224826}
  41. {"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}
  42. {"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}
  43. {"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}
  44. {"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}
  45. {"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}
  46. {"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}
  47. {"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 <mgerstner@suse.de> for reporting this.", "target": 1, "dataset": "other", "idx": 195488}
  48. {"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 <mgerstner@suse.de> for reporting this.", "target": 0, "dataset": "other", "idx": 227355}
  49. {"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}
  50. {"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}
  51. {"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<Device, GPUDevice>::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<T>::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<Device, T> functor;\n if (logits_in.IsSameSize(labels_in)) {\n functor(context->eigen_device<Device>(), shape_in.AsEigenDSizes<2>(),\n Eigen::array<Eigen::DenseIndex, 2>{1, 1},\n Eigen::array<Eigen::DenseIndex, 2>{1, 1}, logits_in.matrix<T>(),\n labels_in.matrix<T>(), scratch.matrix<T>(), loss_out->vec<T>(),\n back_out->matrix<T>());\n } else {\n functor(context->eigen_device<Device>(), shape_in.AsEigenDSizes<2>(),\n BCast::ToIndexArray<2>(bcast.x_bcast()),\n BCast::ToIndexArray<2>(bcast.y_bcast()),\n logits_in.template shaped<T, 2>(bcast.x_reshape()),\n labels_in.template shaped<T, 2>(bcast.y_reshape()),\n scratch.matrix<T>(), loss_out->vec<T>(), back_out->matrix<T>());\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}
  52. {"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<Device, GPUDevice>::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<T>::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<Device, T> functor;\n functor(context->eigen_device<Device>(), shape_in.AsEigenDSizes<2>(),\n BCast::ToIndexArray<2>(bcast.x_bcast()),\n BCast::ToIndexArray<2>(bcast.y_bcast()),\n logits_in.template shaped<T, 2>(bcast.x_reshape()),\n labels_in.template shaped<T, 2>(bcast.y_reshape()),\n scratch.matrix<T>(), loss_out->vec<T>(), back_out->matrix<T>());\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}
  53. {"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}
  54. {"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}
  55. {"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; ii<rv; 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\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}
  56. {"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}
  57. {"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<float>()(0);\n const float max_range = input_max_tensor.flat<float>()(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<T, 3>(\n {pre_dim, num_slices, post_dim});\n auto output_tensor =\n float_output.flat_inner_outer_dims<float, 3>(axis_ - 1);\n auto min_ranges = input_min_tensor.vec<float>();\n auto max_ranges = input_max_tensor.vec<float>();\n for (int i = 0; i < num_slices; ++i) {\n DequantizeSlice(ctx->eigen_device<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<S>().data();\n float* in_ptr = float_output.flat<float>().data();\n for (int64 i = 0; i < float_output.NumElements(); ++i) {\n out_ptr[i] = static_cast<S>(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}
  58. {"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<float>()(0);\n const float max_range = input_max_tensor.flat<float>()(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<T, 3>(\n {pre_dim, num_slices, post_dim});\n auto output_tensor =\n float_output.flat_inner_outer_dims<float, 3>(axis_ - 1);\n auto min_ranges = input_min_tensor.vec<float>();\n auto max_ranges = input_max_tensor.vec<float>();\n for (int i = 0; i < num_slices; ++i) {\n DequantizeSlice(ctx->eigen_device<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<S>().data();\n float* in_ptr = float_output.flat<float>().data();\n for (int64 i = 0; i < float_output.NumElements(); ++i) {\n out_ptr[i] = static_cast<S>(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}
  59. {"func": "CallResult<PseudoHandle<>> JSObject::getComputedWithReceiver_RJS(\n Handle<JSObject> 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<JSObject> 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<PropertyAccessor>(\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<HostObject>(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<Handle<>> 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}
  60. {"func": "CallResult<PseudoHandle<>> JSObject::getComputedWithReceiver_RJS(\n Handle<JSObject> 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<JSObject> 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<PropertyAccessor>(\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<HostObject>(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<Handle<>> 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}
  61. {"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; i<ptr->server_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; i<ptr->quality_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; i<ptr->segment_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; i<ptr->fragment_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}
  62. {"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; i<ptr->server_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; i<ptr->quality_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; i<ptr->segment_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; i<ptr->fragment_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}
  63. {"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<n; i++){\n aAscii[i] = (u8)bToken;\n }\n iTbl++;\n }\n}", "project": "sqlite", "hash": 214840049614538452414476078085917423347, "size": 12, "commit_id": "d1d43efa4fb0f2098c0e2c5bf2e807c58d5ec05b", "message": "Prevent fts5 tokenizer unicode61 from considering '\\0' to be a token characters, even if other characters of class \"Cc\" are.\n\nFossilOrigin-Name: b7b7bde9b7a03665e3691c6d51118965f216d2dfb1617f138b9f9e60e418ed2f", "target": 1, "dataset": "other", "idx": 195680}
  64. {"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<n; i++){\n aAscii[i] = (u8)bToken;\n }\n iTbl++;\n }\n aAscii[0] = 0; /* 0x00 is never a token character */\n}", "project": "sqlite", "hash": 138808873422941292787822650142783113699, "size": 13, "commit_id": "d1d43efa4fb0f2098c0e2c5bf2e807c58d5ec05b", "message": "Prevent fts5 tokenizer unicode61 from considering '\\0' to be a token characters, even if other characters of class \"Cc\" are.\n\nFossilOrigin-Name: b7b7bde9b7a03665e3691c6d51118965f216d2dfb1617f138b9f9e60e418ed2f", "target": 0, "dataset": "other", "idx": 230603}
  65. {"func": "int32_t *enc_untrusted_create_wait_queue() {\n MessageWriter input;\n MessageReader output;\n input.Push<uint64_t>(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<int32_t *>(output.next<uintptr_t>());\n int klinux_errno = output.next<int>();\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}
  66. {"func": "int32_t *enc_untrusted_create_wait_queue() {\n MessageWriter input;\n MessageReader output;\n input.Push<uint64_t>(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<int32_t *>(output.next<uintptr_t>());\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<int>();\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}
  67. {"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}
  68. {"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}
  69. {"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}
  70. {"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}
  71. {"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<SgxParams *>(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<void *>(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<void *>(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}
  72. {"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<SgxParams *>(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<void *>(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<void *>(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}
  73. {"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}
  74. {"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}
  75. {"func": "inline void ComputeInterpolationWeights(\n const int64 out_size, const int64 in_size, const float scale,\n const int resolution, InterpolationCache<T_SCALE>* 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<int64>(in_f), static_cast<int64>(0));\n interpolation->upper[i] =\n std::min(static_cast<int64>(std::ceil(in)), in_size - 1);\n interpolation->lerp[i] = in - in_f;\n interpolation->ilerp[i] =\n static_cast<T_SCALE>((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}
  76. {"func": "inline void ComputeInterpolationWeights(\n const int64 out_size, const int64 in_size, const float scale,\n const int resolution, InterpolationCache<T_SCALE>* 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<int64>(in_f), static_cast<int64>(0));\n interpolation->upper[i] =\n std::min(static_cast<int64>(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<T_SCALE>((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}
  77. {"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 <john.fastabend@gmail.com>\nSigned-off-by: Alexei Starovoitov <ast@kernel.org>\nLink: https://lore.kernel.org/bpf/158507151689.15666.566796274289413203.stgit@john-Precision-5820-Tower", "target": 1, "dataset": "other", "idx": 195753}
  78. {"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 <john.fastabend@gmail.com>\nSigned-off-by: Alexei Starovoitov <ast@kernel.org>\nLink: https://lore.kernel.org/bpf/158507151689.15666.566796274289413203.stgit@john-Precision-5820-Tower", "target": 0, "dataset": "other", "idx": 232639}
  79. {"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<Scalar>::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}
  80. {"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<Scalar>::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}
  81. {"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}
  82. {"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}
  83. {"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 <yonghua.huang@intel.com>", "target": 1, "dataset": "other", "idx": 195776}
  84. {"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 <yonghua.huang@intel.com>", "target": 0, "dataset": "other", "idx": 232979}
  85. {"func": " void ComputeEasyCases(OpKernelContext* context, bool* done,\n std::vector<Tlen>* 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<int32>()(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<Tlen>();\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}
  86. {"func": " void ComputeEasyCases(OpKernelContext* context, bool* done,\n std::vector<Tlen>* 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<int32>()(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<Tlen>();\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}
  87. {"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<extension_len; ) {\n\tu_int16_t extension_id, extension_len;\n\n\tif((offset+4) > 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_i<alpn_len; alpn_i++)\n\t {\n\t alpn_str[alpn_str_len+alpn_i] = packet->payload[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; i<extension_len-1; i++) {\n\t u_int8_t s_group = packet->payload[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<ja3.server.num_cipher; i++) {\n\trc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-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 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<ja3.server.num_tls_extension; i++) {\n\tint rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-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.server.num_elliptic_curve_point_format; i++) {\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-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') {\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; i<cipher_len;) {\n\t u_int16_t *id = (u_int16_t*)&packet->payload[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; i<extension_len-2;) {\n\t\t u_int16_t s_group = ntohs(*((u_int16_t*)&packet->payload[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; i<extension_len-1; i++) {\n\t\t u_int8_t s_group = packet->payload[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; i<tot_signature_algorithms_len; i++) {\n\t\t int rc = snprintf(&ja3.client.signature_algorithms[i*2], sizeof(ja3.client.signature_algorithms)-i*2, \"%02X\", packet->payload[s_offset+i]);\n\n\t\t if(rc < 0) break;\n\t\t}\n\n\t\tfor(i=0; i<tot_signature_algorithms_len; i+=2) {\n\t\t u_int16_t cipher_id = (u_int16_t)ntohs(*((u_int16_t*)&packet->payload[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_i<alpn_len; alpn_i++)\n\t\t\talpn_str[alpn_str_len+alpn_i] = packet->payload[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+1<version_len; j += 2) {\n\t\t u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[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], &param_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], &param_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<ja3.client.num_cipher; i++) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \"%s%u\",\n\t\t\t (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<ja3.client.num_tls_extension; i++) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \"%s%u\",\n\t\t\t (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<ja3.client.num_elliptic_curve; i++) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \"%s%u\",\n\t\t\t (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<ja3.client.num_elliptic_curve_point_format; i++) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \"%s%u\",\n\t\t\t (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}
  88. {"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<extension_len; ) {\n\tu_int16_t extension_id, extension_len;\n\n\tif((offset+4) > 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_i<alpn_len; alpn_i++)\n\t {\n\t alpn_str[alpn_str_len+alpn_i] = packet->payload[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; i<extension_len-1; i++) {\n\t u_int8_t s_group = packet->payload[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.server.num_cipher) && (JA3_STR_LEN > 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.server.num_tls_extension) && (JA3_STR_LEN > 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.server.num_elliptic_curve_point_format) && (JA3_STR_LEN > 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; i<cipher_len;) {\n\t u_int16_t *id = (u_int16_t*)&packet->payload[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; i<extension_len-2;) {\n\t\t u_int16_t s_group = ntohs(*((u_int16_t*)&packet->payload[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; i<extension_len-1; i++) {\n\t\t u_int8_t s_group = packet->payload[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; i<tot_signature_algorithms_len; i++) {\n\t\t int rc = snprintf(&ja3.client.signature_algorithms[i*2], sizeof(ja3.client.signature_algorithms)-i*2, \"%02X\", packet->payload[s_offset+i]);\n\n\t\t if(rc < 0) break;\n\t\t}\n\n\t\tfor(i=0; i<tot_signature_algorithms_len; i+=2) {\n\t\t u_int16_t cipher_id = (u_int16_t)ntohs(*((u_int16_t*)&packet->payload[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_i<alpn_len; alpn_i++)\n\t\t\talpn_str[alpn_str_len+alpn_i] = packet->payload[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+1<version_len; j += 2) {\n\t\t u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[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], &param_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], &param_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<ja3.client.num_cipher; i++) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\",\n\t\t\t (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<ja3.client.num_tls_extension; i++) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\",\n\t\t\t (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<ja3.client.num_elliptic_curve; i++) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\",\n\t\t\t (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<ja3.client.num_elliptic_curve_point_format; i++) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\",\n\t\t\t (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}
  89. {"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 <nlivic@gmail.com>\nSigned-off-by: Dan Carpenter <dan.carpenter@oracle.com>\nSigned-off-by: Trond Myklebust <trond.myklebust@hammerspace.com>", "target": 1, "dataset": "other", "idx": 195843}
  90. {"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 <nlivic@gmail.com>\nSigned-off-by: Dan Carpenter <dan.carpenter@oracle.com>\nSigned-off-by: Trond Myklebust <trond.myklebust@hammerspace.com>", "target": 0, "dataset": "other", "idx": 234482}
  91. {"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<CPUDevice>();\n auto input = Tensor(in).flat_inner_dims<RealT, FFTRank + 1>();\n const auto input_dims = input.dimensions();\n\n // Slice input to fft_shape on its inner-most dimensions.\n Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> 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<ComplexT, FFTRank + 1>();\n const Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> 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<ComplexT>::v(),\n temp_shape, &temp));\n auto full_fft = temp.flat_inner_dims<ComplexT, FFTRank + 1>();\n full_fft.device(device) =\n input.slice(zero_start_indices, input_slice_sizes)\n .template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(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}
  92. {"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<CPUDevice>();\n auto input = Tensor(in).flat_inner_dims<RealT, FFTRank + 1>();\n const auto input_dims = input.dimensions();\n\n // Slice input to fft_shape on its inner-most dimensions.\n Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> 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<ComplexT, FFTRank + 1>();\n const Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> 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<ComplexT>::v(),\n temp_shape, &temp));\n auto full_fft = temp.flat_inner_dims<ComplexT, FFTRank + 1>();\n full_fft.device(device) =\n input.slice(zero_start_indices, input_slice_sizes)\n .template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(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}
  93. {"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 <mick@dejavusecurity.com> for finding this!", "target": 1, "dataset": "other", "idx": 195966}
  94. {"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 <mick@dejavusecurity.com> for finding this!", "target": 0, "dataset": "other", "idx": 235766}
  95. {"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<int64>();\n const auto shape_vec = shape_t->vec<int64>();\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<int64> lhs, ArraySlice<int64> 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<T>::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<T>();\n const int ndims = lhs_dims.size();\n switch (ndims) {\n#define CASE(NDIM) \\\n case NDIM: { \\\n TensorRef<Eigen::Tensor<const T, NDIM, Eigen::RowMajor>> rhs_ref = \\\n dense_t->shaped<T, NDIM>(b.y_reshape()) \\\n .broadcast(BCast::ToIndexArray<NDIM>(b.y_bcast())); \\\n Eigen::array<Eigen::DenseIndex, NDIM> 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<T>().device(ctx->eigen_device<Device>()) =\n values_t->flat<T>().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}
  96. {"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<int64>();\n const auto shape_vec = shape_t->vec<int64>();\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<int64> lhs, ArraySlice<int64> 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<T>::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<T>();\n const int ndims = lhs_dims.size();\n switch (ndims) {\n#define CASE(NDIM) \\\n case NDIM: { \\\n TensorRef<Eigen::Tensor<const T, NDIM, Eigen::RowMajor>> rhs_ref = \\\n dense_t->shaped<T, NDIM>(b.y_reshape()) \\\n .broadcast(BCast::ToIndexArray<NDIM>(b.y_bcast())); \\\n Eigen::array<Eigen::DenseIndex, NDIM> 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<T>().device(ctx->eigen_device<Device>()) =\n values_t->flat<T>().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}
  97. {"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}
  98. {"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}
  99. {"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<void**>(&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}
  100. {"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<void**>(&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}
  101. {"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 (n<len) {\n gen_assignment(s, t->car, 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; i<nargs; i++) {\n gen_move(s, cursp()+i+1, base+i+1, 1);\n }\n push_n(nargs+2);pop_n(nargs+2); /* space for receiver, arguments and a block */\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n push();\n }\n else {\n codegen(s, tree->car, 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}
  102. {"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 (n<len) {\n gen_assignment(s, t->car, 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; i<nargs; i++) {\n gen_move(s, cursp()+i+1, base+i+1, 1);\n }\n push_n(nargs+2);pop_n(nargs+2); /* space for receiver, arguments and a block */\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n push();\n }\n else {\n codegen(s, tree->car, 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}
  103. {"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}
  104. {"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}
  105. {"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<int32>();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat<SPLITS_TYPE>();\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<tstring>();\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}
  106. {"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<int32>();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat<SPLITS_TYPE>();\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<tstring>();\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}
  107. {"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 <yong.tang.github@outlook.com>", "target": 1, "dataset": "other", "idx": 196330}
  108. {"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<float, 2>()(i, j))) {\n return errors::InvalidArgument(\n \"boxes values must be finite, received boxes[\", i, \"]: \",\n boxes.tensor<float, 2>()(i, 0), \", \",\n boxes.tensor<float, 2>()(i, 1), \", \",\n boxes.tensor<float, 2>()(i, 2), \", \",\n boxes.tensor<float, 2>()(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 <yong.tang.github@outlook.com>", "target": 0, "dataset": "other", "idx": 238855}
  109. {"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 <david@adalogics.com>", "target": 1, "dataset": "other", "idx": 196589}
  110. {"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 <david@adalogics.com>", "target": 0, "dataset": "other", "idx": 240791}
  111. {"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}
  112. {"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}
  113. {"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}
  114. {"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}
  115. {"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}
  116. {"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}
  117. {"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<Device, T>()(\n context, context->eigen_device<Device>(),\n in_backprop->tensor<T, 4>(), filter.tensor<T, 4>(),\n out_backprop.tensor<T, 4>(), dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n static_cast<int>(dims.spatial_dims[0].stride),\n static_cast<int>(dims.spatial_dims[1].stride),\n static_cast<int>(pad_top), static_cast<int>(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<T>::value,\n TensorShape({static_cast<int64>(shard_size),\n static_cast<int64>(output_image_size),\n static_cast<int64>(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<T>().data();\n T* col_buffer_data = col_buffer.template flat<T>().data();\n const T* out_backprop_data = out_backprop.template flat<T>().data();\n\n auto in_backprop_flat = in_backprop->template flat<T>();\n T* input_backprop_data = in_backprop_flat.data();\n in_backprop_flat.device(context->eigen_device<Device>()) =\n in_backprop_flat.constant(T(0));\n\n if (use_parallel_contraction) {\n typedef Eigen::TensorMap<Eigen::Tensor<T, 2, Eigen::RowMajor>,\n Eigen::Unaligned>\n TensorMap;\n typedef Eigen::TensorMap<Eigen::Tensor<const T, 2, Eigen::RowMajor>,\n Eigen::Unaligned>\n ConstTensorMap;\n\n // Initialize contraction dims (we need to transpose 'B' below).\n Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 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<T>(\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<int>(shard_size),\n static_cast<int>(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<T>()(\n context, out_data, filter_data, filter_total_size,\n output_image_size, dims.out_depth, im2col_buf);\n\n Col2im<T>(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}
  118. {"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<Device, T>()(\n context, context->eigen_device<Device>(),\n in_backprop->tensor<T, 4>(), filter.tensor<T, 4>(),\n out_backprop.tensor<T, 4>(), dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n static_cast<int>(dims.spatial_dims[0].stride),\n static_cast<int>(dims.spatial_dims[1].stride),\n static_cast<int>(pad_top), static_cast<int>(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<T>::value,\n TensorShape({static_cast<int64>(shard_size),\n static_cast<int64>(output_image_size),\n static_cast<int64>(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<T>().data();\n T* col_buffer_data = col_buffer.template flat<T>().data();\n const T* out_backprop_data = out_backprop.template flat<T>().data();\n\n auto in_backprop_flat = in_backprop->template flat<T>();\n T* input_backprop_data = in_backprop_flat.data();\n in_backprop_flat.device(context->eigen_device<Device>()) =\n in_backprop_flat.constant(T(0));\n\n if (use_parallel_contraction) {\n typedef Eigen::TensorMap<Eigen::Tensor<T, 2, Eigen::RowMajor>,\n Eigen::Unaligned>\n TensorMap;\n typedef Eigen::TensorMap<Eigen::Tensor<const T, 2, Eigen::RowMajor>,\n Eigen::Unaligned>\n ConstTensorMap;\n\n // Initialize contraction dims (we need to transpose 'B' below).\n Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 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<T>(\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<int>(shard_size),\n static_cast<int>(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<T>()(\n context, out_data, filter_data, filter_total_size,\n output_image_size, dims.out_depth, im2col_buf);\n\n Col2im<T>(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}
  119. {"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, \"&amp;\");\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, \"&lt;\");\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, \"&gt;\");\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}
  120. {"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, \"&amp;\");\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, \"&lt;\");\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, \"&gt;\");\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}
  121. {"func": " void Compute(OpKernelContext* context) override {\n const float in_min = context->input(2).flat<float>()(0);\n const float in_max = context->input(3).flat<float>()(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<T, 4>::ConstTensor image_data(\n context->input(0).tensor<T, 4>());\n typename TTypes<T, 4>::Tensor output_data(st.output->tensor<T, 4>());\n\n ResizeBilinear<T>(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<float>()(0) = in_min;\n\n Tensor* out_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &out_max));\n out_max->flat<float>()(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}
  122. {"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<float>()(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<float>()(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<T, 4>::ConstTensor image_data(\n context->input(0).tensor<T, 4>());\n typename TTypes<T, 4>::Tensor output_data(st.output->tensor<T, 4>());\n\n ResizeBilinear<T>(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<float>()(0) = in_min;\n\n Tensor* out_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &out_max));\n out_max->flat<float>()(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}
  123. {"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; i<gf_list_count(avccfg->sequenceParameterSets); 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; i<gf_list_count(svccfg->sequenceParameterSets); 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; i<gf_list_count(mvccfg->sequenceParameterSets); 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; i<count; i++) {\n\t\t\tu8 hash[20];\n\t\t\tGF_AV1_OBUArrayEntry *obu = gf_list_get(av1c->obu_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; i<ac3->streams[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; i<nb_compat_profiles; i++) {\n\t\t\tif (!i)\n\t\t\t\tfprintf(stderr, \"\\tCompatible profiles:\");\n\t\t\tfprintf(stderr, \" 0x%02X\", compat_profiles[i]);\n\t\t}\n\t\tif (i) fprintf(stderr, \"\\n\");\n\t} else if (msub_type==GF_ISOM_SUBTYPE_MLPA) {\n\t\tu32 fmt, prate;\n\t\tif (gf_isom_truehd_config_get(file, trackNum, 1, &fmt, &prate) != GF_OK) {\n\t\t\tfprintf(stderr, \"\\tInvalid TrueHD audio config\\n\");\n\t\t}\n\t\tfprintf(stderr, \"TrueHD Audio stream - Sample Rate %u - channels %u - format %u peak rate %u\\n\", sr, nb_ch, fmt, prate);\n\t} else if (codecid) {\n\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n\t\t\tu32 w, h;\n\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\tfprintf(stderr, \"%s - Resolution %d x %d\\n\", gf_codecid_name(codecid), w, h);\n\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\tgf_isom_get_audio_info(file, trackNum, 1, &sr, &nb_ch, NULL);\n\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codecid), sr, nb_ch);\n\t\t} else {\n\t\t\tfprintf(stderr, \"%s\\n\", gf_codecid_name(codecid) );\n\t\t}\n\t} else if (pfmt) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"Raw video %s - Resolution %d x %d\\n\", gf_pixel_fmt_name(pfmt), w, h);\n\t} else if (msub_type==GF_QT_SUBTYPE_TMCD) {\n\t\tu32 stsd_idx;\n\t\tGF_ISOSample *sample = gf_isom_get_sample(file, trackNum, 1, &stsd_idx);\n\t\tfprintf(stderr, \"Time Code stream\\n\");\n\t\tif (sample) {\n\t\t\tchar szTimecode[100];\n\t\t\tu32 tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt;\n\n\t\t\tgf_isom_get_tmcd_config(file, trackNum, stsd_idx, &tmcd_flags, &tmcd_num, &tmcd_den, &tmcd_fpt);\n\n\t\t\tgf_inspect_format_timecode(sample->data, 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 (i<hdr_len) {\n\t\t\t\t\tif (start[i]==0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\t\\t%s\\n\", start+offset);\n\t\t\t\t\t\toffset=i+1;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\\\tt%s\\n\", start+offset);\n\t\t\t}\n\t\t\tif (orig_len) fprintf(stderr, \"\\tOriginal media size \"LLD\"\\n\", orig_len);\n\t\t\tfprintf(stderr, \"\\tEncryption algorithm %s\\n\", (enc_type==1) ? \"AEA 128 CBC\" : (enc_type ? \"AEA 128 CTR\" : \"None\"));\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_cenc_media(file, trackNum, 1)) {\n\t\t\tconst u8 *def_key;\n\t\t\tu32 def_key_size;\n\t\t\tBool IsEncrypted;\n\t\t\tu8 crypt_byte_block, skip_byte_block;\n\t\t\tIV_size = 0;\n\t\t\tgf_isom_get_cenc_info(file, trackNum, 1, NULL, &scheme_type, &version);\n\n\t\t\tgf_isom_cenc_get_default_info(file, trackNum, 1, NULL, &IsEncrypted, &crypt_byte_block, &skip_byte_block, &def_key, &def_key_size);\n\n\t\t\tfprintf(stderr, \"\\n\\tProtected by CENC scheme %s version 0x%08X\", gf_4cc_to_str(scheme_type), version);\n\n\t\t\tif (crypt_byte_block && skip_byte_block)\n\t\t\t\tfprintf(stderr, \" - Pattern %d:%d\", (u32) skip_byte_block, (u32) crypt_byte_block);\n\t\t\tif (def_key && def_key[0])\n\t\t\t\tfprintf(stderr, \" - MultiKey\");\n\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t\tdump_key_info(def_key, def_key_size, IsEncrypted);\n\n\t\t} else if(gf_isom_is_adobe_protection_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_adobe_protection_info(file, trackNum, 1, NULL, &scheme_type, &version, NULL);\n\t\t\tfprintf(stderr, \"\\nProtected by Adobe scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\nProtected by unknown scheme %s\\n\", gf_4cc_to_str(gf_isom_is_media_encrypted(file, trackNum, 0) ));\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t}\n\n\tif ( gf_media_get_rfc_6381_codec_name(file, trackNum, szCodec, GF_FALSE, GF_FALSE) == GF_OK) {\n\t\tfprintf(stderr, \"\\tRFC6381 Codec Parameters: %s\\n\", szCodec);\n\t}\n\n\n\tDumpMetaItem(file, 0, trackNum, \"\\tTrack Meta\");\n\n\tgf_isom_get_track_switch_group_count(file, trackNum, &alt_group, &nb_groups);\n\tif (alt_group) {\n\t\tfprintf(stderr, \"Alternate Group ID %d\\n\", alt_group);\n\t\tfor (i=0; i<nb_groups; i++) {\n\t\t\tu32 nb_crit, switchGroupID;\n\t\t\tconst u32 *criterias = gf_isom_get_track_switch_parameter(file, trackNum, i+1, &switchGroupID, &nb_crit);\n\t\t\tif (!nb_crit) {\n\t\t\t\tfprintf(stderr, \"\\tNo criteria in %s group\\n\", switchGroupID ? \"switch\" : \"alternate\");\n\t\t\t} else {\n\t\t\t\tif (switchGroupID) {\n\t\t\t\t\tfprintf(stderr, \"\\tSwitchGroup ID %d criterias: \", switchGroupID);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"\\tAlternate Group criterias: \");\n\t\t\t\t}\n\t\t\t\tfor (j=0; j<nb_crit; j++) {\n\t\t\t\t\tif (j) fprintf(stderr, \" \");\n\t\t\t\t\tfprintf(stderr, \"%s\", gf_4cc_to_str(criterias[j]) );\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch (gf_isom_has_sync_points(file, trackNum)) {\n\tcase 0:\n\t\tfprintf(stderr, \"\\tAll samples are sync\\n\");\n\t\tbreak;\n\tcase 1:\n\t{\n\t\tu32 nb_sync = gf_isom_get_sync_point_count(file, trackNum) - 1;\n\t\tif (! nb_sync) {\n\t\t\tfprintf(stderr, \"\\tOnly one sync sample\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\tAverage GOP length: %d samples\\n\", gf_isom_get_sample_count(file, trackNum) / nb_sync);\n\t\t}\n\t}\n\tbreak;\n\tcase 2:\n\t\tfprintf(stderr, \"\\tNo sync sample found\\n\");\n\t\tbreak;\n\t}\n\tfprintf(stderr, \"\\tMax sample duration: %d / %d\\n\", gf_isom_get_max_sample_delta(file, trackNum), timescale);\n\n\tif (!full_dump) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}\n\n\tdur = size = 0;\n\tmax_rate = rate = 0;\n\ttime_slice = 0;\n\tts = gf_isom_get_media_timescale(file, trackNum);\n\tcsize = gf_isom_get_constant_sample_size(file, trackNum);\n\tcdur = gf_isom_get_constant_sample_duration(file, trackNum);\n\tcount = gf_isom_get_sample_count(file, trackNum);\n\tif (csize && cdur) {\n\t\tsize = count * csize;\n\t\tdur = cdur * count;\n\t} else {\n\n\t\tfor (j=0; j<count; j++) {\n\t\t\tGF_ISOSample *samp;\n\t\t\tif (is_od_track) {\n\t\t\t\tsamp = gf_isom_get_sample(file, trackNum, j+1, NULL);\n\t\t\t} else {\n\t\t\t\tsamp = gf_isom_get_sample_info(file, trackNum, j+1, NULL, NULL);\n\t\t\t}\n\t\t\tif (!samp) {\n\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to fetch sample %d\\n\", j+1));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdur = samp->DTS+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; j<count; j++) {\n\t\t\tgf_isom_get_chapter(file, trackNum, j+1, &time, &name);\n\t\t\tfprintf(stderr, \"\\tChapter #%d - %s - \\\"%s\\\"\\n\", j+1, format_duration(time, 1000, szDur), name);\n\t\t}", "project": "gpac", "hash": 106085528695165772265170925572687749931, "size": 1036, "commit_id": "289ffce3e0d224d314f5f92a744d5fe35999f20b", "message": "fixed #1767 (fuzz)", "target": 1, "dataset": "other", "idx": 196719}
  124. {"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; i<gf_list_count(avccfg->sequenceParameterSets); 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; i<gf_list_count(svccfg->sequenceParameterSets); 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; i<gf_list_count(mvccfg->sequenceParameterSets); 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; i<count; i++) {\n\t\t\t\tu8 hash[20];\n\t\t\t\tGF_AV1_OBUArrayEntry *obu = gf_list_get(av1c->obu_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; i<ac3->streams[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; i<nb_compat_profiles; i++) {\n\t\t\tif (!i)\n\t\t\t\tfprintf(stderr, \"\\tCompatible profiles:\");\n\t\t\tfprintf(stderr, \" 0x%02X\", compat_profiles[i]);\n\t\t}\n\t\tif (i) fprintf(stderr, \"\\n\");\n\t} else if (msub_type==GF_ISOM_SUBTYPE_MLPA) {\n\t\tu32 fmt, prate;\n\t\tif (gf_isom_truehd_config_get(file, trackNum, 1, &fmt, &prate) != GF_OK) {\n\t\t\tfprintf(stderr, \"\\tInvalid TrueHD audio config\\n\");\n\t\t}\n\t\tfprintf(stderr, \"TrueHD Audio stream - Sample Rate %u - channels %u - format %u peak rate %u\\n\", sr, nb_ch, fmt, prate);\n\t} else if (codecid) {\n\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n\t\t\tu32 w, h;\n\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\tfprintf(stderr, \"%s - Resolution %d x %d\\n\", gf_codecid_name(codecid), w, h);\n\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\tgf_isom_get_audio_info(file, trackNum, 1, &sr, &nb_ch, NULL);\n\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codecid), sr, nb_ch);\n\t\t} else {\n\t\t\tfprintf(stderr, \"%s\\n\", gf_codecid_name(codecid) );\n\t\t}\n\t} else if (pfmt) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"Raw video %s - Resolution %d x %d\\n\", gf_pixel_fmt_name(pfmt), w, h);\n\t} else if (msub_type==GF_QT_SUBTYPE_TMCD) {\n\t\tu32 stsd_idx;\n\t\tGF_ISOSample *sample = gf_isom_get_sample(file, trackNum, 1, &stsd_idx);\n\t\tfprintf(stderr, \"Time Code stream\\n\");\n\t\tif (sample) {\n\t\t\tchar szTimecode[100];\n\t\t\tu32 tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt;\n\n\t\t\tgf_isom_get_tmcd_config(file, trackNum, stsd_idx, &tmcd_flags, &tmcd_num, &tmcd_den, &tmcd_fpt);\n\n\t\t\tgf_inspect_format_timecode(sample->data, 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 (i<hdr_len) {\n\t\t\t\t\tif (start[i]==0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\t\\t%s\\n\", start+offset);\n\t\t\t\t\t\toffset=i+1;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\\\tt%s\\n\", start+offset);\n\t\t\t}\n\t\t\tif (orig_len) fprintf(stderr, \"\\tOriginal media size \"LLD\"\\n\", orig_len);\n\t\t\tfprintf(stderr, \"\\tEncryption algorithm %s\\n\", (enc_type==1) ? \"AEA 128 CBC\" : (enc_type ? \"AEA 128 CTR\" : \"None\"));\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_cenc_media(file, trackNum, 1)) {\n\t\t\tconst u8 *def_key;\n\t\t\tu32 def_key_size;\n\t\t\tBool IsEncrypted;\n\t\t\tu8 crypt_byte_block, skip_byte_block;\n\t\t\tIV_size = 0;\n\t\t\tgf_isom_get_cenc_info(file, trackNum, 1, NULL, &scheme_type, &version);\n\n\t\t\tgf_isom_cenc_get_default_info(file, trackNum, 1, NULL, &IsEncrypted, &crypt_byte_block, &skip_byte_block, &def_key, &def_key_size);\n\n\t\t\tfprintf(stderr, \"\\n\\tProtected by CENC scheme %s version 0x%08X\", gf_4cc_to_str(scheme_type), version);\n\n\t\t\tif (crypt_byte_block && skip_byte_block)\n\t\t\t\tfprintf(stderr, \" - Pattern %d:%d\", (u32) skip_byte_block, (u32) crypt_byte_block);\n\t\t\tif (def_key && def_key[0])\n\t\t\t\tfprintf(stderr, \" - MultiKey\");\n\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t\tdump_key_info(def_key, def_key_size, IsEncrypted);\n\n\t\t} else if(gf_isom_is_adobe_protection_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_adobe_protection_info(file, trackNum, 1, NULL, &scheme_type, &version, NULL);\n\t\t\tfprintf(stderr, \"\\nProtected by Adobe scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\nProtected by unknown scheme %s\\n\", gf_4cc_to_str(gf_isom_is_media_encrypted(file, trackNum, 0) ));\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t}\n\n\tif ( gf_media_get_rfc_6381_codec_name(file, trackNum, szCodec, GF_FALSE, GF_FALSE) == GF_OK) {\n\t\tfprintf(stderr, \"\\tRFC6381 Codec Parameters: %s\\n\", szCodec);\n\t}\n\n\n\tDumpMetaItem(file, 0, trackNum, \"\\tTrack Meta\");\n\n\tgf_isom_get_track_switch_group_count(file, trackNum, &alt_group, &nb_groups);\n\tif (alt_group) {\n\t\tfprintf(stderr, \"Alternate Group ID %d\\n\", alt_group);\n\t\tfor (i=0; i<nb_groups; i++) {\n\t\t\tu32 nb_crit, switchGroupID;\n\t\t\tconst u32 *criterias = gf_isom_get_track_switch_parameter(file, trackNum, i+1, &switchGroupID, &nb_crit);\n\t\t\tif (!nb_crit) {\n\t\t\t\tfprintf(stderr, \"\\tNo criteria in %s group\\n\", switchGroupID ? \"switch\" : \"alternate\");\n\t\t\t} else {\n\t\t\t\tif (switchGroupID) {\n\t\t\t\t\tfprintf(stderr, \"\\tSwitchGroup ID %d criterias: \", switchGroupID);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"\\tAlternate Group criterias: \");\n\t\t\t\t}\n\t\t\t\tfor (j=0; j<nb_crit; j++) {\n\t\t\t\t\tif (j) fprintf(stderr, \" \");\n\t\t\t\t\tfprintf(stderr, \"%s\", gf_4cc_to_str(criterias[j]) );\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch (gf_isom_has_sync_points(file, trackNum)) {\n\tcase 0:\n\t\tfprintf(stderr, \"\\tAll samples are sync\\n\");\n\t\tbreak;\n\tcase 1:\n\t{\n\t\tu32 nb_sync = gf_isom_get_sync_point_count(file, trackNum) - 1;\n\t\tif (! nb_sync) {\n\t\t\tfprintf(stderr, \"\\tOnly one sync sample\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\tAverage GOP length: %d samples\\n\", gf_isom_get_sample_count(file, trackNum) / nb_sync);\n\t\t}\n\t}\n\tbreak;\n\tcase 2:\n\t\tfprintf(stderr, \"\\tNo sync sample found\\n\");\n\t\tbreak;\n\t}\n\tfprintf(stderr, \"\\tMax sample duration: %d / %d\\n\", gf_isom_get_max_sample_delta(file, trackNum), timescale);\n\n\tif (!full_dump) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}\n\n\tdur = size = 0;\n\tmax_rate = rate = 0;\n\ttime_slice = 0;\n\tts = gf_isom_get_media_timescale(file, trackNum);\n\tcsize = gf_isom_get_constant_sample_size(file, trackNum);\n\tcdur = gf_isom_get_constant_sample_duration(file, trackNum);\n\tcount = gf_isom_get_sample_count(file, trackNum);\n\tif (csize && cdur) {\n\t\tsize = count * csize;\n\t\tdur = cdur * count;\n\t} else {\n\n\t\tfor (j=0; j<count; j++) {\n\t\t\tGF_ISOSample *samp;\n\t\t\tif (is_od_track) {\n\t\t\t\tsamp = gf_isom_get_sample(file, trackNum, j+1, NULL);\n\t\t\t} else {\n\t\t\t\tsamp = gf_isom_get_sample_info(file, trackNum, j+1, NULL, NULL);\n\t\t\t}\n\t\t\tif (!samp) {\n\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to fetch sample %d\\n\", j+1));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdur = samp->DTS+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; j<count; j++) {\n\t\t\tgf_isom_get_chapter(file, trackNum, j+1, &time, &name);\n\t\t\tfprintf(stderr, \"\\tChapter #%d - %s - \\\"%s\\\"\\n\", j+1, format_duration(time, 1000, szDur), name);\n\t\t}", "project": "gpac", "hash": 4539415702861642474065400031381230619, "size": 1040, "commit_id": "289ffce3e0d224d314f5f92a744d5fe35999f20b", "message": "fixed #1767 (fuzz)", "target": 0, "dataset": "other", "idx": 243213}
  125. {"func": " void Compute(OpKernelContext* context) override {\n const auto& input = context->input(0);\n auto flat_in = input.flat<tstring>();\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<int32>()();\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<T>();\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<const T*>(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<const char*>(flat_in(i).data());\n char* out_data_bytes = reinterpret_cast<char*>(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}
  126. {"func": " void Compute(OpKernelContext* context) override {\n const auto& input = context->input(0);\n auto flat_in = input.flat<tstring>();\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<int32>()();\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<T>();\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<size_t>(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<const char*>(flat_in(i).data());\n char* out_data_bytes = reinterpret_cast<char*>(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}
  127. {"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}
  128. {"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}
  129. {"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<Tidx>();\n\n // Chek to make sure indices is not out of boundary\n Eigen::Tensor<Tidx, 0, Eigen::RowMajor> dims_prod_eigen = dims.prod();\n Tidx dims_prod = dims_prod_eigen();\n const Tidx* indices = indices_tensor.flat<Tidx>().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<bool, 1> reverse({true});\n\n Tensor strides_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum<Tidx>::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_tensor));\n\n auto strides = strides_tensor.vec<Tidx>();\n strides = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer<Tidx>(), false)\n .reverse(reverse);\n\n Tensor strides_shifted_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum<Tidx>::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_shifted_tensor));\n\n auto strides_shifted = strides_shifted_tensor.vec<Tidx>();\n strides_shifted = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer<Tidx>(), 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<Tidx>();\n\n output = output.constant(indices_tensor.scalar<Tidx>()());\n output = output.binaryExpr(strides, mod_op<Tidx>()) / 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<Tidx>();\n\n Eigen::array<Eigen::Index, 2> reshape{\n {static_cast<Eigen::Index>(dims_tensor.NumElements()), 1}};\n Eigen::array<Eigen::Index, 2> bcast(\n {1, static_cast<Eigen::Index>(indices_tensor.NumElements())});\n Eigen::array<Eigen::Index, 2> indices_reshape{\n {1, static_cast<Eigen::Index>(indices_tensor.NumElements())}};\n Eigen::array<Eigen::Index, 2> indices_bcast(\n {static_cast<Eigen::Index>(dims_tensor.NumElements()), 1});\n\n output = indices_tensor.vec<Tidx>()\n .reshape(indices_reshape)\n .broadcast(indices_bcast);\n output = output.binaryExpr(strides.reshape(reshape).broadcast(bcast),\n mod_op<Tidx>()) /\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}
  130. {"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<Tidx>();\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<Tidx, 0, Eigen::RowMajor> dims_prod_eigen = dims.prod();\n Tidx dims_prod = dims_prod_eigen();\n const Tidx* indices = indices_tensor.flat<Tidx>().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<bool, 1> reverse({true});\n\n Tensor strides_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum<Tidx>::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_tensor));\n\n auto strides = strides_tensor.vec<Tidx>();\n strides = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer<Tidx>(), false)\n .reverse(reverse);\n\n Tensor strides_shifted_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum<Tidx>::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_shifted_tensor));\n\n auto strides_shifted = strides_shifted_tensor.vec<Tidx>();\n strides_shifted = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer<Tidx>(), 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<Tidx>();\n\n output = output.constant(indices_tensor.scalar<Tidx>()());\n output = output.binaryExpr(strides, mod_op<Tidx>()) / 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<Tidx>();\n\n Eigen::array<Eigen::Index, 2> reshape{\n {static_cast<Eigen::Index>(dims_tensor.NumElements()), 1}};\n Eigen::array<Eigen::Index, 2> bcast(\n {1, static_cast<Eigen::Index>(indices_tensor.NumElements())});\n Eigen::array<Eigen::Index, 2> indices_reshape{\n {1, static_cast<Eigen::Index>(indices_tensor.NumElements())}};\n Eigen::array<Eigen::Index, 2> indices_bcast(\n {static_cast<Eigen::Index>(dims_tensor.NumElements()), 1});\n\n output = indices_tensor.vec<Tidx>()\n .reshape(indices_reshape)\n .broadcast(indices_bcast);\n output = output.binaryExpr(strides.reshape(reshape).broadcast(bcast),\n mod_op<Tidx>()) /\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}
  131. {"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, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\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->oti<GF_CODECID_LAST_MPEG4_MAPPING)) {\n\t\tsprintf(nhml, \"streamType=\\\"%d\\\" objectTypeIndication=\\\"%d\\\" \", ctx->streamtype, 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}
  132. {"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, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\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->oti<GF_CODECID_LAST_MPEG4_MAPPING)) {\n\t\tsprintf(nhml, \"streamType=\\\"%d\\\" objectTypeIndication=\\\"%d\\\" \", ctx->streamtype, 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}
  133. {"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;i<val_1;i++) {\n int c = avio_r8(pb);\n if (avio_feof(pb))\n return AVERROR_EOF;\n for (j=0;j<c;j++) {\n if (avio_feof(pb))\n return AVERROR_EOF;\n avio_r8(pb); // val_3\n avio_r8(pb); // val_4\n }\n }\n\n avio_r8(pb); // num_streams\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_5\n\n avio_r8(pb); // '2'\n num_video = avio_r8(pb);\n\n avio_seek(pb, off, SEEK_SET);\n if (num_video != 1) {\n av_log(s, AV_LOG_ERROR, \"number of video tracks %d is not 1\\n\", num_video);\n return AVERROR_PATCHWELCOME;\n }\n\n for (i = 0; i < num_video; i++) {\n AVStream *st = avformat_new_stream(s, NULL);\n int num, den;\n\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = 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;i<viv->num_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 <michael@niedermayer.cc>", "target": 1, "dataset": "other", "idx": 196768}
  134. {"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;i<val_1;i++) {\n int c = avio_r8(pb);\n if (avio_feof(pb))\n return AVERROR_EOF;\n for (j=0;j<c;j++) {\n if (avio_feof(pb))\n return AVERROR_EOF;\n avio_r8(pb); // val_3\n avio_r8(pb); // val_4\n }\n }\n\n avio_r8(pb); // num_streams\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_5\n\n avio_r8(pb); // '2'\n num_video = avio_r8(pb);\n\n avio_seek(pb, off, SEEK_SET);\n if (num_video != 1) {\n av_log(s, AV_LOG_ERROR, \"number of video tracks %d is not 1\\n\", num_video);\n return AVERROR_PATCHWELCOME;\n }\n\n for (i = 0; i < num_video; i++) {\n AVStream *st = avformat_new_stream(s, NULL);\n int num, den;\n\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = 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;i<viv->num_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 <michael@niedermayer.cc>", "target": 0, "dataset": "other", "idx": 244426}
  135. {"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}
  136. {"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}
  137. {"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<int32>();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat<SPLITS_TYPE>();\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<tstring>();\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}
  138. {"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<int32>();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat<SPLITS_TYPE>();\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<tstring>();\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}
  139. {"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<T>()();\n auto max_val = input_max_tensor.scalar<T>()();\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<T>::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_max_tensor));\n }\n\n if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_,\n range_given_, &input_min_tensor, &input_max_tensor, round_mode_,\n narrow_range_, output->flat<T>());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(),\n input.template flat_inner_outer_dims<T, 3>(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<T, 3>(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}
  140. {"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<T>::value, TensorShape());\n Tensor input_max_tensor(DataTypeToEnum<T>::value, TensorShape());\n // Initialize the tensors with the values in the Attrs.\n input_min_tensor.template scalar<T>()() = static_cast<T>(input_min_);\n input_max_tensor.template scalar<T>()() = static_cast<T>(input_max_);\n\n functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> functor;\n functor(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, /*narrow_range=*/false, output->flat<T>());\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}
  141. {"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<T>();\n auto argmax_flat = argmax.flat<int64>();\n auto grad_in_flat = grad_in.flat<T>();\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}
  142. {"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<T>();\n auto argmax_flat = argmax.flat<int64>();\n auto grad_in_flat = grad_in.flat<T>();\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}
  143. {"func": "void UncompressElementOp::Compute(OpKernelContext* ctx) {\n Tensor tensor = ctx->input(0);\n const Variant& variant = tensor.scalar<Variant>()();\n const CompressedElement* compressed = variant.get<CompressedElement>();\n\n std::vector<Tensor> 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}
  144. {"func": "void UncompressElementOp::Compute(OpKernelContext* ctx) {\n Tensor tensor = ctx->input(0);\n const Variant& variant = tensor.scalar<Variant>()();\n const CompressedElement* compressed = variant.get<CompressedElement>();\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<Tensor> 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}
  145. {"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<SgxParams *>(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<void *>(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<void *>(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}
  146. {"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<SgxParams *>(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<void *>(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<void *>(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}
  147. {"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; i<nCol; i++, apColl++){\n *apColl = multiSelectCollSeq(pParse, p, i);\n if( 0==*apColl ){\n *apColl = db->pDfltColl;\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}
  148. {"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; i<nCol; i++, apColl++){\n *apColl = multiSelectCollSeq(pParse, p, i);\n if( 0==*apColl ){\n *apColl = db->pDfltColl;\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}
  149. {"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}
  150. {"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}
  151. {"func": "Status CompressElement(const std::vector<Tensor>& 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<TensorProto> 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}
  152. {"func": "Status CompressElement(const std::vector<Tensor>& 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<TensorProto> 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}
  153. {"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<T>();\n const auto b_values = b_values_t->vec<T>();\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<int64>();\n const auto b_shape = b_shape_t->flat<int64>();\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<int64>();\n const auto b_indices_mat = b_indices_t->matrix<int64>();\n std::vector<T> a_augmented_values, b_augmented_values;\n std::vector<std::pair<bool, int64>> 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<int64>();\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<Eigen::Tensor<const T, 1, Eigen::RowMajor>,\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<T>().device(ctx->eigen_device<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}
  154. {"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<T>();\n const auto b_values = b_values_t->vec<T>();\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<int64>();\n const auto b_shape = b_shape_t->flat<int64>();\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<int64>();\n const auto b_indices_mat = b_indices_t->matrix<int64>();\n std::vector<T> a_augmented_values, b_augmented_values;\n std::vector<std::pair<bool, int64>> 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<int64>();\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<Eigen::Tensor<const T, 1, Eigen::RowMajor>,\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<T>().device(ctx->eigen_device<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}
  155. {"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 <yavlasov@google.com>", "target": 1, "dataset": "other", "idx": 196858}
  156. {"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 <yavlasov@google.com>", "target": 0, "dataset": "other", "idx": 246616}
  157. {"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<numdefaults ; i++)\n\t*defaults[i].location = defaults[i].defaultvalue;\n \n // check for a custom default file\n i = M_CheckParm (\"-config\");\n if (i && i<myargc-1)\n {\n\tdefaultfile = myargv[i+1];\n\tprintf (\"\tdefault file: %s\\n\",defaultfile);\n }\n else\n\tdefaultfile = basedefault;\n \n // read the file in, overriding any set defaults\n f = fopen (defaultfile, \"r\");\n if (f)\n {\n\twhile (!feof(f))\n\t{\n\t isstring = false;\n\t if (fscanf (f, \"%79s %[^\\n]\\n\", def, strparm) == 2)\n\t {\n\t\tif (strparm[0] == '\"')\n\t\t{\n\t\t // get a string default\n\t\t isstring = true;\n\t\t len = strlen(strparm);\n\t\t newstring = (char *) malloc(len);\n\t\t strparm[len-1] = 0;\n\t\t strcpy(newstring, strparm+1);\n\t\t}\n\t\telse if (strparm[0] == '0' && strparm[1] == 'x')\n\t\t sscanf(strparm+2, \"%x\", &parm);\n\t\telse\n\t\t sscanf(strparm, \"%i\", &parm);\n\t\tfor (i=0 ; i<numdefaults ; i++)\n\t\t if (!strcmp(def, defaults[i].name))\n\t\t {\n\t\t\tif (!isstring)\n\t\t\t *defaults[i].location = parm;\n\t\t\telse\n\t\t\t *defaults[i].location =\n\t\t\t\t(int) newstring;\n\t\t\tbreak;\n\t\t }\n\t }\n\t}\n\t\t\n\tfclose (f);\n }\n\n for (i = 0; i < numdefaults; i++)\n {\n if (defaults[i].scantranslate)\n {\n parm = *defaults[i].location;\n defaults[i].untranslated = parm;\n *defaults[i].location = scantokey[parm];\n }\n }\n}", "project": "doom-vanille", "hash": 82891971845625363789583776832370969270, "size": 74, "commit_id": "8a6d9a02fa991a91ff90ccdc73b5ceabaa6cb9ec", "message": "Fix buffer overflow in M_LoadDefaults\n\nToo much data will most likely result in a crash or freeze, but you can overwrite the stack which can be used to do an arbitrary code execution. (https://twitter.com/notrevenant/status/1268654123903340544)", "target": 1, "dataset": "other", "idx": 196884}
  158. {"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<numdefaults ; i++)\n\t*defaults[i].location = defaults[i].defaultvalue;\n \n // check for a custom default file\n i = M_CheckParm (\"-config\");\n if (i && i<myargc-1)\n {\n\tdefaultfile = myargv[i+1];\n\tprintf (\"\tdefault file: %s\\n\",defaultfile);\n }\n else\n\tdefaultfile = basedefault;\n \n // read the file in, overriding any set defaults\n f = fopen (defaultfile, \"r\");\n if (f)\n {\n\twhile (!feof(f))\n\t{\n\t isstring = false;\n\t if (fscanf (f, \"%79s %99[^\\n]\\n\", def, strparm) == 2)\n\t {\n\t\tif (strparm[0] == '\"')\n\t\t{\n\t\t // get a string default\n\t\t isstring = true;\n\t\t len = strlen(strparm);\n\t\t newstring = (char *) malloc(len);\n\t\t strparm[len-1] = 0;\n\t\t strcpy(newstring, strparm+1);\n\t\t}\n\t\telse if (strparm[0] == '0' && strparm[1] == 'x')\n\t\t sscanf(strparm+2, \"%x\", &parm);\n\t\telse\n\t\t sscanf(strparm, \"%i\", &parm);\n\t\tfor (i=0 ; i<numdefaults ; i++)\n\t\t if (!strcmp(def, defaults[i].name))\n\t\t {\n\t\t\tif (!isstring)\n\t\t\t *defaults[i].location = parm;\n\t\t\telse\n\t\t\t *defaults[i].location =\n\t\t\t\t(int) newstring;\n\t\t\tbreak;\n\t\t }\n\t }\n\t}\n\t\t\n\tfclose (f);\n }\n\n for (i = 0; i < numdefaults; i++)\n {\n if (defaults[i].scantranslate)\n {\n parm = *defaults[i].location;\n defaults[i].untranslated = parm;\n *defaults[i].location = scantokey[parm];\n }\n }\n}", "project": "doom-vanille", "hash": 235405443936260339657459276709067885020, "size": 74, "commit_id": "8a6d9a02fa991a91ff90ccdc73b5ceabaa6cb9ec", "message": "Fix buffer overflow in M_LoadDefaults\n\nToo much data will most likely result in a crash or freeze, but you can overwrite the stack which can be used to do an arbitrary code execution. (https://twitter.com/notrevenant/status/1268654123903340544)", "target": 0, "dataset": "other", "idx": 247279}
  159. {"func": " void Compute(OpKernelContext* context) override {\n typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n ConstEigenMatrixMap;\n typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\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<int> input_size(tensor_in_and_out_dims);\n std::vector<int> 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<int>(std::floor(input_size[i] / pooling_ratio_[i]));\n DCHECK_GT(output_size[i], 0);\n }\n\n // Generate pooling sequence.\n std::vector<int64> row_cum_seq;\n std::vector<int64> 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<int64>(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<int64>(col_cum_seq.size())}),\n &output_col_seq_tensor));\n\n ConstEigenMatrixMap in_mat(tensor_in.flat<T>().data(), input_size[3],\n input_size[2] * input_size[1] * input_size[0]);\n\n EigenMatrixMap out_mat(output_tensor->flat<T>().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<T, Eigen::Dynamic, 1> 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<int64>();\n auto output_col_seq_flat = output_col_seq_tensor->flat<int64>();\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}
  160. {"func": " void Compute(OpKernelContext* context) override {\n typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n ConstEigenMatrixMap;\n typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\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<int> input_size(tensor_in_and_out_dims);\n std::vector<int> 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<int>(std::floor(input_size[i] / pooling_ratio_[i]));\n DCHECK_GT(output_size[i], 0);\n }\n\n // Generate pooling sequence.\n std::vector<int64> row_cum_seq;\n std::vector<int64> 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<int64>(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<int64>(col_cum_seq.size())}),\n &output_col_seq_tensor));\n\n ConstEigenMatrixMap in_mat(tensor_in.flat<T>().data(), input_size[3],\n input_size[2] * input_size[1] * input_size[0]);\n\n EigenMatrixMap out_mat(output_tensor->flat<T>().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<T, Eigen::Dynamic, 1> 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<int64>();\n auto output_col_seq_flat = output_col_seq_tensor->flat<int64>();\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}
  161. {"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}
  162. {"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}
  163. {"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<Targmax, int64>::value),\n errors::Internal(\"SpatialMaxPoolWithArgMaxHelper requires Targmax \"\n \"to be int64 when input_backprop != nullptr\"));\n }\n\n typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n ConstEigenMatrixMap;\n typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n EigenMatrixMap;\n typedef Eigen::Map<Eigen::Matrix<Targmax, Eigen::Dynamic, Eigen::Dynamic>>\n EigenIndexMatrixMap;\n\n ConstEigenMatrixMap in_mat(\n tensor_in.flat<T>().data(), params.depth,\n params.tensor_in_cols * params.tensor_in_rows * params.tensor_in_batch);\n EigenMatrixMap out_mat(\n output->flat<T>().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<Targmax>().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 = [&params, &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<T>.\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<T>::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<T>();\n auto out_arg_max_flat = output_arg_max->flat<int64>();\n auto out_backprop_flat = out_backprop.flat<T>();\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}
  164. {"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<Targmax, int64>::value),\n errors::Internal(\"SpatialMaxPoolWithArgMaxHelper requires Targmax \"\n \"to be int64 when input_backprop != nullptr\"));\n }\n\n typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n ConstEigenMatrixMap;\n typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n EigenMatrixMap;\n typedef Eigen::Map<Eigen::Matrix<Targmax, Eigen::Dynamic, Eigen::Dynamic>>\n EigenIndexMatrixMap;\n\n ConstEigenMatrixMap in_mat(\n tensor_in.flat<T>().data(), params.depth,\n params.tensor_in_cols * params.tensor_in_rows * params.tensor_in_batch);\n EigenMatrixMap out_mat(\n output->flat<T>().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<Targmax>().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 = [&params, &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<T>.\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<T>::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<T>();\n auto out_arg_max_flat = output_arg_max->flat<int64>();\n auto out_backprop_flat = out_backprop.flat<T>();\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}
  165. {"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<uint64_t, asylo::system_call::kParameterMax> 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<uint8_t, MallocDeleter> request_owner(request.As<uint8_t>());\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<uint8_t>(), 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<uint8_t, MallocDeleter> 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<void *>(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<int64_t>(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}
  166. {"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<uint64_t, asylo::system_call::kParameterMax> 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<uint8_t, MallocDeleter> request_owner(request.As<uint8_t>());\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<uint8_t>(), 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<uint8_t, MallocDeleter> 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<void *>(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<int64_t>(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}
  167. {"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}
  168. {"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}
  169. {"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; i<gf_isom_get_track_count(file); i++) {\n\t\tif (gf_isom_get_media_type(file, i+1) != GF_ISOM_MEDIA_HINT) continue;\n\t\tgf_isom_sdp_track_get(file, i+1, &sdp, &size);\n\t\tfprintf(dump, \"%s\", sdp);\n\t}\n\tfprintf(dump, \"\\n\\n\");", "project": "gpac", "hash": 146034260197706968005738203104188095642, "size": 37, "commit_id": "ce01bd15f711d4575b7424b54b3a395ec64c1784", "message": "fixed #1566", "target": 1, "dataset": "other", "idx": 196997}
  170. {"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\tif (sdp && size)\n\t\tfprintf(dump, \"%s\", sdp);\n\tfprintf(dump, \"\\r\\n\");\n\n\t//then tracks\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (gf_isom_get_media_type(file, i+1) != GF_ISOM_MEDIA_HINT) continue;\n\t\tgf_isom_sdp_track_get(file, i+1, &sdp, &size);\n\t\tfprintf(dump, \"%s\", sdp);\n\t}\n\tfprintf(dump, \"\\n\\n\");", "project": "gpac", "hash": 129968796869173739557009867841578254601, "size": 38, "commit_id": "ce01bd15f711d4575b7424b54b3a395ec64c1784", "message": "fixed #1566", "target": 0, "dataset": "other", "idx": 249539}
  171. {"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": 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}
  172. {"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}
  173. {"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<int32>()(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<int32>()(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<int32>();\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<Device, T>();\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<Device>(), num_batches,\n samples_per_batch, num_elements, means_tensor.flat<T>(),\n stddevs_tensor.flat<T>(), minvals_tensor.flat<T>(),\n maxvals_tensor.flat<T>(), rng, samples_tensor->flat<T>());\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}
  174. {"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<int32>()(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<int32>()(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<int32>();\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<Device, T>();\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<Device>(), num_batches,\n samples_per_batch, num_elements, means_tensor.flat<T>(),\n stddevs_tensor.flat<T>(), minvals_tensor.flat<T>(),\n maxvals_tensor.flat<T>(), rng, samples_tensor->flat<T>());\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}
  175. {"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}
  176. {"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}
  177. {"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<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n ConstEigenMatrixMap;\n typedef Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>>\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<int64>();\n auto col_seq_tensor_flat = col_seq_tensor.flat<int64>();\n auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat<int64>();\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<double>::v(), in_shape,\n &in_backprop_tensor_temp));\n in_backprop_tensor_temp.flat<double>().setZero();\n // Transform 4D tensor to 2D matrix.\n EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n in_backprop_tensor_temp.flat<double>().data(), in_depth,\n in_cols * in_rows * in_batch);\n ConstEigenMatrixMap out_backprop_mat(out_backprop.flat<T>().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<double>(\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<T>();\n auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat<double>();\n for (int64 i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n in_backprop_tensor_flat(i) =\n static_cast<T>(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}
  178. {"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<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n ConstEigenMatrixMap;\n typedef Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>>\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<int64>();\n auto col_seq_tensor_flat = col_seq_tensor.flat<int64>();\n auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat<int64>();\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<double>::v(), in_shape,\n &in_backprop_tensor_temp));\n in_backprop_tensor_temp.flat<double>().setZero();\n // Transform 4D tensor to 2D matrix.\n EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n in_backprop_tensor_temp.flat<double>().data(), in_depth,\n in_cols * in_rows * in_batch);\n ConstEigenMatrixMap out_backprop_mat(out_backprop.flat<T>().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<double>(\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<T>();\n auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat<double>();\n for (int64 i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n in_backprop_tensor_flat(i) =\n static_cast<T>(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}
  179. {"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 <sjg@chromium.org>\nReported-by: Bruce Monroe <bruce.monroe@intel.com>\nReported-by: Arie Haenel <arie.haenel@intel.com>\nReported-by: Julien Lenoir <julien.lenoir@intel.com>", "target": 1, "dataset": "other", "idx": 197162}
  180. {"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 <sjg@chromium.org>\nReported-by: Bruce Monroe <bruce.monroe@intel.com>\nReported-by: Arie Haenel <arie.haenel@intel.com>\nReported-by: Julien Lenoir <julien.lenoir@intel.com>", "target": 0, "dataset": "other", "idx": 254234}
  181. {"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}
  182. {"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}
  183. {"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}
  184. {"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}
  185. {"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<int32>& dilations, const std::vector<int32>& strides,\n Padding padding, absl::Span<const int64> 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}
  186. {"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<int32>& dilations, const std::vector<int32>& strides,\n Padding padding, absl::Span<const int64> 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}
  187. {"func": "std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)\n{\n\tstd::vector<GetLengthType> 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<MAX_EFFECTS> forbiddenCommands;\n\tstd::bitset<MAX_VOLCMDS> 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<ORDERINDEX>(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<uint8>(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<uint8>(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<uint8>(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<uint8>(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<double>(rowDuration) / static_cast<double>(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<SmpLength>(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<double, int> 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<MAX_MIXPLUGINS> plugSetProgram;\n\t\t\tfor(const auto &param : 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}
  188. {"func": "std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)\n{\n\tstd::vector<GetLengthType> 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<MAX_EFFECTS> forbiddenCommands;\n\tstd::bitset<MAX_VOLCMDS> 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<ORDERINDEX>(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<uint8>(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<uint8>(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<uint8>(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<uint8>(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<double>(rowDuration) / static_cast<double>(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<SmpLength>(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<double, int> 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<MAX_MIXPLUGINS> plugSetProgram;\n\t\t\tfor(const auto &param : 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}
  189. {"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}
  190. {"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}
  191. {"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}
  192. {"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}
  193. {"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 (&copy));\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 <smcv@collabora.com>\n(cherry picked from commit 46b3ede5241561c7d588951048c687c5075a3eac)", "target": 1, "dataset": "other", "idx": 197260}
  194. {"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 (&copy));\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 <smcv@collabora.com>\n(cherry picked from commit 46b3ede5241561c7d588951048c687c5075a3eac)", "target": 0, "dataset": "other", "idx": 256099}
  195. {"func": "Status SparseTensorToCSRSparseMatrixCPUFunctor::operator()(\n const int64 batch_size, const int num_rows,\n TTypes<int64>::ConstMatrix indices, TTypes<int32>::Vec batch_ptr,\n TTypes<int32>::Vec csr_row_ptr, TTypes<int32>::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}
  196. {"func": "Status SparseTensorToCSRSparseMatrixCPUFunctor::operator()(\n const int64 batch_size, const int num_rows,\n TTypes<int64>::ConstMatrix indices, TTypes<int32>::Vec batch_ptr,\n TTypes<int32>::Vec csr_row_ptr, TTypes<int32>::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}
  197. {"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<char>(output);\n const char* value_raw = GetTensorData<char>(value);\n const int32_t* lookup_data = GetTensorData<int32_t>(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}
  198. {"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<char>(output);\n const char* value_raw = GetTensorData<char>(value);\n const int32_t* lookup_data = GetTensorData<int32_t>(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}
  199. {"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 <gorcunov@gmail.com>", "target": 1, "dataset": "other", "idx": 197360}
  200. {"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 <gorcunov@gmail.com>", "target": 0, "dataset": "other", "idx": 257477}
  201. {"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 <josephsutton@catalyst.net.nz>\nReviewed-by: Andreas Schneider <asn@samba.org>", "target": 1, "dataset": "other", "idx": 197396}
  202. {"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 <josephsutton@catalyst.net.nz>\nReviewed-by: Andreas Schneider <asn@samba.org>", "target": 0, "dataset": "other", "idx": 258087}
  203. {"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}
  204. {"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}
  205. {"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}
  206. {"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}
  207. {"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}
  208. {"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}
  209. {"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}
  210. {"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}
  211. {"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}
  212. {"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}
  213. {"func": "CallResult<bool> JSObject::putComputedWithReceiver_RJS(\n Handle<JSObject> 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<JSObject> 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<PropertyAccessor>(\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<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n CallResult<bool> 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<JSObject> 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<JSObject>(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }\n CallResult<bool> 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<HostObject>(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<uint32_t> arrayIndex;\n MutableHandle<StringPrimitive> 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<JSArray>(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}
  214. {"func": "CallResult<bool> JSObject::putComputedWithReceiver_RJS(\n Handle<JSObject> 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<JSObject> 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<PropertyAccessor>(\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<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n CallResult<bool> 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<JSObject> 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<JSObject>(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }\n CallResult<bool> 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<HostObject>(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<uint32_t> arrayIndex;\n MutableHandle<StringPrimitive> 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<JSArray>(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}
  215. {"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<int64, int64> old_row_to_new_row_map;\n std::vector<bool> 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<int64>();\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<int64, int64> old_col_to_new_col_map;\n std::vector<bool> 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<int64>();\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<tstring>()();\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<tstring>()();\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<TensorSlice> 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<float>();\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<float>();\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<float>();\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}
  216. {"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<int64, int64> old_row_to_new_row_map;\n std::vector<bool> 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<int64>();\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<int64, int64> old_col_to_new_col_map;\n std::vector<bool> 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<int64>();\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<tstring>()();\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<tstring>()();\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<TensorSlice> 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<float>();\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<float>();\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<float>();\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}
  217. {"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; i<pTabList->nSrc; 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; k<pEList->nExpr; 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( k<pEList->nExpr ){\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; k<pEList->nExpr; 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; i<pTabList->nSrc; 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; j<pTab->nCol; 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}
  218. {"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; i<pTabList->nSrc; 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; k<pEList->nExpr; 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( k<pEList->nExpr ){\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; k<pEList->nExpr; 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; i<pTabList->nSrc; 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; j<pTab->nCol; 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}
  219. {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const float input_min_float = ctx->input(1).flat<float>()(0);\n const float input_max_float = ctx->input(2).flat<float>()(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<float>().setConstant(used_min_float);\n output_max->flat<float>().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}
  220. {"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<float>()(0);\n const float input_max_float = ctx->input(2).flat<float>()(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<float>().setConstant(used_min_float);\n output_max->flat<float>().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}
  221. {"func": "int RemoveUnknownSections(void)\r\n{\r\n int a;\r\n int Modified = FALSE;\r\n for (a=0;a<SectionsRead-1;){\r\n switch(Sections[a].Type){\r\n case M_SOF0:\r\n case M_SOF1:\r\n case M_SOF2:\r\n case M_SOF3:\r\n case M_SOF5:\r\n case M_SOF6:\r\n case M_SOF7:\r\n case M_SOF9:\r\n case M_SOF10:\r\n case M_SOF11:\r\n case M_SOF13:\r\n case M_SOF14:\r\n case M_SOF15:\r\n case M_SOI:\r\n case M_EOI:\r\n case M_SOS:\r\n case M_JFIF:\r\n case M_EXIF:\r\n case M_XMP:\r\n case M_COM:\r\n case M_DQT:\r\n case M_DHT:\r\n case M_DRI:\r\n case M_IPTC:\r\n // keep.\r\n a++;\r\n break;\r\n default:\r\n // Unknown. Delete.\r\n free (Sections[a].Data);\r\n // Move succeding sections back by one to close space in array.\r\n memmove(Sections+a, Sections+a+1, sizeof(Section_t) * (SectionsRead-a));\r\n SectionsRead -= 1;\r\n Modified = TRUE;\r\n }\r\n }\r\n return Modified;\r\n}\r", "project": "jhead", "hash": 99506882083525381430266022733946342388, "size": 44, "commit_id": "b8d78e5ec982e86cdd70ebfc1ebbb2273c982eea", "message": "Same error as previous checking in different function", "target": 1, "dataset": "other", "idx": 197609}
  222. {"func": "int RemoveUnknownSections(void)\r\n{\r\n int a;\r\n int Modified = FALSE;\r\n for (a=0;a<SectionsRead-1;){\r\n switch(Sections[a].Type){\r\n case M_SOF0:\r\n case M_SOF1:\r\n case M_SOF2:\r\n case M_SOF3:\r\n case M_SOF5:\r\n case M_SOF6:\r\n case M_SOF7:\r\n case M_SOF9:\r\n case M_SOF10:\r\n case M_SOF11:\r\n case M_SOF13:\r\n case M_SOF14:\r\n case M_SOF15:\r\n case M_SOI:\r\n case M_EOI:\r\n case M_SOS:\r\n case M_JFIF:\r\n case M_EXIF:\r\n case M_XMP:\r\n case M_COM:\r\n case M_DQT:\r\n case M_DHT:\r\n case M_DRI:\r\n case M_IPTC:\r\n // keep.\r\n a++;\r\n break;\r\n default:\r\n // Unknown. Delete.\r\n free (Sections[a].Data);\r\n // Move succeding sections back by one to close space in array.\r\n memmove(Sections+a, Sections+a+1, sizeof(Section_t) * (SectionsRead-a-1));\r\n SectionsRead -= 1;\r\n Modified = TRUE;\r\n }\r\n }\r\n return Modified;\r\n}\r", "project": "jhead", "hash": 331719028316894674358311993067451848682, "size": 44, "commit_id": "b8d78e5ec982e86cdd70ebfc1ebbb2273c982eea", "message": "Same error as previous checking in different function", "target": 0, "dataset": "other", "idx": 261985}
  223. {"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. */\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}
  224. {"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}
  225. {"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<int32>();\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<int64>();\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<PhiloxRandom, double> Normal;\n typedef random::UniformDistribution<PhiloxRandom, double> 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<T>().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<T>().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<double>(alpha_flat[alpha_idx]);\n\n DISABLE_FLOAT_EQUALITY_WARNING\n if (alpha == static_cast<double>(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<T>(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<T>(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}
  226. {"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<int32>();\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<int64>();\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<PhiloxRandom, double> Normal;\n typedef random::UniformDistribution<PhiloxRandom, double> 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<T>().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<T>().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<double>(alpha_flat[alpha_idx]);\n\n DISABLE_FLOAT_EQUALITY_WARNING\n if (alpha == static_cast<double>(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<T>(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<T>(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}
  227. {"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 <burakcarikci@crypttech.com>\nSigned-off-by: Michael Niedermayer <michael@niedermayer.cc>", "target": 1, "dataset": "other", "idx": 197652}
  228. {"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 <burakcarikci@crypttech.com>\nSigned-off-by: Michael Niedermayer <michael@niedermayer.cc>", "target": 0, "dataset": "other", "idx": 262684}
  229. {"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<int32>();\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}
  230. {"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<int32>();\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}
  231. {"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<T>::value,\n errors::InvalidArgument(\n \"Asked for a CSRSparseMatrix of type \",\n DataTypeString(DataTypeToEnum<T>::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<int64>();\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}
  232. {"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<T>::value)\n return errors::InvalidArgument(\n \"Asked for a CSRSparseMatrix of type \",\n DataTypeString(DataTypeToEnum<T>::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<int64>();\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}
  233. {"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 <yonghua.huang@intel.com>", "target": 1, "dataset": "other", "idx": 197721}
  234. {"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 <yonghua.huang@intel.com>", "target": 0, "dataset": "other", "idx": 262864}
  235. {"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 <matzeton@googlemail.com>", "target": 1, "dataset": "other", "idx": 197747}
  236. {"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 <matzeton@googlemail.com>", "target": 0, "dataset": "other", "idx": 263377}
  237. {"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<struct klinux_sockaddr_un *>(\n reinterpret_cast<const struct klinux_sockaddr_un *>(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<struct klinux_sockaddr_in *>(\n reinterpret_cast<const struct klinux_sockaddr_in *>(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<struct klinux_sockaddr_in6 *>(\n reinterpret_cast<const struct klinux_sockaddr_in6 *>(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}
  238. {"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<struct klinux_sockaddr_un *>(\n reinterpret_cast<const struct klinux_sockaddr_un *>(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<struct klinux_sockaddr_in *>(\n reinterpret_cast<const struct klinux_sockaddr_in *>(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<struct klinux_sockaddr_in6 *>(\n reinterpret_cast<const struct klinux_sockaddr_in6 *>(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}
  239. {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& input = context->input(0);\n const float input_min = context->input(1).flat<float>()(0);\n const float input_max = context->input(2).flat<float>()(0);\n const Tensor& mean = context->input(3);\n const float mean_min = context->input(4).flat<float>()(0);\n const float mean_max = context->input(5).flat<float>()(0);\n const Tensor& var = context->input(6);\n const float var_min = context->input(7).flat<float>()(0);\n const float var_max = context->input(8).flat<float>()(0);\n const Tensor& beta = context->input(9);\n const float beta_min = context->input(10).flat<float>()(0);\n const float beta_max = context->input(11).flat<float>()(0);\n const Tensor& gamma = context->input(12);\n const float gamma_min = context->input(13).flat<float>()(0);\n const float gamma_max = context->input(14).flat<float>()(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<T1, T2>(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<float>()(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<float>()(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}
  240. {"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<float>()(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<float>()(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<float>()(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<float>()(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<float>()(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<float>()(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<float>()(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<float>()(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<float>()(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<float>()(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<T1, T2>(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<float>()(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<float>()(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}
  241. {"func": "ImmutableConstantOp::ImmutableConstantOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context,\n context->GetAttr(kMemoryRegionNameAttr, &region_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}
  242. {"func": "ImmutableConstantOp::ImmutableConstantOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context,\n context->GetAttr(kMemoryRegionNameAttr, &region_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}
  243. {"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}
  244. {"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}
  245. {"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}
  246. {"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}
  247. {"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}
  248. {"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}
  249. {"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<OpData*>(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<TfLiteTransposeConvParams*>(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<kernel_type>(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<kernel_type>(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<kernel_type>(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}
  250. {"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<OpData*>(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<TfLiteTransposeConvParams*>(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<kernel_type>(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<kernel_type>(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<kernel_type>(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}
  251. {"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<size_t>(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<uint64_t>(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}
  252. {"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<size_t>(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<uint64_t>(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}
  253. {"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 <jeriko.one@gmx.us> for finding and reporting this.", "target": 1, "dataset": "other", "idx": 197927}
  254. {"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 <jeriko.one@gmx.us> for finding and reporting this.", "target": 0, "dataset": "other", "idx": 265791}
  255. {"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}
  256. {"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}
  257. {"func": "inline size_t codepoint_length(const char *s8, size_t l) {\n if (l) {\n auto b = static_cast<uint8_t>(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}
  258. {"func": "inline size_t codepoint_length(const char *s8, size_t l) {\n if (l) {\n auto b = static_cast<uint8_t>(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}
  259. {"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<CPUDevice>();\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<int64>();\n const auto grad_values = grad_values_t->vec<T>();\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<T>();\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<T>()();\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<bool>();\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}
  260. {"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<CPUDevice>();\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<int64>();\n const auto grad_values = grad_values_t->vec<T>();\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<T>();\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<T>()();\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<bool>();\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}
  261. {"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; i<stbl->SampleSize->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; i<nb_pack; i++) {\n\t\tstbl->SampleSize->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}
  262. {"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; i<stbl->SampleSize->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; i<nb_pack; i++) {\n\t\tstbl->SampleSize->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}
  263. {"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<float>()(0);\n const float max_x = context->input(3).flat<float>()(0);\n const float min_y = context->input(4).flat<float>()(0);\n const float max_y = context->input(5).flat<float>()(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<T>().data();\n const T* y_data = y.flat<T>().data();\n Toutput* z_data = z->flat<Toutput>().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<T, Toutput>(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<T, Toutput>(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<T, Toutput>(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<T, Toutput>(\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<float>()(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<float>()(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}
  264. {"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<float>()(0);\n const float max_x = context->input(3).flat<float>()(0);\n const float min_y = context->input(4).flat<float>()(0);\n const float max_y = context->input(5).flat<float>()(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<T>().data();\n const T* y_data = y.flat<T>().data();\n Toutput* z_data = z->flat<Toutput>().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<T, Toutput>(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<T, Toutput>(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<T, Toutput>(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<T, Toutput>(\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<float>()(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<float>()(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}
  265. {"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<T>(op_context.on_value);\n const T off_value = *GetTensorData<T>(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<T>(op_context.output);\n const TI* indices = GetTensorData<TI>(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<int>(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}
  266. {"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<T>(op_context.on_value);\n const T off_value = *GetTensorData<T>(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<T>(op_context.output);\n const TI* indices = GetTensorData<TI>(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<int>(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}
  267. {"func": " void Compute(OpKernelContext* context) override {\n const int64 axis_input = context->input(0).scalar<int64>()();\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<int64>().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<int64>()(axis),\n errors::InvalidArgument(\"Input num_split should be between 1 \"\n \"and the splitting dimension size (\",\n input_shape.vec<int64>()(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<int64>()), &sparse_tensor));\n\n std::vector<sparse::SparseTensor> outputs;\n OP_REQUIRES_OK(context, sparse::SparseTensor::Split<T>(\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<int64>()(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}
  268. {"func": " void Compute(OpKernelContext* context) override {\n const int64 axis_input = context->input(0).scalar<int64>()();\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<int64>().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<int64>()(axis),\n errors::InvalidArgument(\"Input num_split should be between 1 \"\n \"and the splitting dimension size (\",\n input_shape.vec<int64>()(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<int64>();\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<sparse::SparseTensor> outputs;\n OP_REQUIRES_OK(context, sparse::SparseTensor::Split<T>(\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<int64>()(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}
  269. {"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; i<gf_isom_get_track_count(file); i++) {\n\t\tif (!gf_isom_is_track_in_root_od(file, i+1)) continue;\n\t\tswitch (gf_isom_get_media_type(file,i+1)) {\n\t\tcase GF_ISOM_MEDIA_OD:\n\t\t\todT = i+1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_MEDIA_SCENE:\n\t\t\tsceneT = i+1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tremove_ocr = 0;\n\tif (IOD_Profile == GF_SDP_IOD_ISMA_STRICT) {\n\t\tIOD_Profile = GF_SDP_IOD_ISMA;\n\t\tremove_ocr = 1;\n\t}\n\n\t/*if we want ISMA like iods, we need at least BIFS */\n\tif ( (IOD_Profile == GF_SDP_IOD_ISMA) && !sceneT ) return GF_BAD_PARAM;\n\n\t/*do NOT change PLs, we assume they are correct*/\n\tiod = (GF_InitialObjectDescriptor *) gf_isom_get_root_od(file);\n\tif (!iod) return GF_NOT_SUPPORTED;\n\n\t/*rewrite an IOD with good SL config - embbed data if possible*/\n\tif (IOD_Profile == GF_SDP_IOD_ISMA) {\n\t\tGF_ESD *esd;\n\t\tBool is_ok = 1;\n\t\twhile (gf_list_count(iod->ESDescriptors)) {\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; i<gf_isom_get_track_count(file); i++) {\n\t\t\t\tesd = gf_isom_get_esd(file, i+1, 1);\n\t\t\t\tif (!esd) continue;\n\t\t\t\tif (esd->decoderConfig->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}
  270. {"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; i<gf_isom_get_track_count(file); i++) {\n\t\tif (!gf_isom_is_track_in_root_od(file, i+1)) continue;\n\t\tswitch (gf_isom_get_media_type(file,i+1)) {\n\t\tcase GF_ISOM_MEDIA_OD:\n\t\t\todT = i+1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_MEDIA_SCENE:\n\t\t\tsceneT = i+1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tremove_ocr = 0;\n\tif (IOD_Profile == GF_SDP_IOD_ISMA_STRICT) {\n\t\tIOD_Profile = GF_SDP_IOD_ISMA;\n\t\tremove_ocr = 1;\n\t}\n\n\t/*if we want ISMA like iods, we need at least BIFS */\n\tif ( (IOD_Profile == GF_SDP_IOD_ISMA) && !sceneT ) return GF_BAD_PARAM;\n\n\t/*do NOT change PLs, we assume they are correct*/\n\tiod = (GF_InitialObjectDescriptor *) gf_isom_get_root_od(file);\n\tif (!iod) return GF_NOT_SUPPORTED;\n\n\t/*rewrite an IOD with good SL config - embbed data if possible*/\n\tif (IOD_Profile == GF_SDP_IOD_ISMA) {\n\t\tGF_ESD *esd;\n\t\tBool is_ok = 1;\n\t\twhile (gf_list_count(iod->ESDescriptors)) {\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; i<gf_isom_get_track_count(file); i++) {\n\t\t\t\tesd = gf_isom_get_esd(file, i+1, 1);\n\t\t\t\tif (!esd) continue;\n\t\t\t\tif (esd->decoderConfig->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}
  271. {"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}
  272. {"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}
  273. {"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}
  274. {"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}
  275. {"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}
  276. {"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}
  277. {"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}
  278. {"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}
  279. {"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<float>()(0);\n const float max_x = context->input(3).flat<float>()(0);\n const float min_y = context->input(4).flat<float>()(0);\n const float max_y = context->input(5).flat<float>()(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<T>(0.0f, min_x, max_x);\n const int32 offset_y = FloatToQuantizedUnclamped<T>(0.0f, min_y, max_y);\n const T* x_data = x.flat<T>().data();\n const T* y_data = y.flat<T>().data();\n Toutput* z_data = z->flat<Toutput>().data();\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarMultiply<T, Toutput>(context, y_data, offset_y, y.NumElements(),\n x_data[0], offset_x, z_data);\n } else if (y.NumElements() == 1) {\n ScalarMultiply<T, Toutput>(context, x_data, offset_x, x.NumElements(),\n y_data[0], offset_y, z_data);\n } else {\n VectorMultiply<T, Toutput>(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<T, Toutput>(\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<T, T, Toutput>(\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<float>()(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<float>()(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}
  280. {"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<float>()(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<float>()(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<float>()(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<float>()(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<T>(0.0f, min_x, max_x);\n const int32 offset_y = FloatToQuantizedUnclamped<T>(0.0f, min_y, max_y);\n const T* x_data = x.flat<T>().data();\n const T* y_data = y.flat<T>().data();\n Toutput* z_data = z->flat<Toutput>().data();\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarMultiply<T, Toutput>(context, y_data, offset_y, y.NumElements(),\n x_data[0], offset_x, z_data);\n } else if (y.NumElements() == 1) {\n ScalarMultiply<T, Toutput>(context, x_data, offset_x, x.NumElements(),\n y_data[0], offset_y, z_data);\n } else {\n VectorMultiply<T, Toutput>(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<T, Toutput>(\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<T, T, Toutput>(\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<float>()(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<float>()(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}
  281. {"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}
  282. {"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}
  283. {"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<float>()(0);\n const float input_max_float = ctx->input(3).flat<float>()(0);\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_min));\n output_min->flat<float>()(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<float>()(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}
  284. {"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<float>()(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<float>()(0);\n\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_min));\n output_min->flat<float>()(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<float>()(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}
  285. {"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}
  286. {"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}
  287. {"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<uint16_t>(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<uint16_t>(strlen(aNetworkName));\n\n otPbkdf2Cmac(reinterpret_cast<const uint8_t *>(aPassPhrase), static_cast<uint16_t>(strlen(aPassPhrase)),\n reinterpret_cast<const uint8_t *>(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}
  288. {"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<uint16_t>(strnlen(aPassPhrase, OT_COMMISSIONING_PASSPHRASE_MAX_SIZE + 1));\n networkNameLen = static_cast<uint8_t>(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<uint16_t>(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<const uint8_t *>(aPassPhrase), passphraseLen, reinterpret_cast<const uint8_t *>(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}
  289. {"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; i<FF_ARRAY_ELEMS(h->last_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); i<h->mb_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 <michaelni@gmx.at>", "target": 1, "dataset": "other", "idx": 198173}
  290. {"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; i<FF_ARRAY_ELEMS(h->last_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); i<h->mb_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 <michaelni@gmx.at>", "target": 0, "dataset": "other", "idx": 270122}
  291. {"func": "Status KernelAndDeviceOp::Run(\n ScopedStepContainer* step_container, const EagerKernelArgs& inputs,\n std::vector<EagerKernelRet>* outputs,\n CancellationManager* cancellation_manager,\n const absl::optional<EagerRemoteFunctionParams>& 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(&params);\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}
  292. {"func": "Status KernelAndDeviceOp::Run(\n ScopedStepContainer* step_container, const EagerKernelArgs& inputs,\n std::vector<EagerKernelRet>* outputs,\n CancellationManager* cancellation_manager,\n const absl::optional<EagerRemoteFunctionParams>& 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(&params);\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}
  293. {"func": " void Compute(OpKernelContext* ctx) override {\n const auto splits = ctx->input(0).flat<int64>();\n const auto values = ctx->input(1).flat<Tidx>();\n const Tensor& size_t = ctx->input(2);\n const auto weights = ctx->input(3).flat<T>();\n const int64 weights_size = weights.size();\n\n Tidx size = size_t.scalar<Tidx>()();\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<Device, T> fill;\n fill(ctx->eigen_device<Device>(), out_t->flat<T>());\n const auto out = out_t->matrix<T>();\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}
  294. {"func": " void Compute(OpKernelContext* ctx) override {\n const auto splits = ctx->input(0).flat<int64>();\n const auto values = ctx->input(1).flat<Tidx>();\n const Tensor& size_t = ctx->input(2);\n const auto weights = ctx->input(3).flat<T>();\n const int64 weights_size = weights.size();\n\n Tidx size = size_t.scalar<Tidx>()();\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<Device, T> fill;\n fill(ctx->eigen_device<Device>(), out_t->flat<T>());\n const auto out = out_t->matrix<T>();\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}
  295. {"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<int64>());\n gtl::InlinedVector<int64, 8> 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<int64>();\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<int64>();\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<int64> 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<T>();\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<T>::value, {num_entries});\n\n auto output_indices_t = output_indices.matrix<int64>();\n auto output_values_t = output_values.vec<T>();\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<T>::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}
  296. {"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<int64>();\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<int64, 8> 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<int64>();\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<int64> 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<T>();\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<T>::value, {num_entries});\n\n auto output_indices_t = output_indices.matrix<int64>();\n auto output_values_t = output_values.vec<T>();\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<T>::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}
  297. {"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 <lq@chinaffmpeg.org>\n(cherry picked from commit 9dfb19baeb86a8bb02c53a441682c6e9a6e104cc)", "target": 1, "dataset": "other", "idx": 198208}
  298. {"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 <lq@chinaffmpeg.org>\n(cherry picked from commit 9dfb19baeb86a8bb02c53a441682c6e9a6e104cc)", "target": 0, "dataset": "other", "idx": 270450}
  299. {"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}
  300. {"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}
  301. {"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}
  302. {"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}
  303. {"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; k<gf_list_count(mov->moov->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; k<gf_list_count(mov->moov->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; k<gf_list_count(mov->moof->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; k<gf_list_count(mov->moof->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; k<gf_list_count(mov->moof->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}
  304. {"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; k<gf_list_count(mov->moov->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; k<gf_list_count(mov->moov->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; k<gf_list_count(mov->moof->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; k<gf_list_count(mov->moof->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; k<gf_list_count(mov->moof->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}
  305. {"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 <lev@openvpn.net>\nAcked-by: Arne Schwabe <arne@rfc2549.org>\nAcked-by: Antonio Quartulli <antonio@openvpn.net>\nAcked-by: Gert Doering <gert@greenie.muc.de>\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 <gert@greenie.muc.de>", "target": 1, "dataset": "other", "idx": 198315}
  306. {"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 <lev@openvpn.net>\nAcked-by: Arne Schwabe <arne@rfc2549.org>\nAcked-by: Antonio Quartulli <antonio@openvpn.net>\nAcked-by: Gert Doering <gert@greenie.muc.de>\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 <gert@greenie.muc.de>", "target": 0, "dataset": "other", "idx": 272280}
  307. {"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; i<traf_count; i++) {\n\t\t\tGF_TrackFragmentBox *atraf = gf_list_get(moof_box->TrackList, 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; i<gf_list_count(moof_clone->TrackList); 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_start<seg_start))\n\t\t\t\tseg_start = sidx_start;\n\t\t}\n\t\tfrag_start = trak->moov->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; j<trun->sample_count; j++) {\n\t\t\tGF_Err e;\n\t\t\ts32 cts_offset=0;\n\t\t\tif (j<trun->nb_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; i<gf_list_count(trak->editBox->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; i<gf_list_count(traf->sampleGroupsDescription); 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; j<gf_list_count(groupDescs); j++) {\n\t\t\t\tnew_sgdesc = gf_list_get(groupDescs, j);\n\t\t\t\tif (new_sgdesc->grouping_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; i<gf_list_count(traf->sampleGroups); 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; j<gf_list_count(groups); j++) {\n\t\t\t\tstbl_group = gf_list_get(groups, j);\n\t\t\t\tif ((frag_group->grouping_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}
  308. {"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; i<traf_count; i++) {\n\t\t\tGF_TrackFragmentBox *atraf = gf_list_get(moof_box->TrackList, 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; i<gf_list_count(moof_clone->TrackList); 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_start<seg_start))\n\t\t\t\tseg_start = sidx_start;\n\t\t}\n\t\tfrag_start = trak->moov->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; j<trun->sample_count; j++) {\n\t\t\tGF_Err e;\n\t\t\ts32 cts_offset=0;\n\t\t\tif (j<trun->nb_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; i<gf_list_count(trak->editBox->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; i<gf_list_count(traf->sampleGroupsDescription); 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; j<gf_list_count(groupDescs); j++) {\n\t\t\t\tnew_sgdesc = gf_list_get(groupDescs, j);\n\t\t\t\tif (new_sgdesc->grouping_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; i<gf_list_count(traf->sampleGroups); 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; j<gf_list_count(groups); j++) {\n\t\t\t\tstbl_group = gf_list_get(groups, j);\n\t\t\t\tif ((frag_group->grouping_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}
  309. {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast<TfLiteConcatenationParams*>(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<int8_t> 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}
  310. {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast<TfLiteConcatenationParams*>(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<int>::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<int8_t> 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}
  311. {"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}
  312. {"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}
  313. {"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 <michael@niedermayer.cc>\n(cherry picked from commit 1812352d767ccf5431aa440123e2e260a4db2726)\nSigned-off-by: Michael Niedermayer <michael@niedermayer.cc>", "target": 1, "dataset": "other", "idx": 198372}
  314. {"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 <michael@niedermayer.cc>\n(cherry picked from commit 1812352d767ccf5431aa440123e2e260a4db2726)\nSigned-off-by: Michael Niedermayer <michael@niedermayer.cc>", "target": 0, "dataset": "other", "idx": 273279}
  315. {"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<int>(*GetTensorData<int64_t>(axis));\n } else {\n axis_value = *GetTensorData<int>(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}
  316. {"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<int>(*GetTensorData<int64_t>(axis));\n } else {\n axis_value = *GetTensorData<int>(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}
  317. {"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}
  318. {"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}
  319. {"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<INDEX_TYPE>()();\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}
  320. {"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<INDEX_TYPE>()();\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}
  321. {"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<T>();\n auto b_values = ctx->input(4).vec<T>();\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<int64>();\n const auto b_shape_flat = b_shape->flat<int64>();\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<Treal>()();\n\n // (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix<int64>();\n auto b_indices_mat = b_indices->matrix<int64>();\n std::vector<std::pair<bool, int64>> entries_to_copy; // from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector<T> 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<int64>();\n auto out_values_flat = out_values_t->vec<T>();\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}
  322. {"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<T>();\n auto b_values = ctx->input(4).vec<T>();\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<int64>();\n const auto b_shape_flat = b_shape->flat<int64>();\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<Treal>()();\n\n // (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix<int64>();\n auto b_indices_mat = b_indices->matrix<int64>();\n std::vector<std::pair<bool, int64>> entries_to_copy; // from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector<T> 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<int64>();\n auto out_values_flat = out_values_t->vec<T>();\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}
  323. {"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 <josephsutton@catalyst.net.nz>\nReviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>\n(cherry picked from commit e1ab0c43629686d1d2c0b0b2bcdc90057a792049)", "target": 1, "dataset": "other", "idx": 198425}
  324. {"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 <josephsutton@catalyst.net.nz>\nReviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>\n(cherry picked from commit e1ab0c43629686d1d2c0b0b2bcdc90057a792049)", "target": 0, "dataset": "other", "idx": 274270}
  325. {"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<int32>::max()),\n errors::InvalidArgument(\"image cannot have >= int32 max elements\"));\n const int32 height = static_cast<int32>(image.dim_size(0));\n const int32 width = static_cast<int32>(image.dim_size(1));\n const int32 channels = static_cast<int32>(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<int32>::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<uint8>().data(), width, height,\n width * channels, channels, desired_channel_bits_,\n compression_, &output->scalar<tstring>()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n } else {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat<uint16>().data(), width, height,\n width * channels * 2, channels, desired_channel_bits_,\n compression_, &output->scalar<tstring>()(), 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}
  326. {"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<int32>::max()),\n errors::InvalidArgument(\"image cannot have >= int32 max elements\"));\n const int32 height = static_cast<int32>(image.dim_size(0));\n const int32 width = static_cast<int32>(image.dim_size(1));\n const int32 channels = static_cast<int32>(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<int32>::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<uint8>().data(), width, height,\n width * channels, channels, desired_channel_bits_,\n compression_, &output->scalar<tstring>()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n } else {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat<uint16>().data(), width, height,\n width * channels * 2, channels, desired_channel_bits_,\n compression_, &output->scalar<tstring>()(), 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}
  327. {"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}
  328. {"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}
  329. {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast<TfLiteSpaceToDepthParams*>(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}
  330. {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast<TfLiteSpaceToDepthParams*>(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}
  331. {"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; i<nb_stsd; i++) {\n\t\t\tGF_ProtectionSchemeInfoBox *a_sinf;\n\t\t\tGF_SampleEntryBox *sentry=NULL;\n\t\t\tif (i+1==sampleDescriptionIndex) continue;\n\t\t\tsentry = gf_list_get(trak->Media->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; i<count; i++) {\n\t\t\tGF_SampleGroupDescriptionBox *sgdesc = (GF_SampleGroupDescriptionBox*)gf_list_get(trak->Media->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}
  332. {"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; i<nb_stsd; i++) {\n\t\t\tGF_ProtectionSchemeInfoBox *a_sinf;\n\t\t\tGF_SampleEntryBox *sentry=NULL;\n\t\t\tif (i+1==sampleDescriptionIndex) continue;\n\t\t\tsentry = gf_list_get(trak->Media->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; i<count; i++) {\n\t\t\tGF_SampleGroupDescriptionBox *sgdesc = (GF_SampleGroupDescriptionBox*)gf_list_get(trak->Media->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}
  333. {"func": "inline Status SparseTensor::Split(const SparseTensor& input_tensor,\n const int split_dim, const int num_split,\n std::vector<SparseTensor>* result) {\n std::vector<Tensor> output_indices;\n std::vector<Tensor> output_values;\n std::vector<TensorShape> output_shapes;\n output_indices.reserve(num_split);\n output_values.reserve(num_split);\n output_shapes.reserve(num_split);\n\n std::vector<typename TTypes<int64>::Matrix> output_indices_t;\n std::vector<typename TTypes<T>::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<T>();\n auto input_indices_t = input_tensor.indices().matrix<int64>();\n\n std::vector<int> 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<int64>()(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<T>::v(),\n TensorShape({num_values[i]}));\n output_shapes.emplace_back(input_tensor.shape());\n output_indices_t.emplace_back(output_indices[i].matrix<int64>());\n output_values_t.emplace_back(output_values[i].vec<T>());\n const int size = GetSliceShape(i, split_size, residual);\n output_shapes[i].set_dim(split_dim, size);\n }\n\n std::vector<int> 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}
  334. {"func": "inline Status SparseTensor::Split(const SparseTensor& input_tensor,\n const int split_dim, const int num_split,\n std::vector<SparseTensor>* result) {\n std::vector<Tensor> output_indices;\n std::vector<Tensor> output_values;\n std::vector<TensorShape> output_shapes;\n output_indices.reserve(num_split);\n output_values.reserve(num_split);\n output_shapes.reserve(num_split);\n\n std::vector<typename TTypes<int64>::Matrix> output_indices_t;\n std::vector<typename TTypes<T>::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<T>();\n auto input_indices_t = input_tensor.indices().matrix<int64>();\n\n std::vector<int> 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<int64>()(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<T>::v(),\n TensorShape({num_values[i]}));\n output_shapes.emplace_back(input_tensor.shape());\n output_indices_t.emplace_back(output_indices[i].matrix<int64>());\n output_values_t.emplace_back(output_values[i].vec<T>());\n const int size = GetSliceShape(i, split_size, residual);\n output_shapes[i].set_dim(split_dim, size);\n }\n\n std::vector<int> 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}
  335. {"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}
  336. {"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}
  337. {"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<int>::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 <cary@ilm.com>\r\n\r\n* Compute level size with 64 bits to avoid overflow\r\n\r\nSigned-off-by: Cary Phillips <cary@ilm.com>", "target": 1, "dataset": "other", "idx": 198573}
  338. {"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 <cary@ilm.com>\r\n\r\n* Compute level size with 64 bits to avoid overflow\r\n\r\nSigned-off-by: Cary Phillips <cary@ilm.com>", "target": 0, "dataset": "other", "idx": 277662}
  339. {"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}
  340. {"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}
  341. {"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) <zheyuma97@gmail.com>\nSigned-off-by: Zheyu Ma <zheyuma97@gmail.com>\nCc: Greg Kroah-Hartman <greg@kroah.com>\nCc: Stefan Richter <stefanr@s5r6.in-berlin.de>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 198639}
  342. {"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) <zheyuma97@gmail.com>\nSigned-off-by: Zheyu Ma <zheyuma97@gmail.com>\nCc: Greg Kroah-Hartman <greg@kroah.com>\nCc: Stefan Richter <stefanr@s5r6.in-berlin.de>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 279632}
  343. {"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}
  344. {"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}
  345. {"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 <jra@samba.org>", "target": 1, "dataset": "other", "idx": 198641}
  346. {"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 <jra@samba.org>", "target": 0, "dataset": "other", "idx": 279699}
  347. {"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}
  348. {"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}
  349. {"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 <jannh@google.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 198668}
  350. {"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 <jannh@google.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 280052}
  351. {"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 <u9012063@gmail.com>\nSigned-off-by: Ilya Maximets <i.maximets@ovn.org>", "target": 1, "dataset": "other", "idx": 198672}
  352. {"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 <u9012063@gmail.com>\nSigned-off-by: Ilya Maximets <i.maximets@ovn.org>", "target": 0, "dataset": "other", "idx": 280721}
  353. {"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 <mika.kuoppala@linux.intel.com>\nSigned-off-by: Akeem G Abodunrin <akeem.g.abodunrin@intel.com>\nCc: Kumar Valsan Prathap <prathap.kumar.valsan@intel.com>\nCc: Chris Wilson <chris.p.wilson@intel.com>\nCc: Balestrieri Francesco <francesco.balestrieri@intel.com>\nCc: Bloomfield Jon <jon.bloomfield@intel.com>\nCc: Dutt Sudeep <sudeep.dutt@intel.com>", "target": 1, "dataset": "other", "idx": 198697}
  354. {"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 <mika.kuoppala@linux.intel.com>\nSigned-off-by: Akeem G Abodunrin <akeem.g.abodunrin@intel.com>\nCc: Kumar Valsan Prathap <prathap.kumar.valsan@intel.com>\nCc: Chris Wilson <chris.p.wilson@intel.com>\nCc: Balestrieri Francesco <francesco.balestrieri@intel.com>\nCc: Bloomfield Jon <jon.bloomfield@intel.com>\nCc: Dutt Sudeep <sudeep.dutt@intel.com>", "target": 0, "dataset": "other", "idx": 281552}
  355. {"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}
  356. {"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}
  357. {"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}
  358. {"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}
  359. {"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}
  360. {"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}
  361. {"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}
  362. {"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}
  363. {"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}
  364. {"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}
  365. {"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}
  366. {"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}
  367. {"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}
  368. {"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}
  369. {"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}
  370. {"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}
  371. {"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(&current->sighand->siglock);\n\tif (!(clone_flags & CLONE_THREAD))\n\t\thlist_add_head(&delayed.node, &current->signal->multiprocess);\n\trecalc_sigpending();\n\tspin_unlock_irq(&current->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(&current->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(&current->signal->live);\n\t\t\trefcount_inc(&current->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(&current->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(&current->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(&current->sighand->siglock);\n\thlist_del_init(&delayed.node);\n\tspin_unlock_irq(&current->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 <eddy_wu@trendmicro.com>\nAcked-by: Oleg Nesterov <oleg@redhat.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 199840}
  372. {"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(&current->sighand->siglock);\n\tif (!(clone_flags & CLONE_THREAD))\n\t\thlist_add_head(&delayed.node, &current->signal->multiprocess);\n\trecalc_sigpending();\n\tspin_unlock_irq(&current->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(&current->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(&current->signal->live);\n\t\t\trefcount_inc(&current->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(&current->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(&current->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(&current->sighand->siglock);\n\thlist_del_init(&delayed.node);\n\tspin_unlock_irq(&current->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 <eddy_wu@trendmicro.com>\nAcked-by: Oleg Nesterov <oleg@redhat.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 293695}
  373. {"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}
  374. {"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}
  375. {"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}
  376. {"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}
  377. {"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 <viro@zeniv.linux.org.uk>", "target": 1, "dataset": "other", "idx": 199916}
  378. {"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 <viro@zeniv.linux.org.uk>", "target": 0, "dataset": "other", "idx": 295331}
  379. {"func": "CallResult<HermesValue> 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<HermesValue> res{ExecutionStatus::EXCEPTION};\n CallResult<PseudoHandle<>> resPH{ExecutionStatus::EXCEPTION};\n CallResult<Handle<Arguments>> resArgs{ExecutionStatus::EXCEPTION};\n CallResult<bool> 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<lType>( \\\n hermes::truncateToInt32(O2REG(name).getNumber())); \\\n auto rnum = static_cast<uint32_t>( \\\n hermes::truncateToInt32(O3REG(name).getNumber())) & \\\n 0x1f; \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast<returnType>(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<lType>(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<uint32_t>(res->getNumber()) & 0x1f; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast<returnType>(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<int32_t>(); \\\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<int32_t>()); \\\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<JSFunction>(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<GeneratorInnerFunction>(\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<GeneratorInnerFunction>(\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<GeneratorInnerFunction>(\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<GeneratorInnerFunction>(\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<JSObject>::vmcast(&runtime->functionPrototype),\n Handle<Environment>::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<Environment>::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<Environment>::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<Environment>::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<Environment>::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<Environment>::vmcast(tmpHandle)\n : Handle<Environment>::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<Environment>(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<Environment>(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<Environment>(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<Environment>(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<Environment>(O2REG(LoadFromEnvironment))\n ->slot(ip->iLoadFromEnvironment.op3);\n ip = NEXTINST(LoadFromEnvironment);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironmentL) {\n O1REG(LoadFromEnvironmentL) =\n vmcast<Environment>(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<HermesValue> propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetById).isObject())) {\n auto *obj = vmcast<JSObject>(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<HiddenClass>(static_cast<GCCell *>(\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<PropStorage::Inline::Yes>(\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<bool> 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<JSObject>::vmcast(&O2REG(GetById)), runtime, id, desc));\n if (propObj) {\n if (desc.flags.accessor)\n ++NumGetByIdAccessor;\n else if (propObj != vmcast<JSObject>(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<JSObject>::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<JSObject>(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<HiddenClass>(static_cast<GCCell *>(\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<PropStorage::Inline::Yes>(\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<bool> 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<JSObject>::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<HermesValue> propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getComputed_RJS(\n Handle<JSObject>::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<JSObject>::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<JSObject>::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<BigStorage>(O2REG(GetNextPName)) &&\n \"GetNextPName's second op must be BigStorage\");\n auto obj = Handle<JSObject>::vmcast(&O3REG(GetNextPName));\n auto arr = Handle<BigStorage>::vmcast(&O2REG(GetNextPName));\n uint32_t idx = O4REG(GetNextPName).getNumber();\n uint32_t size = O5REG(GetNextPName).getNumber();\n MutableHandle<JSObject> 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<int32_t>(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<JSObject>::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<JSObject>::vmcast(&O2REG(NewObjectWithParent))\n : O2REG(NewObjectWithParent).isNull()\n ? Runtime::makeNullHandle<JSObject>()\n : Handle<JSObject>::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<Callable>(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<Callable>::vmcast(&O3REG(CreateThis)),\n runtime,\n Handle<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSError>(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<JSError>(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}
  380. {"func": "CallResult<HermesValue> 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<HermesValue> res{ExecutionStatus::EXCEPTION};\n CallResult<PseudoHandle<>> resPH{ExecutionStatus::EXCEPTION};\n CallResult<Handle<Arguments>> resArgs{ExecutionStatus::EXCEPTION};\n CallResult<bool> 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<lType>( \\\n hermes::truncateToInt32(O2REG(name).getNumber())); \\\n auto rnum = static_cast<uint32_t>( \\\n hermes::truncateToInt32(O3REG(name).getNumber())) & \\\n 0x1f; \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast<returnType>(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<lType>(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<uint32_t>(res->getNumber()) & 0x1f; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast<returnType>(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<int32_t>(); \\\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<int32_t>()); \\\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<JSFunction>(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<GeneratorInnerFunction>(\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<GeneratorInnerFunction>(\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<GeneratorInnerFunction>(\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<JSObject>::vmcast(&runtime->functionPrototype),\n Handle<Environment>::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<Environment>::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<Environment>::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<Environment>::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<Environment>::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<Environment>::vmcast(tmpHandle)\n : Handle<Environment>::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<Environment>(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<Environment>(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<Environment>(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<Environment>(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<Environment>(O2REG(LoadFromEnvironment))\n ->slot(ip->iLoadFromEnvironment.op3);\n ip = NEXTINST(LoadFromEnvironment);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironmentL) {\n O1REG(LoadFromEnvironmentL) =\n vmcast<Environment>(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<HermesValue> propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetById).isObject())) {\n auto *obj = vmcast<JSObject>(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<HiddenClass>(static_cast<GCCell *>(\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<PropStorage::Inline::Yes>(\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<bool> 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<JSObject>::vmcast(&O2REG(GetById)), runtime, id, desc));\n if (propObj) {\n if (desc.flags.accessor)\n ++NumGetByIdAccessor;\n else if (propObj != vmcast<JSObject>(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<JSObject>::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<JSObject>(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<HiddenClass>(static_cast<GCCell *>(\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<PropStorage::Inline::Yes>(\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<bool> 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<JSObject>::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<HermesValue> propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getComputed_RJS(\n Handle<JSObject>::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<JSObject>::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<JSObject>::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<BigStorage>(O2REG(GetNextPName)) &&\n \"GetNextPName's second op must be BigStorage\");\n auto obj = Handle<JSObject>::vmcast(&O3REG(GetNextPName));\n auto arr = Handle<BigStorage>::vmcast(&O2REG(GetNextPName));\n uint32_t idx = O4REG(GetNextPName).getNumber();\n uint32_t size = O5REG(GetNextPName).getNumber();\n MutableHandle<JSObject> 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<int32_t>(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<JSObject>::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<JSObject>::vmcast(&O2REG(NewObjectWithParent))\n : O2REG(NewObjectWithParent).isNull()\n ? Runtime::makeNullHandle<JSObject>()\n : Handle<JSObject>::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<Callable>(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<Callable>::vmcast(&O3REG(CreateThis)),\n runtime,\n Handle<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSObject>::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<JSError>(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<JSError>(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}
  381. {"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}
  382. {"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}
  383. {"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}
  384. {"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}
  385. {"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}
  386. {"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}
  387. {"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}
  388. {"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}
  389. {"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}
  390. {"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}
  391. {"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}
  392. {"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}
  393. {"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}
  394. {"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}
  395. {"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 <br@sseusa.com> 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}
  396. {"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 <br@sseusa.com> 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}
  397. {"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}
  398. {"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}
  399. {"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}
  400. {"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}
  401. {"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}
  402. {"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}
  403. {"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}
  404. {"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}
  405. {"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 <stefanb@linux.ibm.com>", "target": 1, "dataset": "other", "idx": 200558}
  406. {"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 <stefanb@linux.ibm.com>", "target": 0, "dataset": "other", "idx": 305346}
  407. {"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 <stable@vger.kernel.org> # 2.6.31\nCc: Hans de Goede <hdegoede@redhat.com>\nSigned-off-by: Johan Hovold <johan@kernel.org>\nSigned-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl>\nSigned-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>", "target": 1, "dataset": "other", "idx": 200621}
  408. {"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 <stable@vger.kernel.org> # 2.6.31\nCc: Hans de Goede <hdegoede@redhat.com>\nSigned-off-by: Johan Hovold <johan@kernel.org>\nSigned-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl>\nSigned-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>", "target": 0, "dataset": "other", "idx": 306343}
  409. {"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 <stable@vger.kernel.org> # 2.6.31\nCc: Hans de Goede <hdegoede@redhat.com>\nSigned-off-by: Johan Hovold <johan@kernel.org>\nSigned-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl>\nSigned-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>", "target": 1, "dataset": "other", "idx": 200622}
  410. {"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 <stable@vger.kernel.org> # 2.6.31\nCc: Hans de Goede <hdegoede@redhat.com>\nSigned-off-by: Johan Hovold <johan@kernel.org>\nSigned-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl>\nSigned-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>", "target": 0, "dataset": "other", "idx": 306292}
  411. {"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}
  412. {"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}
  413. {"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}
  414. {"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}
  415. {"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}
  416. {"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 \"<!\"). In a DTD context, that isn't legal.\n */\n else if (tok == XML_TOK_INSTANCE_START) {\n *nextPtr = next;\n return XML_ERROR_SYNTAX;\n }\n start = next;\n eventPtr = start;\n }\n}", "project": "libexpat", "hash": 315722906188758225822115197049039800003, "size": 73, "commit_id": "c4bf96bb51dd2a1b0e185374362ee136fe2c9d7f", "message": "xmlparse.c: Fix external entity infinite loop bug (CVE-2017-9233)", "target": 0, "dataset": "other", "idx": 308321}
  417. {"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\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}
  418. {"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}
  419. {"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 <len.brown@intel.com>\nCc: stable@vger.kernel.org", "target": 1, "dataset": "other", "idx": 200832}
  420. {"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 <len.brown@intel.com>\nCc: stable@vger.kernel.org", "target": 0, "dataset": "other", "idx": 310345}
  421. {"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; i<MAX_COMPONENTS; i++)\n\t{\n\t\ttmpbuf[i]=NULL; outbuf[i]=NULL;\n\t}\n\n\tif((this->init&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; i++)\n\t{\n\t\tscaledw=TJSCALED(jpegwidth, sf[i]);\n\t\tscaledh=TJSCALED(jpegheight, sf[i]);\n\t\tif(scaledw<=width && scaledh<=height)\n\t\t\tbreak;\n\t}\n\tif(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; i<dinfo->num_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; row<ph[i]; row++)\n\t\t{\n\t\t\toutbuf[i][row]=ptr;\n\t\t\tptr+=(strides && strides[i]!=0)? strides[i]:pw[i];\n\t\t}\n\t}\n\tif(usetmpbuf)\n\t{\n\t\tif((_tmpbuf=(JSAMPLE *)malloc(sizeof(JSAMPLE)*tmpbufsize))==NULL)\n\t\t\t_throw(\"tjDecompressToYUVPlanes(): Memory allocation failure\");\n\t\tptr=_tmpbuf;\n\t\tfor(i=0; i<dinfo->num_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; row<th[i]; row++)\n\t\t\t{\n\t\t\t\ttmpbuf[i][row]=ptr;\n\t\t\t\tptr+=iw[i];\n\t\t\t}\n\t\t}\n\t}\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(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; i<dinfo->num_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; i<dinfo->num_components; i++)\n\t\t\t{\n\t\t\t\tfor(j=0; j<min(th[i], ph[i]-crow[i]); j++)\n\t\t\t\t{\n\t\t\t\t\tmemcpy(outbuf[i][crow[i]+j], tmpbuf[i][j], pw[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tjpeg_finish_decompress(dinfo);\n\n\tbailout:\n\tif(dinfo->global_state>DSTATE_START) jpeg_abort_decompress(dinfo);\n\tfor(i=0; i<MAX_COMPONENTS; i++)\n\t{\n\t\tif(tmpbuf[i]) free(tmpbuf[i]);\n\t\tif(outbuf[i]) free(outbuf[i]);\n\t}\n\tif(_tmpbuf) free(_tmpbuf);\n\tif(this->jerr.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}
  422. {"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; i<MAX_COMPONENTS; i++)\n\t{\n\t\ttmpbuf[i]=NULL; outbuf[i]=NULL;\n\t}\n\n\tif((this->init&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; i++)\n\t{\n\t\tscaledw=TJSCALED(jpegwidth, sf[i]);\n\t\tscaledh=TJSCALED(jpegheight, sf[i]);\n\t\tif(scaledw<=width && scaledh<=height)\n\t\t\tbreak;\n\t}\n\tif(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; i<dinfo->num_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; row<ph[i]; row++)\n\t\t{\n\t\t\toutbuf[i][row]=ptr;\n\t\t\tptr+=(strides && strides[i]!=0)? strides[i]:pw[i];\n\t\t}\n\t}\n\tif(usetmpbuf)\n\t{\n\t\tif((_tmpbuf=(JSAMPLE *)malloc(sizeof(JSAMPLE)*tmpbufsize))==NULL)\n\t\t\t_throw(\"tjDecompressToYUVPlanes(): Memory allocation failure\");\n\t\tptr=_tmpbuf;\n\t\tfor(i=0; i<dinfo->num_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; row<th[i]; row++)\n\t\t\t{\n\t\t\t\ttmpbuf[i][row]=ptr;\n\t\t\t\tptr+=iw[i];\n\t\t\t}\n\t\t}\n\t}\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(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; i<dinfo->num_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; i<dinfo->num_components; i++)\n\t\t\t{\n\t\t\t\tfor(j=0; j<min(th[i], ph[i]-crow[i]); j++)\n\t\t\t\t{\n\t\t\t\t\tmemcpy(outbuf[i][crow[i]+j], tmpbuf[i][j], pw[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tjpeg_finish_decompress(dinfo);\n\n\tbailout:\n\tif(dinfo->global_state>DSTATE_START) jpeg_abort_decompress(dinfo);\n\tfor(i=0; i<MAX_COMPONENTS; i++)\n\t{\n\t\tif(tmpbuf[i]) free(tmpbuf[i]);\n\t\tif(outbuf[i]) free(outbuf[i]);\n\t}\n\tif(_tmpbuf) free(_tmpbuf);\n\tif(this->jerr.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}
  423. {"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 <sandeen@redhat.com>\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199377\nReviewed-by: Darrick J. Wong <darrick.wong@oracle.com>\nSigned-off-by: Darrick J. Wong <darrick.wong@oracle.com>", "target": 1, "dataset": "other", "idx": 200867}
  424. {"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 <sandeen@redhat.com>\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199377\nReviewed-by: Darrick J. Wong <darrick.wong@oracle.com>\nSigned-off-by: Darrick J. Wong <darrick.wong@oracle.com>", "target": 0, "dataset": "other", "idx": 311147}
  425. {"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}
  426. {"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}
  427. {"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}
  428. {"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}
  429. {"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}
  430. {"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}
  431. {"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}
  432. {"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}
  433. {"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}
  434. {"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}
  435. {"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 <ieatmuttonchuan@gmail.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 1, "dataset": "other", "idx": 201423}
  436. {"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 <ieatmuttonchuan@gmail.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 0, "dataset": "other", "idx": 319215}
  437. {"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}
  438. {"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}
  439. {"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: <stable@vger.kernel.org>\nReported-by: Fan Yang <Fan_Yang@sjtu.edu.cn>\nSigned-off-by: Fan Yang <Fan_Yang@sjtu.edu.cn>\nTested-by: Fan Yang <Fan_Yang@sjtu.edu.cn>\nTested-by: Dan Williams <dan.j.williams@intel.com>\nReviewed-by: Dan Williams <dan.j.williams@intel.com>\nAcked-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 201788}
  440. {"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: <stable@vger.kernel.org>\nReported-by: Fan Yang <Fan_Yang@sjtu.edu.cn>\nSigned-off-by: Fan Yang <Fan_Yang@sjtu.edu.cn>\nTested-by: Fan Yang <Fan_Yang@sjtu.edu.cn>\nTested-by: Dan Williams <dan.j.williams@intel.com>\nReviewed-by: Dan Williams <dan.j.williams@intel.com>\nAcked-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 321574}
  441. {"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}
  442. {"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}
  443. {"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 <stefanb@linux.ibm.com>", "target": 1, "dataset": "other", "idx": 201812}
  444. {"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 <stefanb@linux.ibm.com>", "target": 0, "dataset": "other", "idx": 322084}
  445. {"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}
  446. {"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}
  447. {"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(&current->mm->mmap_sem))\n\t\t\treturn -EINTR;\n\t} else {\n\t\tdown_read(&current->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(&current->mm->mmap_sem);\n\telse\n\t\tup_read(&current->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 <jannh@google.com>\nFixes: c1ca757bd6f4 (\"io_uring: add IORING_OP_MADVISE\")\nAcked-by: Jens Axboe <axboe@kernel.dk>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 201869}
  448. {"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(&current->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(&current->mm->mmap_sem);\n\t\t\treturn -EINTR;\n\t\t}\n\t} else {\n\t\tdown_read(&current->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(&current->mm->mmap_sem);\n\telse\n\t\tup_read(&current->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 <jannh@google.com>\nFixes: c1ca757bd6f4 (\"io_uring: add IORING_OP_MADVISE\")\nAcked-by: Jens Axboe <axboe@kernel.dk>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 323578}
  449. {"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}
  450. {"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}
  451. {"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 <jannh@google.com>\nReviewed-by: Jiri Slaby <jirislaby@kernel.org>\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 1, "dataset": "other", "idx": 201881}
  452. {"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 <jannh@google.com>\nReviewed-by: Jiri Slaby <jirislaby@kernel.org>\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 0, "dataset": "other", "idx": 326074}
  453. {"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 <eric.sesterhenn@x41-dsec.de>\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 <cjihrig@gmail.com>\nReviewed-By: Richard Lau <riclau@uk.ibm.com>", "target": 1, "dataset": "other", "idx": 201892}
  454. {"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 <eric.sesterhenn@x41-dsec.de>\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 <cjihrig@gmail.com>\nReviewed-By: Richard Lau <riclau@uk.ibm.com>", "target": 0, "dataset": "other", "idx": 326145}
  455. {"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 <pablo@netfilter.org>", "target": 1, "dataset": "other", "idx": 202069}
  456. {"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 <pablo@netfilter.org>", "target": 0, "dataset": "other", "idx": 328360}
  457. {"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 <scannell.smn@gmail.com>\nSigned-off-by: Daniel Borkmann <daniel@iogearbox.net>\nReviewed-by: John Fastabend <john.fastabend@gmail.com>\nAcked-by: Alexei Starovoitov <ast@kernel.org>", "target": 1, "dataset": "other", "idx": 202076}
  458. {"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 <scannell.smn@gmail.com>\nSigned-off-by: Daniel Borkmann <daniel@iogearbox.net>\nReviewed-by: John Fastabend <john.fastabend@gmail.com>\nAcked-by: Alexei Starovoitov <ast@kernel.org>", "target": 0, "dataset": "other", "idx": 328523}
  459. {"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}
  460. {"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}
  461. {"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}
  462. {"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}
  463. {"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 <orcohen@paloaltonetworks.com>\nSigned-off-by: Eric Dumazet <edumazet@google.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 202143}
  464. {"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 <orcohen@paloaltonetworks.com>\nSigned-off-by: Eric Dumazet <edumazet@google.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 330393}
  465. {"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 <lianyihan@360.cn>\nSigned-off-by: Prasad J Pandit <pjp@fedoraproject.org>\nReviewed-by: Gerd Hoffmann <kraxel@redhat.com>\nSigned-off-by: Peter Maydell <peter.maydell@linaro.org>", "target": 1, "dataset": "other", "idx": 202144}
  466. {"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 <lianyihan@360.cn>\nSigned-off-by: Prasad J Pandit <pjp@fedoraproject.org>\nReviewed-by: Gerd Hoffmann <kraxel@redhat.com>\nSigned-off-by: Peter Maydell <peter.maydell@linaro.org>", "target": 0, "dataset": "other", "idx": 330516}
  467. {"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 <xiezhipeng1@huawei.com>", "target": 1, "dataset": "other", "idx": 202305}
  468. {"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 <xiezhipeng1@huawei.com>", "target": 0, "dataset": "other", "idx": 333146}
  469. {"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}
  470. {"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}
  471. {"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}
  472. {"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}
  473. {"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 <dbueso@suse.de>\nSigned-off-by: Thomas Gleixner <tglx@linutronix.de>\nLink: https://lkml.kernel.org/r/20190724152323.bojciei3muvfxalm@linux-r8p5", "target": 1, "dataset": "other", "idx": 202574}
  474. {"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 <dbueso@suse.de>\nSigned-off-by: Thomas Gleixner <tglx@linutronix.de>\nLink: https://lkml.kernel.org/r/20190724152323.bojciei3muvfxalm@linux-r8p5", "target": 0, "dataset": "other", "idx": 335107}
  475. {"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}
  476. {"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}
  477. {"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 <Qiuhao.Li@outlook.com>\nReviewed-by: Keith Busch <kbusch@kernel.org>\nReviewed-by: Philippe Mathieu-Daud\u00e9 <f4bug@amsat.org>\nSigned-off-by: Klaus Jensen <k.jensen@samsung.com>", "target": 1, "dataset": "other", "idx": 202660}
  478. {"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 <Qiuhao.Li@outlook.com>\nReviewed-by: Keith Busch <kbusch@kernel.org>\nReviewed-by: Philippe Mathieu-Daud\u00e9 <f4bug@amsat.org>\nSigned-off-by: Klaus Jensen <k.jensen@samsung.com>", "target": 0, "dataset": "other", "idx": 336154}
  479. {"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 <viro@zeniv.linux.org.uk>", "target": 1, "dataset": "other", "idx": 202665}
  480. {"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 <viro@zeniv.linux.org.uk>", "target": 0, "dataset": "other", "idx": 336269}
  481. {"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}
  482. {"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}
  483. {"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 <Emmanouel.Kellinis AT kpmg.co.uk>, 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}
  484. {"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 <Emmanouel.Kellinis AT kpmg.co.uk>, 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}
  485. {"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}
  486. {"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}
  487. {"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}
  488. {"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}
  489. {"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 <cascardo@canonical.com>\nSigned-off-by: Jens Axboe <axboe@kernel.dk>", "target": 1, "dataset": "other", "idx": 202741}
  490. {"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 <cascardo@canonical.com>\nSigned-off-by: Jens Axboe <axboe@kernel.dk>", "target": 0, "dataset": "other", "idx": 338639}
  491. {"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 <asteinhauser@google.com>\nSigned-off-by: Thomas Gleixner <tglx@linutronix.de>\nCc: stable@vger.kernel.org", "target": 1, "dataset": "other", "idx": 202751}
  492. {"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 <asteinhauser@google.com>\nSigned-off-by: Thomas Gleixner <tglx@linutronix.de>\nCc: stable@vger.kernel.org", "target": 0, "dataset": "other", "idx": 338780}
  493. {"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 <mszeredi@redhat.com>\nTested-by: Jan Kara <jack@suse.cz>\nCc: <stable@vger.kernel.org>", "target": 1, "dataset": "other", "idx": 202842}
  494. {"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 <mszeredi@redhat.com>\nTested-by: Jan Kara <jack@suse.cz>\nCc: <stable@vger.kernel.org>", "target": 0, "dataset": "other", "idx": 342120}
  495. {"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, &region_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}
  496. {"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, &region_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}
  497. {"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 <wanpengli@tencent.com>\nMessage-Id: <1614326399-5762-1-git-send-email-wanpengli@tencent.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 1, "dataset": "other", "idx": 202898}
  498. {"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 <wanpengli@tencent.com>\nMessage-Id: <1614326399-5762-1-git-send-email-wanpengli@tencent.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 0, "dataset": "other", "idx": 343525}
  499. {"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 <asn@cryptomilk.org>\nReviewed-by: Anderson Toshiyuki Sasaki <ansasaki@redhat.com>\nReviewed-by: Jakub Jelen <jjelen@redhat.com>", "target": 1, "dataset": "other", "idx": 203616}
  500. {"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 <asn@cryptomilk.org>\nReviewed-by: Anderson Toshiyuki Sasaki <ansasaki@redhat.com>\nReviewed-by: Jakub Jelen <jjelen@redhat.com>", "target": 0, "dataset": "other", "idx": 345161}
  501. {"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 <jim@jtan.com>\nSigned-off-by: Anthony Liguori <aliguori@us.ibm.com>", "target": 1, "dataset": "other", "idx": 203887}
  502. {"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 <jim@jtan.com>\nSigned-off-by: Anthony Liguori <aliguori@us.ibm.com>", "target": 0, "dataset": "other", "idx": 346299}
  503. {"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}
  504. {"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}
  505. {"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}
  506. {"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}
  507. {"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 <input-tiled-tif> <output-strip-tif> */\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}
  508. {"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 <input-tiled-tif> <output-strip-tif> */\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}
  509. {"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 <dmitry.torokhov@gmail.com>", "target": 1, "dataset": "other", "idx": 204147}
  510. {"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 <dmitry.torokhov@gmail.com>", "target": 0, "dataset": "other", "idx": 353362}
  511. {"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 <cai@lca.pw>\nCc: Peter Xu <peterx@redhat.com>\nSigned-off-by: Sean Christopherson <sean.j.christopherson@intel.com>\nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger <borntraeger@de.ibm.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 1, "dataset": "other", "idx": 204189}
  512. {"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 <cai@lca.pw>\nCc: Peter Xu <peterx@redhat.com>\nSigned-off-by: Sean Christopherson <sean.j.christopherson@intel.com>\nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger <borntraeger@de.ibm.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 0, "dataset": "other", "idx": 354690}
  513. {"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 <cai@lca.pw>\nCc: Peter Xu <peterx@redhat.com>\nSigned-off-by: Sean Christopherson <sean.j.christopherson@intel.com>\nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger <borntraeger@de.ibm.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 1, "dataset": "other", "idx": 204190}
  514. {"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 <cai@lca.pw>\nCc: Peter Xu <peterx@redhat.com>\nSigned-off-by: Sean Christopherson <sean.j.christopherson@intel.com>\nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger <borntraeger@de.ibm.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 0, "dataset": "other", "idx": 354527}
  515. {"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 <cai@lca.pw>\nCc: Peter Xu <peterx@redhat.com>\nSigned-off-by: Sean Christopherson <sean.j.christopherson@intel.com>\nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger <borntraeger@de.ibm.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 1, "dataset": "other", "idx": 204191}
  516. {"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 <cai@lca.pw>\nCc: Peter Xu <peterx@redhat.com>\nSigned-off-by: Sean Christopherson <sean.j.christopherson@intel.com>\nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger <borntraeger@de.ibm.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 0, "dataset": "other", "idx": 354422}
  517. {"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}
  518. {"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}
  519. {"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}
  520. {"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}
  521. {"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; i<pTabList->nSrc; 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; k<pEList->nExpr; 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( k<pEList->nExpr ){\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; k<pEList->nExpr; 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; i<pTabList->nSrc; 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; j<pTab->nCol; 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}
  522. {"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; i<pTabList->nSrc; 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; k<pEList->nExpr; 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( k<pEList->nExpr ){\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; k<pEList->nExpr; 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; i<pTabList->nSrc; 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; j<pTab->nCol; 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}
  523. {"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}
  524. {"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}
  525. {"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 <kevin@8t8.us>", "target": 1, "dataset": "other", "idx": 204337}
  526. {"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 <kevin@8t8.us>", "target": 0, "dataset": "other", "idx": 357032}
  527. {"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 /* <<UniPG */\n /*}*/\n /* << INDEX */\n\n if (p_j2k->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}
  528. {"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 /* <<UniPG */\n /*}*/\n /* << INDEX */\n\n if (p_j2k->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}
  529. {"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}
  530. {"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}
  531. {"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}
  532. {"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}
  533. {"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}
  534. {"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}
  535. {"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}
  536. {"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}
  537. {"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 <peterh@wetafx.co.nz>", "target": 1, "dataset": "other", "idx": 204639}
  538. {"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 <peterh@wetafx.co.nz>", "target": 0, "dataset": "other", "idx": 362854}
  539. {"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 <minhquangbui99@gmail.com>\nSigned-off-by: Magnus Karlsson <magnus.karlsson@intel.com>\nSigned-off-by: Daniel Borkmann <daniel@iogearbox.net>\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}
  540. {"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 <minhquangbui99@gmail.com>\nSigned-off-by: Magnus Karlsson <magnus.karlsson@intel.com>\nSigned-off-by: Daniel Borkmann <daniel@iogearbox.net>\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}
  541. {"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}
  542. {"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}
  543. {"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 <aarcange@redhat.com>\nSuggested-by: Jann Horn <jannh@google.com>\nReported-by: Jann Horn <jannh@google.com>\nAcked-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.com>\nFixes: 6d0a07edd17c (\"mm: thp: calculate the mapcount correctly for THP pages during WP faults\")\nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 204725}
  544. {"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 <aarcange@redhat.com>\nSuggested-by: Jann Horn <jannh@google.com>\nReported-by: Jann Horn <jannh@google.com>\nAcked-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.com>\nFixes: 6d0a07edd17c (\"mm: thp: calculate the mapcount correctly for THP pages during WP faults\")\nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 364123}
  545. {"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}
  546. {"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}
  547. {"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 <edumazet@google.com>\nCc: Tuong Lien <tuong.t.lien@dektech.com.au>\nCc: Jon Maloy <jmaloy@redhat.com>\nCc: Ying Xue <ying.xue@windriver.com>\nReported-by: syzbot <syzkaller@googlegroups.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 1, "dataset": "other", "idx": 204764}
  548. {"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 <edumazet@google.com>\nCc: Tuong Lien <tuong.t.lien@dektech.com.au>\nCc: Jon Maloy <jmaloy@redhat.com>\nCc: Ying Xue <ying.xue@windriver.com>\nReported-by: syzbot <syzkaller@googlegroups.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 0, "dataset": "other", "idx": 364977}
  549. {"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, \"</\", 2)) {\n if (lws && !elem->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, \"<?\", 2)) {\n if (lws) {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n /* PI - ignore it */\n c += 2;\n if (parse_ignore(ctx, c, \"?>\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"<!--\", 4)) {\n if (lws) {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n /* Comment - ignore it */\n c += 4;\n if (parse_ignore(ctx, c, \"-->\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"<![CDATA[\", 9)) {\n /* CDSect */\n goto store_content;\n } else if (*c == '<') {\n if (lws) {\n if (elem->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}
  550. {"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, \"</\", 2)) {\n if (lws && !elem->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, \"<?\", 2)) {\n if (lws) {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n /* PI - ignore it */\n c += 2;\n if (parse_ignore(ctx, c, \"?>\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"<!--\", 4)) {\n if (lws) {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n /* Comment - ignore it */\n c += 4;\n if (parse_ignore(ctx, c, \"-->\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"<![CDATA[\", 9)) {\n /* CDSect */\n goto store_content;\n } else if (*c == '<') {\n if (lws) {\n if (elem->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}
  551. {"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, \"<?\", 2)) {\n /* XMLDecl or PI - ignore it */\n c += 2;\n if (parse_ignore(ctx, c, \"?>\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \"<!--\", 4)) {\n /* Comment - ignore it */\n c += 2;\n if (parse_ignore(ctx, c, \"-->\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \"<!\", 2)) {\n /* DOCTYPE */\n /* TODO - standalone ignore counting < and > */\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}
  552. {"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, \"<?\", 2)) {\n /* XMLDecl or PI - ignore it */\n c += 2;\n if (parse_ignore(ctx, c, \"?>\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \"<!--\", 4)) {\n /* Comment - ignore it */\n c += 2;\n if (parse_ignore(ctx, c, \"-->\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \"<!\", 2)) {\n /* DOCTYPE */\n /* TODO - standalone ignore counting < and > */\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}
  553. {"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 <rdunlap@infradead.org>\nSigned-off-by: Andrew Morton <akpm@linux-foundation.org>\nTested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nCc: Lee Schermerhorn <lee.schermerhorn@hp.com>\nLink: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.org\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 204856}
  554. {"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 <rdunlap@infradead.org>\nSigned-off-by: Andrew Morton <akpm@linux-foundation.org>\nTested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nCc: Lee Schermerhorn <lee.schermerhorn@hp.com>\nLink: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.org\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 366756}
  555. {"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 <balaton@eik.bme.hu>\nMessage-id: 58666389b6cae256e4e972a32c05cf8aa51bffc0.1590089984.git.balaton@eik.bme.hu\nSigned-off-by: Gerd Hoffmann <kraxel@redhat.com>", "target": 1, "dataset": "other", "idx": 204867}
  556. {"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 <balaton@eik.bme.hu>\nMessage-id: 58666389b6cae256e4e972a32c05cf8aa51bffc0.1590089984.git.balaton@eik.bme.hu\nSigned-off-by: Gerd Hoffmann <kraxel@redhat.com>", "target": 0, "dataset": "other", "idx": 367048}
  557. {"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<long>(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}
  558. {"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<size_t>(newIdx) > p_->size_) {\n p_->eof_ = true;\n return 1;\n }\n\n p_->idx_ = static_cast<size_t>(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}
  559. {"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}
  560. {"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}
  561. {"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; t<nr_recode_types; t++) {\n gl_lock_init (h->iconv_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 <rjones@redhat.com>\nFixes: CVE-2021-3504\nFixes: https://bugzilla.redhat.com/show_bug.cgi?id=1949687", "target": 1, "dataset": "other", "idx": 205584}
  562. {"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; t<nr_recode_types; t++) {\n gl_lock_init (h->iconv_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 <rjones@redhat.com>\nFixes: CVE-2021-3504\nFixes: https://bugzilla.redhat.com/show_bug.cgi?id=1949687", "target": 0, "dataset": "other", "idx": 368604}
  563. {"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}
  564. {"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}
  565. {"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<Value>& 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<Value>& 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}
  566. {"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<Value>& 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<Value>& 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}
  567. {"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}
  568. {"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}
  569. {"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}
  570. {"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}
  571. {"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}
  572. {"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}
  573. {"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}
  574. {"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}
  575. {"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}
  576. {"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}
  577. {"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}
  578. {"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}
  579. {"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}
  580. {"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}
  581. {"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}
  582. {"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}
  583. {"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 <christophe.leroy@csgroup.eu>\nSigned-off-by: Athira Rajeev <atrajeev@linux.vnet.ibm.com>\nTested-by: Christophe Leroy <christophe.leroy@csgroup.eu>\nSigned-off-by: Michael Ellerman <mpe@ellerman.id.au>\nLink: https://lore.kernel.org/r/1623952506-1431-1-git-send-email-atrajeev@linux.vnet.ibm.com", "target": 1, "dataset": "other", "idx": 205900}
  584. {"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 <christophe.leroy@csgroup.eu>\nSigned-off-by: Athira Rajeev <atrajeev@linux.vnet.ibm.com>\nTested-by: Christophe Leroy <christophe.leroy@csgroup.eu>\nSigned-off-by: Michael Ellerman <mpe@ellerman.id.au>\nLink: https://lore.kernel.org/r/1623952506-1431-1-git-send-email-atrajeev@linux.vnet.ibm.com", "target": 0, "dataset": "other", "idx": 374683}
  585. {"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}
  586. {"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}
  587. {"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\" <ebiederm@xmission.com>", "target": 1, "dataset": "other", "idx": 205956}
  588. {"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\" <ebiederm@xmission.com>", "target": 0, "dataset": "other", "idx": 375155}
  589. {"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 <samuel.thibault@ens-lyon.org>", "target": 1, "dataset": "other", "idx": 205959}
  590. {"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 <samuel.thibault@ens-lyon.org>", "target": 0, "dataset": "other", "idx": 375358}
  591. {"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 = &params[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 = &params[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 <gorcunov@gmail.com>", "target": 1, "dataset": "other", "idx": 205976}
  592. {"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 = &params[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 = &params[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 <gorcunov@gmail.com>", "target": 0, "dataset": "other", "idx": 375670}
  593. {"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 <Nicolas.Joly@microsoft.com>\nSigned-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>", "target": 1, "dataset": "other", "idx": 206023}
  594. {"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 <Nicolas.Joly@microsoft.com>\nSigned-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>", "target": 0, "dataset": "other", "idx": 376250}
  595. {"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 <fwilhelm@google.com>\nCc: stable@vger.kernel.org\nFixes: 2fcf4876ada (\"KVM: nSVM: implement on demand allocation of the nested state\")\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 1, "dataset": "other", "idx": 206039}
  596. {"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 <fwilhelm@google.com>\nCc: stable@vger.kernel.org\nFixes: 2fcf4876ada (\"KVM: nSVM: implement on demand allocation of the nested state\")\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 0, "dataset": "other", "idx": 376647}
  597. {"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}
  598. {"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}
  599. {"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}
  600. {"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}
  601. {"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}
  602. {"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}
  603. {"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}
  604. {"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}
  605. {"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}
  606. {"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}
  607. {"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}
  608. {"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}
  609. {"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 <adam@grimm-co.com>\nReviewed-by: Lee Duncan <lduncan@suse.com>\nReviewed-by: Mike Christie <michael.christie@oracle.com>\nSigned-off-by: Chris Leech <cleech@redhat.com>\nSigned-off-by: Martin K. Petersen <martin.petersen@oracle.com>", "target": 1, "dataset": "other", "idx": 206293}
  610. {"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 <adam@grimm-co.com>\nReviewed-by: Lee Duncan <lduncan@suse.com>\nReviewed-by: Mike Christie <michael.christie@oracle.com>\nSigned-off-by: Chris Leech <cleech@redhat.com>\nSigned-off-by: Martin K. Petersen <martin.petersen@oracle.com>", "target": 0, "dataset": "other", "idx": 380003}
  611. {"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 <blackgod016574@gmail.com>\nSigned-off-by: Michael Ellerman <mpe@ellerman.id.au>", "target": 1, "dataset": "other", "idx": 206300}
  612. {"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 <blackgod016574@gmail.com>\nSigned-off-by: Michael Ellerman <mpe@ellerman.id.au>", "target": 0, "dataset": "other", "idx": 380132}
  613. {"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}
  614. {"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}
  615. {"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 <kwolf@redhat.com>\nSigned-off-by: Stefano Stabellini <stefano.stabellini@eu.citrix.com>", "target": 1, "dataset": "other", "idx": 206467}
  616. {"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 <kwolf@redhat.com>\nSigned-off-by: Stefano Stabellini <stefano.stabellini@eu.citrix.com>", "target": 0, "dataset": "other", "idx": 381410}
  617. {"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 <arnd@kernel.org>\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 <sakari.ailus@linux.intel.com>\nAcked-by: Arnd Bergmann <arnd@arndb.de>\nAcked-by: Hans Verkuil <hverkuil-cisco@xs4all.nl>\nReviewed-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>\nSigned-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>", "target": 1, "dataset": "other", "idx": 206468}
  618. {"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 <arnd@kernel.org>\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 <sakari.ailus@linux.intel.com>\nAcked-by: Arnd Bergmann <arnd@arndb.de>\nAcked-by: Hans Verkuil <hverkuil-cisco@xs4all.nl>\nReviewed-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>\nSigned-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>", "target": 0, "dataset": "other", "idx": 381516}
  619. {"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 <dh.herrmann@gmail.com>\nAcked-by: Peter Hutterer <peter.hutterer@who-t.net>\nSigned-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>", "target": 1, "dataset": "other", "idx": 206492}
  620. {"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 <dh.herrmann@gmail.com>\nAcked-by: Peter Hutterer <peter.hutterer@who-t.net>\nSigned-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>", "target": 0, "dataset": "other", "idx": 381731}
  621. {"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}
  622. {"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}
  623. {"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}
  624. {"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}
  625. {"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 <guiyao@huawei.com>\n[rharwood@redhat.com: whitespace, tweak commit message]\nReviewed-by: Robbie Harwood <rharwood@redhat.com>", "target": 1, "dataset": "other", "idx": 206559}
  626. {"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 <guiyao@huawei.com>\n[rharwood@redhat.com: whitespace, tweak commit message]\nReviewed-by: Robbie Harwood <rharwood@redhat.com>", "target": 0, "dataset": "other", "idx": 382874}
  627. {"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; i<number_arguments; i+=4) {\n double weight =\n ((double)d.x-arguments[i+2])*((double)d.x-arguments[i+2])\n + ((double)d.y-arguments[i+3])*((double)d.y-arguments[i+3]);\n weight = pow(weight,coeff[0]); /* shepards power factor */\n weight = ( weight < 1.0 ) ? 1.0 : 1.0/weight;\n\n s.x += (arguments[ i ]-arguments[i+2])*weight;\n s.y += (arguments[i+1]-arguments[i+3])*weight;\n denominator += weight;\n }\n s.x /= denominator;\n s.y /= denominator;\n s.x += d.x; /* make it as relative displacement */\n s.y += d.y;\n break;\n }\n default:\n break; /* use the default no-op given above */\n }\n /* map virtual canvas location back to real image coordinate */\n if ( bestfit && method != ArcDistortion ) {\n s.x -= image->page.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}
  628. {"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; i<number_arguments; i+=4) {\n double weight =\n ((double)d.x-arguments[i+2])*((double)d.x-arguments[i+2])\n + ((double)d.y-arguments[i+3])*((double)d.y-arguments[i+3]);\n weight = pow(weight,coeff[0]); /* shepards power factor */\n weight = ( weight < 1.0 ) ? 1.0 : 1.0/weight;\n\n s.x += (arguments[ i ]-arguments[i+2])*weight;\n s.y += (arguments[i+1]-arguments[i+3])*weight;\n denominator += weight;\n }\n s.x /= denominator;\n s.y /= denominator;\n s.x += d.x; /* make it as relative displacement */\n s.y += d.y;\n break;\n }\n default:\n break; /* use the default no-op given above */\n }\n /* map virtual canvas location back to real image coordinate */\n if ( bestfit && method != ArcDistortion ) {\n s.x -= image->page.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}
  629. {"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: <stable@vger.kernel.org>\nFixes: d646960f7986 (\"NFC: Initial LLCP support\")\nReported-by: syzbot+80fb126e7f7d8b1a5914@syzkaller.appspotmail.com\nReported-by: butt3rflyh4ck <butterflyhuangxx@gmail.com>\nSigned-off-by: Krzysztof Kozlowski <krzysztof.kozlowski@canonical.com>\nLink: https://lore.kernel.org/r/20210531072138.5219-1-krzysztof.kozlowski@canonical.com\nSigned-off-by: Jakub Kicinski <kuba@kernel.org>", "target": 1, "dataset": "other", "idx": 206589}
  630. {"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: <stable@vger.kernel.org>\nFixes: d646960f7986 (\"NFC: Initial LLCP support\")\nReported-by: syzbot+80fb126e7f7d8b1a5914@syzkaller.appspotmail.com\nReported-by: butt3rflyh4ck <butterflyhuangxx@gmail.com>\nSigned-off-by: Krzysztof Kozlowski <krzysztof.kozlowski@canonical.com>\nLink: https://lore.kernel.org/r/20210531072138.5219-1-krzysztof.kozlowski@canonical.com\nSigned-off-by: Jakub Kicinski <kuba@kernel.org>", "target": 0, "dataset": "other", "idx": 383386}
  631. {"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}
  632. {"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}
  633. {"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}
  634. {"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}
  635. {"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 <navid.emamdoost@gmail.com>\nSigned-off-by: Luca Coelho <luciano.coelho@intel.com>", "target": 1, "dataset": "other", "idx": 206661}
  636. {"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 <navid.emamdoost@gmail.com>\nSigned-off-by: Luca Coelho <luciano.coelho@intel.com>", "target": 0, "dataset": "other", "idx": 384469}
  637. {"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 <ofriedma@redhat.com>\nSigned-off-by: Matt Benjamin <mbenjamin@redhat.com>", "target": 1, "dataset": "other", "idx": 206666}
  638. {"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 <ofriedma@redhat.com>\nSigned-off-by: Matt Benjamin <mbenjamin@redhat.com>", "target": 0, "dataset": "other", "idx": 384543}
  639. {"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<<tcpd->fwd->win_scale, \"%d\", 1<<tcpd->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}
  640. {"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<<tcpd->fwd->win_scale, \"%d\", 1<<tcpd->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}
  641. {"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 [<ffffffff8125dc56>] alloc_pid+0x66/0x560\n [<ffffffff81226405>] copy_process+0x1465/0x25e0\n [<ffffffff81227943>] kernel_clone+0xf3/0x670\n [<ffffffff812281a1>] kernel_thread+0x61/0x80\n [<ffffffff81253464>] call_usermodehelper_exec_work\n [<ffffffff81253464>] call_usermodehelper_exec_work+0xc4/0x120\n [<ffffffff812591c9>] process_one_work+0x2c9/0x600\n [<ffffffff81259ab9>] worker_thread+0x59/0x5d0\n [<ffffffff812611c8>] kthread+0x178/0x1b0\n [<ffffffff8100227f>] 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 [<ffffffff8154a0cf>] kmem_cache_zalloc\n [<ffffffff8154a0cf>] __alloc_file+0x1f/0xf0\n [<ffffffff8154a809>] alloc_empty_file+0x69/0x120\n [<ffffffff8154a8f3>] alloc_file+0x33/0x1b0\n [<ffffffff8154ab22>] alloc_file_pseudo+0xb2/0x140\n [<ffffffff81559218>] create_pipe_files+0x138/0x2e0\n [<ffffffff8126c793>] umd_setup+0x33/0x220\n [<ffffffff81253574>] call_usermodehelper_exec_async+0xb4/0x1b0\n [<ffffffff8100227f>] 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 <qiang.zhang@windriver.com>\nSigned-off-by: Daniel Borkmann <daniel@iogearbox.net>\nLink: https://lore.kernel.org/bpf/20210317030915.2865-1-qiang.zhang@windriver.com", "target": 1, "dataset": "other", "idx": 206697}
  642. {"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 [<ffffffff8125dc56>] alloc_pid+0x66/0x560\n [<ffffffff81226405>] copy_process+0x1465/0x25e0\n [<ffffffff81227943>] kernel_clone+0xf3/0x670\n [<ffffffff812281a1>] kernel_thread+0x61/0x80\n [<ffffffff81253464>] call_usermodehelper_exec_work\n [<ffffffff81253464>] call_usermodehelper_exec_work+0xc4/0x120\n [<ffffffff812591c9>] process_one_work+0x2c9/0x600\n [<ffffffff81259ab9>] worker_thread+0x59/0x5d0\n [<ffffffff812611c8>] kthread+0x178/0x1b0\n [<ffffffff8100227f>] 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 [<ffffffff8154a0cf>] kmem_cache_zalloc\n [<ffffffff8154a0cf>] __alloc_file+0x1f/0xf0\n [<ffffffff8154a809>] alloc_empty_file+0x69/0x120\n [<ffffffff8154a8f3>] alloc_file+0x33/0x1b0\n [<ffffffff8154ab22>] alloc_file_pseudo+0xb2/0x140\n [<ffffffff81559218>] create_pipe_files+0x138/0x2e0\n [<ffffffff8126c793>] umd_setup+0x33/0x220\n [<ffffffff81253574>] call_usermodehelper_exec_async+0xb4/0x1b0\n [<ffffffff8100227f>] 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 <qiang.zhang@windriver.com>\nSigned-off-by: Daniel Borkmann <daniel@iogearbox.net>\nLink: https://lore.kernel.org/bpf/20210317030915.2865-1-qiang.zhang@windriver.com", "target": 0, "dataset": "other", "idx": 385297}
  643. {"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}
  644. {"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}
  645. {"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 <kris.re@bbhmedia.com>\n\nReviewed-By: Trevor Norris <trev.norris@gmail.com>", "target": 1, "dataset": "other", "idx": 206709}
  646. {"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 <kris.re@bbhmedia.com>\n\nReviewed-By: Trevor Norris <trev.norris@gmail.com>", "target": 0, "dataset": "other", "idx": 385616}
  647. {"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}
  648. {"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}
  649. {"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 <jhs@mojatatu.com>\nCc: Jiri Pirko <jiri@resnulli.us>\nCc: John Fastabend <john.fastabend@gmail.com>\nSigned-off-by: Cong Wang <xiyou.wangcong@gmail.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 1, "dataset": "other", "idx": 206718}
  650. {"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 <jhs@mojatatu.com>\nCc: Jiri Pirko <jiri@resnulli.us>\nCc: John Fastabend <john.fastabend@gmail.com>\nSigned-off-by: Cong Wang <xiyou.wangcong@gmail.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 0, "dataset": "other", "idx": 385783}
  651. {"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}
  652. {"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}
  653. {"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 <ztong0001@gmail.com>\nCo-developed-by: Ulf Hansson <ulf.hansson@linaro.org>\nLink: https://lore.kernel.org/r/20210511163944.1233295-1-ztong0001@gmail.com\nSigned-off-by: Ulf Hansson <ulf.hansson@linaro.org>", "target": 1, "dataset": "other", "idx": 206735}
  654. {"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 <ztong0001@gmail.com>\nCo-developed-by: Ulf Hansson <ulf.hansson@linaro.org>\nLink: https://lore.kernel.org/r/20210511163944.1233295-1-ztong0001@gmail.com\nSigned-off-by: Ulf Hansson <ulf.hansson@linaro.org>", "target": 0, "dataset": "other", "idx": 386074}
  655. {"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 <no file name> 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}
  656. {"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 \"<no file name>\");\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 <no file name> 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}
  657. {"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+ <stable@vger.kernel.org> # 5.4+\nSigned-off-by: Jason A. Donenfeld <Jason@zx2c4.com>\nSigned-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>", "target": 1, "dataset": "other", "idx": 206866}
  658. {"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+ <stable@vger.kernel.org> # 5.4+\nSigned-off-by: Jason A. Donenfeld <Jason@zx2c4.com>\nSigned-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>", "target": 0, "dataset": "other", "idx": 387888}
  659. {"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)<PATH_MAX) \n\t\t\t\t\tstrcpy(PROC_DISKSTATS_FILE,optarg);\n\t\t\t\tbreak;\n case 1001:\n if (strlen(optarg)<PATH_MAX)\n strcpy(PROC_PARTITIONS_FILE,optarg);\n\t\t\t\tbreak;\n#endif\t\t\t\t\n#if IOSERVICE_IN\n\t\t\tcase 1002:\n\t\t\t\tlong_darwin_disk_names=!long_darwin_disk_names;\n\t\t\t\tbreak;\n#endif\n\t\t\tcase 'D':\n\t\t\t\tif (optarg) daemonize=atoi(optarg);\n\t\t\t\tbreak;\n#ifdef HTML\n\t\t\tcase 'R':\n\t\t\t\tif ((optarg) && atol(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)<PATH_MAX)) strcpy(PROC_FILE,optarg);\n break;\n#endif\t\t\t\n\t\t\tcase 'i':\n if (optarg) {\n input_method=str2in_method(optarg);\n }\n\t\t\t\tbreak;\t\t\t\t\n case 'I':\n if (optarg) iface_list=(char *)strdup(optarg);\n break;\n case 'S':\n if (optarg) sumhidden=atoi(optarg);\n break;\n case 'o':\n if (optarg) {\n output_method=str2out_method(optarg);\n }\n break;\n\t\t\t\tcase 'N':\n\t\t\t\t\t ansi_output=!ansi_output;\n case 'a':\n if (optarg) show_all_if=atoi(optarg);\n break;\n case 't':\n if ((optarg) && atol(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)<PATH_MAX)) strcpy(NETSTAT_FILE,optarg);\n break;\n#endif \n case 'V':\n print_version;\n exit(EXIT_SUCCESS);\n break;\n }\n }\n if (iface_list==NULL && show_all_if==1) show_all_if=2;\n#if EXTENDED_STATS \n /* default init of avg_length */\n if (avg_length==0) {\n if (delay<AVG_LENGTH/2) \n avg_length=AVG_LENGTH; \n else \n avg_length=(delay*2)+1;\n } else /* avg_length was set via cmdline or config file, better check it */\n if (delay*2>=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}
  660. {"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)<PATH_MAX) \n\t\t\t\t\tstrcpy(PROC_DISKSTATS_FILE,optarg);\n\t\t\t\tbreak;\n case 1001:\n if (strlen(optarg)<PATH_MAX)\n strcpy(PROC_PARTITIONS_FILE,optarg);\n\t\t\t\tbreak;\n#endif\t\t\t\t\n#if IOSERVICE_IN\n\t\t\tcase 1002:\n\t\t\t\tlong_darwin_disk_names=!long_darwin_disk_names;\n\t\t\t\tbreak;\n#endif\n\t\t\tcase 'D':\n\t\t\t\tif (optarg) daemonize=atoi(optarg);\n\t\t\t\tbreak;\n#ifdef HTML\n\t\t\tcase 'R':\n\t\t\t\tif ((optarg) && atol(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)<PATH_MAX)) strcpy(PROC_FILE,optarg);\n break;\n#endif\t\t\t\n\t\t\tcase 'i':\n if (optarg) {\n input_method=str2in_method(optarg);\n }\n\t\t\t\tbreak;\t\t\t\t\n case 'I':\n if (optarg) iface_list=(char *)strdup(optarg);\n break;\n case 'S':\n if (optarg) sumhidden=atoi(optarg);\n break;\n case 'o':\n if (optarg) {\n output_method=str2out_method(optarg);\n }\n break;\n\t\t\t\tcase 'N':\n\t\t\t\t\t ansi_output=!ansi_output;\n case 'a':\n if (optarg) show_all_if=atoi(optarg);\n break;\n case 't':\n if ((optarg) && atol(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)<PATH_MAX)) strcpy(NETSTAT_FILE,optarg);\n break;\n#endif \n case 'V':\n print_version;\n exit(EXIT_SUCCESS);\n break;\n }\n }\n if (iface_list==NULL && show_all_if==1) show_all_if=2;\n#if EXTENDED_STATS \n /* default init of avg_length */\n if (avg_length==0) {\n if (delay<AVG_LENGTH/2) \n avg_length=AVG_LENGTH; \n else \n avg_length=(delay*2)+1;\n } else /* avg_length was set via cmdline or config file, better check it */\n if (delay*2>=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}
  661. {"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}
  662. {"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}
  663. {"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}
  664. {"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}
  665. {"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}
  666. {"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}
  667. {"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}
  668. {"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}
  669. {"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 <kt0755@gmail.com>\nSigned-off-by: Zqiang <qiang.zhang@windriver.com>\nSigned-off-by: Felipe Balbi <balbi@kernel.org>", "target": 1, "dataset": "other", "idx": 206932}
  670. {"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 <kt0755@gmail.com>\nSigned-off-by: Zqiang <qiang.zhang@windriver.com>\nSigned-off-by: Felipe Balbi <balbi@kernel.org>", "target": 0, "dataset": "other", "idx": 389362}
  671. {"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}
  672. {"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}
  673. {"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}
  674. {"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}
  675. {"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}
  676. {"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}
  677. {"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; i<pConst->nConst; 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}
  678. {"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; i<pConst->nConst; 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}
  679. {"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}
  680. {"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}
  681. {"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}
  682. {"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}
  683. {"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}
  684. {"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}
  685. {"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 <willmcvicker@google.com>\n[pablo@netfilter.org: rebased original patch on top of nf.git]\nSigned-off-by: Pablo Neira Ayuso <pablo@netfilter.org>", "target": 1, "dataset": "other", "idx": 207223}
  686. {"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 <willmcvicker@google.com>\n[pablo@netfilter.org: rebased original patch on top of nf.git]\nSigned-off-by: Pablo Neira Ayuso <pablo@netfilter.org>", "target": 0, "dataset": "other", "idx": 394260}
  687. {"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}
  688. {"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}
  689. {"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}
  690. {"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}
  691. {"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}
  692. {"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}
  693. {"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}
  694. {"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}
  695. {"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 <orcohen@paloaltonetworks.com>\nReviewed-by: Xin Long <lucien.xin@gmail.com>\nFixes: 610236587600 (\"bpf: Add new cgroup attach type to enable sock modifications\")\nSigned-off-by: Or Cohen <orcohen@paloaltonetworks.com>\nAcked-by: Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 1, "dataset": "other", "idx": 207478}
  696. {"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 <orcohen@paloaltonetworks.com>\nReviewed-by: Xin Long <lucien.xin@gmail.com>\nFixes: 610236587600 (\"bpf: Add new cgroup attach type to enable sock modifications\")\nSigned-off-by: Or Cohen <orcohen@paloaltonetworks.com>\nAcked-by: Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 0, "dataset": "other", "idx": 398128}
  697. {"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 <stable@vger.kernel.org> # 4.12\nCc: Remigiusz Ko\u0142\u0142\u0105taj <remigiusz.kollataj@mobica.com>\nReported-by: syzbot+e29b17e5042bbc56fae9@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold <johan@kernel.org>\nSigned-off-by: Marc Kleine-Budde <mkl@pengutronix.de>", "target": 1, "dataset": "other", "idx": 207488}
  698. {"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 <stable@vger.kernel.org> # 4.12\nCc: Remigiusz Ko\u0142\u0142\u0105taj <remigiusz.kollataj@mobica.com>\nReported-by: syzbot+e29b17e5042bbc56fae9@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold <johan@kernel.org>\nSigned-off-by: Marc Kleine-Budde <mkl@pengutronix.de>", "target": 0, "dataset": "other", "idx": 398308}
  699. {"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}
  700. {"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}
  701. {"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}
  702. {"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}
  703. {"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 <yong.liu@intel.com>\nReviewed-by: Maxime Coquelin <maxime.coquelin@redhat.com>", "target": 1, "dataset": "other", "idx": 207646}
  704. {"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 <yong.liu@intel.com>\nReviewed-by: Maxime Coquelin <maxime.coquelin@redhat.com>", "target": 0, "dataset": "other", "idx": 399931}
  705. {"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}
  706. {"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}
  707. {"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}
  708. {"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}
  709. {"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;ii<nn;ii++)\n fprintf(stderr,\"%02x \",(unsigned char)oout[ii]);\n fprintf(stderr,\"\\n\");\n }\n#endif\n\n return TRUE;\n}", "project": "libvncserver", "hash": 56627314386826006638045179713369898227, "size": 166, "commit_id": "57433015f856cc12753378254ce4f1c78f5d9c7b", "message": "libvncclient: handle half-open TCP connections\n\nWhen a connection is not reset properly at the TCP level (e.g. sudden\npower loss or process crash) the TCP connection becomes half-open and\nread() always returns -1 with errno = EAGAIN while select() always\nreturns 0. This leads to an infinite loop and can be fixed by closing\nthe connection after a certain number of retries (based on a timeout)\nhas been exceeded.", "target": 1, "dataset": "other", "idx": 207769}
  710. {"func": "ReadFromRFBServer(rfbClient* client, char *out, unsigned int n)\n{\n const int USECS_WAIT_PER_RETRY = 100000;\n int retries = 0;\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 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<nn;ii++)\n fprintf(stderr,\"%02x \",(unsigned char)oout[ii]);\n fprintf(stderr,\"\\n\");\n }\n#endif\n\n return TRUE;\n}", "project": "libvncserver", "hash": 96987461285267687729476498662054608847, "size": 180, "commit_id": "57433015f856cc12753378254ce4f1c78f5d9c7b", "message": "libvncclient: handle half-open TCP connections\n\nWhen a connection is not reset properly at the TCP level (e.g. sudden\npower loss or process crash) the TCP connection becomes half-open and\nread() always returns -1 with errno = EAGAIN while select() always\nreturns 0. This leads to an infinite loop and can be fixed by closing\nthe connection after a certain number of retries (based on a timeout)\nhas been exceeded.", "target": 0, "dataset": "other", "idx": 400906}
  711. {"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\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}
  712. {"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}
  713. {"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=<ID=%s,Number=1,Type=String,Description=\\\"Dummy\\\">\", 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 ( r<end )\n {\n // can we skip some samples?\n if ( h->keep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *r!='\\t' && r<end ) r++;\n if ( *r=='\\t' ) { *r = 0; r++; }\n continue;\n }\n }\n\n // collect fmt stats: max vector size, length, number of alleles\n j = 0; // j-th format field\n fmt_aux_t *f = fmt;\n for (;;) {\n switch (*r) {\n case ',':\n m++;\n break;\n\n case '|':\n case '/':\n if (f->is_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 ( t<end )\n {\n // can we skip some samples?\n if ( h->keep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *t && t<end ) t++;\n t++;\n continue;\n }\n }\n if ( m == bcf_hdr_nsamples(h) ) break;\n\n j = 0; // j-th format field, m-th sample\n while ( t < end )\n {\n fmt_aux_t *z = &fmt[j++];\n if (!z->buf) {\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_val<BCF_MIN_BT_INT32 || tmp_val>BCF_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}
  714. {"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=<ID=%s,Number=1,Type=String,Description=\\\"Dummy\\\">\", 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 ( r<end )\n {\n // can we skip some samples?\n if ( h->keep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *r!='\\t' && r<end ) r++;\n if ( *r=='\\t' ) { *r = 0; r++; }\n continue;\n }\n }\n\n // collect fmt stats: max vector size, length, number of alleles\n j = 0; // j-th format field\n fmt_aux_t *f = fmt;\n for (;;) {\n switch (*r) {\n case ',':\n m++;\n break;\n\n case '|':\n case '/':\n if (f->is_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 ( t<end )\n {\n // can we skip some samples?\n if ( h->keep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *t && t<end ) t++;\n t++;\n continue;\n }\n }\n if ( m == bcf_hdr_nsamples(h) ) break;\n\n j = 0; // j-th format field, m-th sample\n while ( t < end )\n {\n fmt_aux_t *z = &fmt[j++];\n if (!z->buf) {\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_val<BCF_MIN_BT_INT32 || tmp_val>BCF_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}
  715. {"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 <linma@zju.edu.cn>\nCc: Marcel Holtmann <marcel@holtmann.org>\nFixes: 7c6a329e4447 (\"[Bluetooth] Fix regression from using default link policy\")\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 1, "dataset": "other", "idx": 207859}
  716. {"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 <linma@zju.edu.cn>\nCc: Marcel Holtmann <marcel@holtmann.org>\nFixes: 7c6a329e4447 (\"[Bluetooth] Fix regression from using default link policy\")\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 0, "dataset": "other", "idx": 402494}
  717. {"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}
  718. {"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}
  719. {"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 <jra@samba.org>", "target": 1, "dataset": "other", "idx": 207975}
  720. {"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 <jra@samba.org>", "target": 0, "dataset": "other", "idx": 403809}
  721. {"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}
  722. {"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}
  723. {"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 <npiggin@gmail.com>\nTested-by: Paolo Bonzini <pbonzini@redhat.com>\nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 1, "dataset": "other", "idx": 207984}
  724. {"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 <npiggin@gmail.com>\nTested-by: Paolo Bonzini <pbonzini@redhat.com>\nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 0, "dataset": "other", "idx": 404071}
  725. {"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}
  726. {"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}
  727. {"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}
  728. {"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}
  729. {"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 <stefanb@linux.ibm.com>", "target": 1, "dataset": "other", "idx": 208069}
  730. {"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 <stefanb@linux.ibm.com>", "target": 0, "dataset": "other", "idx": 404492}
  731. {"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}
  732. {"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}
  733. {"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}
  734. {"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}
  735. {"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 <smcv@collabora.com>\nPart-of: https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2", "target": 1, "dataset": "other", "idx": 208226}
  736. {"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 <smcv@collabora.com>\nPart-of: https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2", "target": 0, "dataset": "other", "idx": 406983}
  737. {"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 <ppandit@redhat.com>\nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 <philmd@redhat.com>\nSigned-off-by: Jason Wang <jasowang@redhat.com>", "target": 1, "dataset": "other", "idx": 208328}
  738. {"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 <ppandit@redhat.com>\nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 <philmd@redhat.com>\nSigned-off-by: Jason Wang <jasowang@redhat.com>", "target": 0, "dataset": "other", "idx": 408536}
  739. {"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 <navid.emamdoost@gmail.com>\nLink: https://lore.kernel.org/r/20190917224713.26371-1-navid.emamdoost@gmail.com\nSigned-off-by: Stefan Schmidt <stefan@datenfreihafen.org>", "target": 1, "dataset": "other", "idx": 208360}
  740. {"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 <navid.emamdoost@gmail.com>\nLink: https://lore.kernel.org/r/20190917224713.26371-1-navid.emamdoost@gmail.com\nSigned-off-by: Stefan Schmidt <stefan@datenfreihafen.org>", "target": 0, "dataset": "other", "idx": 408790}
  741. {"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}
  742. {"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}
  743. {"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}
  744. {"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}
  745. {"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}
  746. {"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}
  747. {"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: <stable@vger.kernel.org>\nFixes: c0efd232929c (\"V4L/DVB (8145a): USB Video Class driver\")\nReported-by: Andrey Konovalov <andreyknvl@google.com>\nSigned-off-by: Will Deacon <will@kernel.org>\nSigned-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>\nSigned-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>", "target": 1, "dataset": "other", "idx": 208387}
  748. {"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: <stable@vger.kernel.org>\nFixes: c0efd232929c (\"V4L/DVB (8145a): USB Video Class driver\")\nReported-by: Andrey Konovalov <andreyknvl@google.com>\nSigned-off-by: Will Deacon <will@kernel.org>\nSigned-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>\nSigned-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>", "target": 0, "dataset": "other", "idx": 409209}
  749. {"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}
  750. {"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}
  751. {"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}
  752. {"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}
  753. {"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 <kzak@redhat.com>", "target": 1, "dataset": "other", "idx": 208443}
  754. {"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 <kzak@redhat.com>", "target": 0, "dataset": "other", "idx": 410433}
  755. {"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 <marco.gra@gmail.com>\nSigned-off-by: Eric Dumazet <edumazet@google.com>\nCc: Ilpo J\u00e4rvinen <ilpo.jarvinen@helsinki.fi>\nCc: Yuchung Cheng <ycheng@google.com>\nCc: Neal Cardwell <ncardwell@google.com>\nAcked-by: Neal Cardwell <ncardwell@google.com>\nReviewed-by: Cong Wang <xiyou.wangcong@gmail.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 1, "dataset": "other", "idx": 208465}
  756. {"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 <marco.gra@gmail.com>\nSigned-off-by: Eric Dumazet <edumazet@google.com>\nCc: Ilpo J\u00e4rvinen <ilpo.jarvinen@helsinki.fi>\nCc: Yuchung Cheng <ycheng@google.com>\nCc: Neal Cardwell <ncardwell@google.com>\nAcked-by: Neal Cardwell <ncardwell@google.com>\nReviewed-by: Cong Wang <xiyou.wangcong@gmail.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 0, "dataset": "other", "idx": 410730}
  757. {"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}
  758. {"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}
  759. {"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}
  760. {"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}
  761. {"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}
  762. {"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}
  763. {"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}
  764. {"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}
  765. {"func": "HRESULT Http::HrReadHeaders()\n{\n\tHRESULT hr;\n\tstd::string strBuffer;\n\tULONG n = 0;\n\tstd::map<std::string, std::string>::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: <value hidden>\");\n\t\telse\n\t\t\tec_log_debug(\"< \"+strBuffer);\n\t\t++n;\n\t} while(hr == hrSuccess);\n\n\thr = HrParseHeaders();\n\tif (hr != hrSuccess)\n\t\thr_ldebug(hr, \"parsing headers failed\");\n\treturn hr;\n}", "project": "kopano-core", "hash": 252899856337214612444746933964237135309, "size": 48, "commit_id": "512457466b87039c6a8d25887fdaca6173619546", "message": "Set limit on header size to prevent bad alloc\n\nThis sets a hard limit of 64 KiB to the header to prevent a memory\nallocation exception from being thrown during the parsing of the request\nheaders.", "target": 1, "dataset": "other", "idx": 208547}
  766. {"func": "HRESULT Http::HrReadHeaders()\n{\n\tHRESULT hr;\n\tstd::string strBuffer;\n\tULONG n = 0;\n\tstd::map<std::string, std::string>::iterator iHeader = mapHeaders.end();\n\tstatic constexpr std::size_t MAX_HEADER_LENGTH = 65536;\n\tstd::size_t numOfBytesRead = 0;\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\tnumOfBytesRead += strBuffer.size();\n\t\tif(numOfBytesRead > MAX_HEADER_LENGTH) {\n\t\t\treturn MAPI_E_TOO_BIG;\n\t\t}\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: <value hidden>\");\n\t\telse\n\t\t\tec_log_debug(\"< \"+strBuffer);\n\t\t++n;\n\t} while(hr == hrSuccess);\n\n\thr = HrParseHeaders();\n\tif (hr != hrSuccess)\n\t\thr_ldebug(hr, \"parsing headers failed\");\n\treturn hr;\n}", "project": "kopano-core", "hash": 80967487134144399005768631526292358142, "size": 55, "commit_id": "512457466b87039c6a8d25887fdaca6173619546", "message": "Set limit on header size to prevent bad alloc\n\nThis sets a hard limit of 64 KiB to the header to prevent a memory\nallocation exception from being thrown during the parsing of the request\nheaders.", "target": 0, "dataset": "other", "idx": 412620}
  767. {"func": "ImagingLibTiffDecode(\n Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes) {\n TIFFSTATE *clientstate = (TIFFSTATE *)state->context;\n char *filename = \"tempfile.tif\";\n char *mode = \"r\";\n TIFF *tiff;\n uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR\n int isYCbCr = 0;\n\n /* buffer is the encoded file, bytes is the length of the encoded file */\n /* it all ends up in state->buffer, which is a uint8* from Imaging.h */\n\n TRACE((\"in decoder: bytes %d\\n\", bytes));\n TRACE(\n (\"State: count %d, state %d, x %d, y %d, ystep %d\\n\",\n state->count,\n state->state,\n state->x,\n state->y,\n state->ystep));\n TRACE(\n (\"State: xsize %d, ysize %d, xoff %d, yoff %d \\n\",\n state->xsize,\n state->ysize,\n state->xoff,\n state->yoff));\n TRACE((\"State: bits %d, bytes %d \\n\", state->bits, state->bytes));\n TRACE(\n (\"Buffer: %p: %c%c%c%c\\n\",\n buffer,\n (char)buffer[0],\n (char)buffer[1],\n (char)buffer[2],\n (char)buffer[3]));\n TRACE(\n (\"State->Buffer: %c%c%c%c\\n\",\n (char)state->buffer[0],\n (char)state->buffer[1],\n (char)state->buffer[2],\n (char)state->buffer[3]));\n TRACE(\n (\"Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \\n\",\n im->mode,\n im->type,\n im->bands,\n im->xsize,\n im->ysize));\n TRACE(\n (\"Image: image8 %p, image32 %p, image %p, block %p \\n\",\n im->image8,\n im->image32,\n im->image,\n im->block));\n TRACE((\"Image: pixelsize: %d, linesize %d \\n\", im->pixelsize, im->linesize));\n\n dump_state(clientstate);\n clientstate->size = bytes;\n clientstate->eof = clientstate->size;\n clientstate->loc = 0;\n clientstate->data = (tdata_t)buffer;\n clientstate->flrealloc = 0;\n dump_state(clientstate);\n\n TIFFSetWarningHandler(NULL);\n TIFFSetWarningHandlerExt(NULL);\n\n if (clientstate->fp) {\n TRACE((\"Opening using fd: %d\\n\", clientstate->fp));\n lseek(clientstate->fp, 0, SEEK_SET); // Sometimes, I get it set to the end.\n tiff = TIFFFdOpen(fd_to_tiff_fd(clientstate->fp), filename, mode);\n } else {\n TRACE((\"Opening from string\\n\"));\n tiff = TIFFClientOpen(\n filename,\n mode,\n (thandle_t)clientstate,\n _tiffReadProc,\n _tiffWriteProc,\n _tiffSeekProc,\n _tiffCloseProc,\n _tiffSizeProc,\n _tiffMapProc,\n _tiffUnmapProc);\n }\n\n if (!tiff) {\n TRACE((\"Error, didn't get the tiff\\n\"));\n state->errcode = IMAGING_CODEC_BROKEN;\n return -1;\n }\n\n if (clientstate->ifd) {\n int rv;\n uint32 ifdoffset = clientstate->ifd;\n TRACE((\"reading tiff ifd %u\\n\", ifdoffset));\n rv = TIFFSetSubDirectory(tiff, ifdoffset);\n if (!rv) {\n TRACE((\"error in TIFFSetSubDirectory\"));\n goto decode_err;\n }\n }\n\n TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric);\n isYCbCr = photometric == PHOTOMETRIC_YCBCR;\n\n if (TIFFIsTiled(tiff)) {\n INT32 x, y, tile_y;\n UINT32 tile_width, tile_length, current_tile_length, current_line,\n current_tile_width, row_byte_size;\n UINT8 *new_data;\n\n TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width);\n TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length);\n\n /* overflow check for row_byte_size calculation */\n if ((UINT32)INT_MAX / state->bits < tile_width) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decode_err;\n }\n\n if (isYCbCr) {\n row_byte_size = tile_width * 4;\n /* sanity check, we use this value in shuffle below */\n if (im->pixelsize != 4) {\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decode_err;\n }\n } else {\n // We could use TIFFTileSize, but for YCbCr data it returns subsampled data\n // size\n row_byte_size = (tile_width * state->bits + 7) / 8;\n }\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < tile_length) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decode_err;\n }\n\n state->bytes = row_byte_size * tile_length;\n\n if (TIFFTileSize(tiff) > state->bytes) {\n // If the strip size as expected by LibTiff isn't what we're expecting,\n // abort.\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decode_err;\n }\n\n /* realloc to fit whole tile */\n /* malloc check above */\n new_data = realloc(state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decode_err;\n }\n\n state->buffer = new_data;\n\n TRACE((\"TIFFTileSize: %d\\n\", state->bytes));\n\n for (y = state->yoff; y < state->ysize; y += tile_length) {\n for (x = state->xoff; x < state->xsize; x += tile_width) {\n if (isYCbCr) {\n /* To avoid dealing with YCbCr subsampling, let libtiff handle it */\n if (!TIFFReadRGBATile(tiff, x, y, (UINT32 *)state->buffer)) {\n TRACE((\"Decode Error, Tile at %dx%d\\n\", x, y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decode_err;\n }\n } else {\n if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, 0) == -1) {\n TRACE((\"Decode Error, Tile at %dx%d\\n\", x, y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decode_err;\n }\n }\n\n TRACE((\"Read tile at %dx%d; \\n\\n\", x, y));\n\n current_tile_width = min((INT32)tile_width, state->xsize - x);\n current_tile_length = min((INT32)tile_length, state->ysize - y);\n // iterate over each line in the tile and stuff data into image\n for (tile_y = 0; tile_y < current_tile_length; tile_y++) {\n TRACE(\n (\"Writing tile data at %dx%d using tile_width: %d; \\n\",\n tile_y + y,\n x,\n current_tile_width));\n\n // UINT8 * bbb = state->buffer + tile_y * row_byte_size;\n // TRACE((\"chars: %x%x%x%x\\n\", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1],\n // ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n /*\n * For some reason the TIFFReadRGBATile() function\n * chooses the lower left corner as the origin.\n * Vertically mirror by shuffling the scanlines\n * backwards\n */\n\n if (isYCbCr) {\n current_line = tile_length - tile_y - 1;\n } else {\n current_line = tile_y;\n }\n\n state->shuffle(\n (UINT8 *)im->image[tile_y + y] + x * im->pixelsize,\n state->buffer + current_line * row_byte_size,\n current_tile_width);\n }\n }\n }\n } else {\n if (!isYCbCr) {\n _decodeStrip(im, state, tiff);\n } else {\n _decodeStripYCbCr(im, state, tiff);\n }\n }\n\ndecode_err:\n TIFFClose(tiff);\n TRACE((\"Done Decoding, Returning \\n\"));\n // Returning -1 here to force ImageFile.load to break, rather than\n // even think about looping back around.\n return -1;\n}", "project": "Pillow", "hash": 337949595576035235304375695306533039366, "size": 227, "commit_id": "cbdce6c5d054fccaf4af34b47f212355c64ace7a", "message": "Fix for CVE-2021-25291\n\n* Invalid tile boundaries lead to OOB Read in TiffDecode.c, in TiffReadRGBATile\n* Check the tile validity before attempting to read.", "target": 1, "dataset": "other", "idx": 208556}
  768. {"func": "ImagingLibTiffDecode(\n Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes) {\n TIFFSTATE *clientstate = (TIFFSTATE *)state->context;\n char *filename = \"tempfile.tif\";\n char *mode = \"r\";\n TIFF *tiff;\n uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR\n int isYCbCr = 0;\n\n /* buffer is the encoded file, bytes is the length of the encoded file */\n /* it all ends up in state->buffer, which is a uint8* from Imaging.h */\n\n TRACE((\"in decoder: bytes %d\\n\", bytes));\n TRACE(\n (\"State: count %d, state %d, x %d, y %d, ystep %d\\n\",\n state->count,\n state->state,\n state->x,\n state->y,\n state->ystep));\n TRACE(\n (\"State: xsize %d, ysize %d, xoff %d, yoff %d \\n\",\n state->xsize,\n state->ysize,\n state->xoff,\n state->yoff));\n TRACE((\"State: bits %d, bytes %d \\n\", state->bits, state->bytes));\n TRACE(\n (\"Buffer: %p: %c%c%c%c\\n\",\n buffer,\n (char)buffer[0],\n (char)buffer[1],\n (char)buffer[2],\n (char)buffer[3]));\n TRACE(\n (\"State->Buffer: %c%c%c%c\\n\",\n (char)state->buffer[0],\n (char)state->buffer[1],\n (char)state->buffer[2],\n (char)state->buffer[3]));\n TRACE(\n (\"Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \\n\",\n im->mode,\n im->type,\n im->bands,\n im->xsize,\n im->ysize));\n TRACE(\n (\"Image: image8 %p, image32 %p, image %p, block %p \\n\",\n im->image8,\n im->image32,\n im->image,\n im->block));\n TRACE((\"Image: pixelsize: %d, linesize %d \\n\", im->pixelsize, im->linesize));\n\n dump_state(clientstate);\n clientstate->size = bytes;\n clientstate->eof = clientstate->size;\n clientstate->loc = 0;\n clientstate->data = (tdata_t)buffer;\n clientstate->flrealloc = 0;\n dump_state(clientstate);\n\n TIFFSetWarningHandler(NULL);\n TIFFSetWarningHandlerExt(NULL);\n\n if (clientstate->fp) {\n TRACE((\"Opening using fd: %d\\n\", clientstate->fp));\n lseek(clientstate->fp, 0, SEEK_SET); // Sometimes, I get it set to the end.\n tiff = TIFFFdOpen(fd_to_tiff_fd(clientstate->fp), filename, mode);\n } else {\n TRACE((\"Opening from string\\n\"));\n tiff = TIFFClientOpen(\n filename,\n mode,\n (thandle_t)clientstate,\n _tiffReadProc,\n _tiffWriteProc,\n _tiffSeekProc,\n _tiffCloseProc,\n _tiffSizeProc,\n _tiffMapProc,\n _tiffUnmapProc);\n }\n\n if (!tiff) {\n TRACE((\"Error, didn't get the tiff\\n\"));\n state->errcode = IMAGING_CODEC_BROKEN;\n return -1;\n }\n\n if (clientstate->ifd) {\n int rv;\n uint32 ifdoffset = clientstate->ifd;\n TRACE((\"reading tiff ifd %u\\n\", ifdoffset));\n rv = TIFFSetSubDirectory(tiff, ifdoffset);\n if (!rv) {\n TRACE((\"error in TIFFSetSubDirectory\"));\n goto decode_err;\n }\n }\n\n TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric);\n isYCbCr = photometric == PHOTOMETRIC_YCBCR;\n\n if (TIFFIsTiled(tiff)) {\n INT32 x, y, tile_y;\n UINT32 tile_width, tile_length, current_tile_length, current_line,\n current_tile_width, row_byte_size;\n UINT8 *new_data;\n\n TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width);\n TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length);\n\n /* overflow check for row_byte_size calculation */\n if ((UINT32)INT_MAX / state->bits < tile_width) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decode_err;\n }\n\n if (isYCbCr) {\n row_byte_size = tile_width * 4;\n /* sanity check, we use this value in shuffle below */\n if (im->pixelsize != 4) {\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decode_err;\n }\n } else {\n // We could use TIFFTileSize, but for YCbCr data it returns subsampled data\n // size\n row_byte_size = (tile_width * state->bits + 7) / 8;\n }\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < tile_length) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decode_err;\n }\n\n state->bytes = row_byte_size * tile_length;\n\n if (TIFFTileSize(tiff) > state->bytes) {\n // If the strip size as expected by LibTiff isn't what we're expecting,\n // abort.\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decode_err;\n }\n\n /* realloc to fit whole tile */\n /* malloc check above */\n new_data = realloc(state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decode_err;\n }\n\n state->buffer = new_data;\n\n TRACE((\"TIFFTileSize: %d\\n\", state->bytes));\n\n for (y = state->yoff; y < state->ysize; y += tile_length) {\n for (x = state->xoff; x < state->xsize; x += tile_width) {\n /* Sanity Check. Apparently in some cases, the TiffReadRGBA* functions\n have a different view of the size of the tiff than we're getting from\n other functions. So, we need to check here. \n */\n if (!TIFFCheckTile(tiff, x, y, 0, 0)) {\n TRACE((\"Check Tile Error, Tile at %dx%d\\n\", x, y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decode_err;\n }\n if (isYCbCr) {\n /* To avoid dealing with YCbCr subsampling, let libtiff handle it */\n if (!TIFFReadRGBATile(tiff, x, y, (UINT32 *)state->buffer)) {\n TRACE((\"Decode Error, Tile at %dx%d\\n\", x, y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decode_err;\n }\n } else {\n if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, 0) == -1) {\n TRACE((\"Decode Error, Tile at %dx%d\\n\", x, y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decode_err;\n }\n }\n\n TRACE((\"Read tile at %dx%d; \\n\\n\", x, y));\n\n current_tile_width = min((INT32)tile_width, state->xsize - x);\n current_tile_length = min((INT32)tile_length, state->ysize - y);\n // iterate over each line in the tile and stuff data into image\n for (tile_y = 0; tile_y < current_tile_length; tile_y++) {\n TRACE(\n (\"Writing tile data at %dx%d using tile_width: %d; \\n\",\n tile_y + y,\n x,\n current_tile_width));\n\n // UINT8 * bbb = state->buffer + tile_y * row_byte_size;\n // TRACE((\"chars: %x%x%x%x\\n\", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1],\n // ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n /*\n * For some reason the TIFFReadRGBATile() function\n * chooses the lower left corner as the origin.\n * Vertically mirror by shuffling the scanlines\n * backwards\n */\n\n if (isYCbCr) {\n current_line = tile_length - tile_y - 1;\n } else {\n current_line = tile_y;\n }\n\n state->shuffle(\n (UINT8 *)im->image[tile_y + y] + x * im->pixelsize,\n state->buffer + current_line * row_byte_size,\n current_tile_width);\n }\n }\n }\n } else {\n if (!isYCbCr) {\n _decodeStrip(im, state, tiff);\n } else {\n _decodeStripYCbCr(im, state, tiff);\n }\n }\n\ndecode_err:\n TIFFClose(tiff);\n TRACE((\"Done Decoding, Returning \\n\"));\n // Returning -1 here to force ImageFile.load to break, rather than\n // even think about looping back around.\n return -1;\n}", "project": "Pillow", "hash": 201448095726443829294002981038733584513, "size": 236, "commit_id": "cbdce6c5d054fccaf4af34b47f212355c64ace7a", "message": "Fix for CVE-2021-25291\n\n* Invalid tile boundaries lead to OOB Read in TiffDecode.c, in TiffReadRGBATile\n* Check the tile validity before attempting to read.", "target": 0, "dataset": "other", "idx": 412799}
  769. {"func": "mt76_add_fragment(struct mt76_dev *dev, struct mt76_queue *q, void *data,\n\t\t int len, bool more)\n{\n\tstruct page *page = virt_to_head_page(data);\n\tint offset = data - page_address(page);\n\tstruct sk_buff *skb = q->rx_head;\n\n\toffset += q->buf_offset;\n\tskb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset, len,\n\t\t\tq->buf_size);\n\n\tif (more)\n\t\treturn;\n\n\tq->rx_head = NULL;\n\tdev->drv->rx_skb(dev, q - dev->q_rx, skb);\n}", "project": "linux", "hash": 146050973517401472759282716419538748236, "size": 17, "commit_id": "b102f0c522cf668c8382c56a4f771b37d011cda2", "message": "mt76: fix array overflow on receiving too many fragments for a packet\n\nIf the hardware receives an oversized packet with too many rx fragments,\nskb_shinfo(skb)->frags can overflow and corrupt memory of adjacent pages.\nThis becomes especially visible if it corrupts the freelist pointer of\na slab page.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Felix Fietkau <nbd@nbd.name>\nSigned-off-by: Kalle Valo <kvalo@codeaurora.org>", "target": 1, "dataset": "other", "idx": 208640}
  770. {"func": "mt76_add_fragment(struct mt76_dev *dev, struct mt76_queue *q, void *data,\n\t\t int len, bool more)\n{\n\tstruct page *page = virt_to_head_page(data);\n\tint offset = data - page_address(page);\n\tstruct sk_buff *skb = q->rx_head;\n\tstruct skb_shared_info *shinfo = skb_shinfo(skb);\n\n\tif (shinfo->nr_frags < ARRAY_SIZE(shinfo->frags)) {\n\t\toffset += q->buf_offset;\n\t\tskb_add_rx_frag(skb, shinfo->nr_frags, page, offset, len,\n\t\t\t\tq->buf_size);\n\t}\n\n\tif (more)\n\t\treturn;\n\n\tq->rx_head = NULL;\n\tdev->drv->rx_skb(dev, q - dev->q_rx, skb);\n}", "project": "linux", "hash": 257436133503741741969364886008365609105, "size": 20, "commit_id": "b102f0c522cf668c8382c56a4f771b37d011cda2", "message": "mt76: fix array overflow on receiving too many fragments for a packet\n\nIf the hardware receives an oversized packet with too many rx fragments,\nskb_shinfo(skb)->frags can overflow and corrupt memory of adjacent pages.\nThis becomes especially visible if it corrupts the freelist pointer of\na slab page.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Felix Fietkau <nbd@nbd.name>\nSigned-off-by: Kalle Valo <kvalo@codeaurora.org>", "target": 0, "dataset": "other", "idx": 413227}
  771. {"func": "ext_get_plugin(const char *name, const char *module, const char *revision)\n{\n uint16_t u;\n\n assert(name);\n assert(module);\n\n for (u = 0; u < ext_plugins_count; u++) {\n if (!strcmp(name, ext_plugins[u].name) &&\n !strcmp(module, ext_plugins[u].module) &&\n (!ext_plugins[u].revision || !strcmp(revision, ext_plugins[u].revision))) {\n /* we have the match */\n return ext_plugins[u].plugin;\n }\n }\n\n /* plugin not found */\n return NULL;\n}", "project": "libyang", "hash": 218030599751924346754684311149140190519, "size": 19, "commit_id": "59a0bff1a5a2f0a0eac07e4bf94d4aea9dd3708d", "message": "plugins BUGFIX handle empty revision correctly\n\nFixes #1451", "target": 1, "dataset": "other", "idx": 208672}
  772. {"func": "ext_get_plugin(const char *name, const char *module, const char *revision)\n{\n uint16_t u;\n\n assert(name);\n assert(module);\n\n for (u = 0; u < ext_plugins_count; u++) {\n if (!strcmp(name, ext_plugins[u].name) && !strcmp(module, ext_plugins[u].module) &&\n ((!revision && !ext_plugins[u].revision) || (revision && !strcmp(revision, ext_plugins[u].revision)))) {\n /* we have the match */\n return ext_plugins[u].plugin;\n }\n }\n\n /* plugin not found */\n return NULL;\n}", "project": "libyang", "hash": 206226070812095655612586328288084046946, "size": 18, "commit_id": "59a0bff1a5a2f0a0eac07e4bf94d4aea9dd3708d", "message": "plugins BUGFIX handle empty revision correctly\n\nFixes #1451", "target": 0, "dataset": "other", "idx": 413412}
  773. {"func": "FastHufDecoder::FastHufDecoder\n (const char *&table,\n int numBytes,\n int minSymbol,\n int maxSymbol,\n int rleSymbol)\n:\n _rleSymbol (rleSymbol),\n _numSymbols (0),\n _minCodeLength (255),\n _maxCodeLength (0),\n _idToSymbol (0)\n{\n //\n // List of symbols that we find with non-zero code lengths\n // (listed in the order we find them). Store these in the\n // same format as the code book stores codes + lengths - \n // low 6 bits are the length, everything above that is\n // the symbol.\n //\n\n std::vector<Int64> symbols;\n\n //\n // The 'base' table is the minimum code at each code length. base[i]\n // is the smallest code (numerically) of length i.\n //\n\n Int64 base[MAX_CODE_LEN + 1]; \n\n //\n // The 'offset' table is the position (in sorted order) of the first id\n // of a given code lenght. Array is indexed by code length, like base. \n //\n\n Int64 offset[MAX_CODE_LEN + 1]; \n\n //\n // Count of how many codes at each length there are. Array is \n // indexed by code length, like base and offset.\n //\n\n size_t codeCount[MAX_CODE_LEN + 1]; \n\n for (int i = 0; i <= MAX_CODE_LEN; ++i)\n {\n codeCount[i] = 0;\n base[i] = 0xffffffffffffffffULL;\n offset[i] = 0;\n }\n\n //\n // Count the number of codes, the min/max code lengths, the number of\n // codes with each length, and record symbols with non-zero code\n // length as we find them.\n //\n\n const char *currByte = table;\n Int64 currBits = 0;\n int currBitCount = 0;\n\n const int SHORT_ZEROCODE_RUN = 59;\n const int LONG_ZEROCODE_RUN = 63;\n const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;\n\n for (Int64 symbol = static_cast<Int64>(minSymbol); symbol <= static_cast<Int64>(maxSymbol); symbol++)\n {\n if (currByte - table > numBytes)\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Truncated table data).\");\n }\n\n //\n // Next code length - either:\n // 0-58 (literal code length)\n // 59-62 (various lengths runs of 0)\n // 63 (run of n 0's, with n is the next 8 bits)\n //\n\n Int64 codeLen = readBits (6, currBits, currBitCount, currByte);\n\n if (codeLen == (Int64) LONG_ZEROCODE_RUN)\n {\n if (currByte - table > numBytes)\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Truncated table data).\");\n }\n\n int runLen = readBits (8, currBits, currBitCount, currByte) +\n SHORTEST_LONG_RUN;\n\n if (symbol + runLen > static_cast<Int64>(maxSymbol + 1))\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Run beyond end of table).\");\n }\n \n symbol += runLen - 1;\n\n }\n else if (codeLen >= static_cast<Int64>(SHORT_ZEROCODE_RUN))\n {\n int runLen = codeLen - SHORT_ZEROCODE_RUN + 2;\n\n if (symbol + runLen > static_cast<Int64>(maxSymbol + 1))\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Run beyond end of table).\");\n }\n\n symbol += runLen - 1;\n\n }\n else if (codeLen != 0)\n {\n symbols.push_back ((symbol << 6) | (codeLen & 63));\n\n if (codeLen < _minCodeLength)\n _minCodeLength = codeLen;\n\n if (codeLen > _maxCodeLength)\n _maxCodeLength = codeLen;\n\n codeCount[codeLen]++;\n }\n }\n\n for (int i = 0; i < MAX_CODE_LEN; ++i)\n _numSymbols += codeCount[i];\n\n table = currByte;\n\n //\n // Compute base - once we have the code length counts, there\n // is a closed form solution for this\n //\n\n {\n double* countTmp = new double[_maxCodeLength+1];\n\n for (int l = _minCodeLength; l <= _maxCodeLength; ++l)\n {\n countTmp[l] = (double)codeCount[l] * \n (double)(2 << (_maxCodeLength-l));\n }\n \n for (int l = _minCodeLength; l <= _maxCodeLength; ++l)\n {\n double tmp = 0;\n\n for (int k =l + 1; k <= _maxCodeLength; ++k)\n tmp += countTmp[k];\n \n tmp /= (double)(2 << (_maxCodeLength - l));\n\n base[l] = (Int64)ceil (tmp);\n }\n\n delete [] countTmp;\n }\n \n //\n // Compute offset - these are the positions of the first\n // id (not symbol) that has length [i]\n //\n\n offset[_maxCodeLength] = 0;\n\n for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--)\n offset[i] = offset[i + 1] + codeCount[i + 1];\n\n //\n // Allocate and fill the symbol-to-id mapping. Smaller Ids should be\n // mapped to less-frequent symbols (which have longer codes). Use\n // the offset table to tell us where the id's for a given code \n // length start off.\n //\n\n _idToSymbol = new int[_numSymbols];\n\n Int64 mapping[MAX_CODE_LEN + 1];\n for (int i = 0; i < MAX_CODE_LEN + 1; ++i) \n mapping[i] = -1;\n for (int i = _minCodeLength; i <= _maxCodeLength; ++i)\n mapping[i] = offset[i];\n\n for (std::vector<Int64>::const_iterator i = symbols.begin(); \n i != symbols.end();\n ++i)\n {\n int codeLen = *i & 63;\n int symbol = *i >> 6;\n\n if (mapping[codeLen] >= static_cast<Int64>(_numSymbols))\n {\n delete[] _idToSymbol;\n _idToSymbol = NULL;\n throw IEX_NAMESPACE::InputExc (\"Huffman decode error \"\n \"(Invalid symbol in header).\");\n }\n _idToSymbol[mapping[codeLen]] = symbol;\n mapping[codeLen]++;\n }\n\n //\n // exceptions can be thrown whilst building tables. Delete\n // _idToSynmbol before re-throwing to prevent memory leak\n //\n try\n {\n buildTables(base, offset);\n }catch(...)\n {\n delete[] _idToSymbol;\n _idToSymbol = NULL;\n throw;\n }\n}", "project": "openexr", "hash": 295327035492456381923444384031538504049, "size": 220, "commit_id": "c3ed4a1db1f39bf4524a644cb2af81dc8cfab33f", "message": "compute Huf codelengths using 64 bit to prevent shift overflow\n\nSigned-off-by: Peter Hillman <peterh@wetafx.co.nz>", "target": 1, "dataset": "other", "idx": 208675}
  774. {"func": "FastHufDecoder::FastHufDecoder\n (const char *&table,\n int numBytes,\n int minSymbol,\n int maxSymbol,\n int rleSymbol)\n:\n _rleSymbol (rleSymbol),\n _numSymbols (0),\n _minCodeLength (255),\n _maxCodeLength (0),\n _idToSymbol (0)\n{\n //\n // List of symbols that we find with non-zero code lengths\n // (listed in the order we find them). Store these in the\n // same format as the code book stores codes + lengths - \n // low 6 bits are the length, everything above that is\n // the symbol.\n //\n\n std::vector<Int64> symbols;\n\n //\n // The 'base' table is the minimum code at each code length. base[i]\n // is the smallest code (numerically) of length i.\n //\n\n Int64 base[MAX_CODE_LEN + 1]; \n\n //\n // The 'offset' table is the position (in sorted order) of the first id\n // of a given code lenght. Array is indexed by code length, like base. \n //\n\n Int64 offset[MAX_CODE_LEN + 1]; \n\n //\n // Count of how many codes at each length there are. Array is \n // indexed by code length, like base and offset.\n //\n\n size_t codeCount[MAX_CODE_LEN + 1]; \n\n for (int i = 0; i <= MAX_CODE_LEN; ++i)\n {\n codeCount[i] = 0;\n base[i] = 0xffffffffffffffffULL;\n offset[i] = 0;\n }\n\n //\n // Count the number of codes, the min/max code lengths, the number of\n // codes with each length, and record symbols with non-zero code\n // length as we find them.\n //\n\n const char *currByte = table;\n Int64 currBits = 0;\n int currBitCount = 0;\n\n const int SHORT_ZEROCODE_RUN = 59;\n const int LONG_ZEROCODE_RUN = 63;\n const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;\n\n for (Int64 symbol = static_cast<Int64>(minSymbol); symbol <= static_cast<Int64>(maxSymbol); symbol++)\n {\n if (currByte - table > numBytes)\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Truncated table data).\");\n }\n\n //\n // Next code length - either:\n // 0-58 (literal code length)\n // 59-62 (various lengths runs of 0)\n // 63 (run of n 0's, with n is the next 8 bits)\n //\n\n Int64 codeLen = readBits (6, currBits, currBitCount, currByte);\n\n if (codeLen == (Int64) LONG_ZEROCODE_RUN)\n {\n if (currByte - table > numBytes)\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Truncated table data).\");\n }\n\n int runLen = readBits (8, currBits, currBitCount, currByte) +\n SHORTEST_LONG_RUN;\n\n if (symbol + runLen > static_cast<Int64>(maxSymbol + 1))\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Run beyond end of table).\");\n }\n \n symbol += runLen - 1;\n\n }\n else if (codeLen >= static_cast<Int64>(SHORT_ZEROCODE_RUN))\n {\n int runLen = codeLen - SHORT_ZEROCODE_RUN + 2;\n\n if (symbol + runLen > static_cast<Int64>(maxSymbol + 1))\n {\n throw IEX_NAMESPACE::InputExc (\"Error decoding Huffman table \"\n \"(Run beyond end of table).\");\n }\n\n symbol += runLen - 1;\n\n }\n else if (codeLen != 0)\n {\n symbols.push_back ((symbol << 6) | (codeLen & 63));\n\n if (codeLen < _minCodeLength)\n _minCodeLength = codeLen;\n\n if (codeLen > _maxCodeLength)\n _maxCodeLength = codeLen;\n\n codeCount[codeLen]++;\n }\n }\n\n for (int i = 0; i < MAX_CODE_LEN; ++i)\n _numSymbols += codeCount[i];\n\n table = currByte;\n\n //\n // Compute base - once we have the code length counts, there\n // is a closed form solution for this\n //\n\n {\n double* countTmp = new double[_maxCodeLength+1];\n\n for (int l = _minCodeLength; l <= _maxCodeLength; ++l)\n {\n countTmp[l] = (double)codeCount[l] * \n (double)(2ll << (_maxCodeLength-l));\n }\n \n for (int l = _minCodeLength; l <= _maxCodeLength; ++l)\n {\n double tmp = 0;\n\n for (int k =l + 1; k <= _maxCodeLength; ++k)\n tmp += countTmp[k];\n \n tmp /= (double)(2ll << (_maxCodeLength - l));\n\n base[l] = (Int64)ceil (tmp);\n }\n\n delete [] countTmp;\n }\n \n //\n // Compute offset - these are the positions of the first\n // id (not symbol) that has length [i]\n //\n\n offset[_maxCodeLength] = 0;\n\n for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--)\n offset[i] = offset[i + 1] + codeCount[i + 1];\n\n //\n // Allocate and fill the symbol-to-id mapping. Smaller Ids should be\n // mapped to less-frequent symbols (which have longer codes). Use\n // the offset table to tell us where the id's for a given code \n // length start off.\n //\n\n _idToSymbol = new int[_numSymbols];\n\n Int64 mapping[MAX_CODE_LEN + 1];\n for (int i = 0; i < MAX_CODE_LEN + 1; ++i) \n mapping[i] = -1;\n for (int i = _minCodeLength; i <= _maxCodeLength; ++i)\n mapping[i] = offset[i];\n\n for (std::vector<Int64>::const_iterator i = symbols.begin(); \n i != symbols.end();\n ++i)\n {\n int codeLen = *i & 63;\n int symbol = *i >> 6;\n\n if (mapping[codeLen] >= static_cast<Int64>(_numSymbols))\n {\n delete[] _idToSymbol;\n _idToSymbol = NULL;\n throw IEX_NAMESPACE::InputExc (\"Huffman decode error \"\n \"(Invalid symbol in header).\");\n }\n _idToSymbol[mapping[codeLen]] = symbol;\n mapping[codeLen]++;\n }\n\n //\n // exceptions can be thrown whilst building tables. Delete\n // _idToSynmbol before re-throwing to prevent memory leak\n //\n try\n {\n buildTables(base, offset);\n }catch(...)\n {\n delete[] _idToSymbol;\n _idToSymbol = NULL;\n throw;\n }\n}", "project": "openexr", "hash": 153643357904600972132151102261211578620, "size": 220, "commit_id": "c3ed4a1db1f39bf4524a644cb2af81dc8cfab33f", "message": "compute Huf codelengths using 64 bit to prevent shift overflow\n\nSigned-off-by: Peter Hillman <peterh@wetafx.co.nz>", "target": 0, "dataset": "other", "idx": 413449}
  775. {"func": "static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */\n{\n\tconst char *oldname = NULL;\n\tchar *oldpath = NULL;\n\tchar *basename = NULL, *basepath = NULL;\n\tchar *newname = NULL, *newpath = NULL;\n\tzval *ret, arg1;\n\tzend_class_entry *ce;\n\tchar *error;\n\tconst char *pcr_error;\n\tint ext_len = ext ? strlen(ext) : 0;\n\tint oldname_len;\n\tphar_archive_data **pphar = NULL;\n\tphp_stream_statbuf ssb;\n\n\tif (!ext) {\n\t\tif (phar->is_zip) {\n\n\t\t\tif (phar->is_data) {\n\t\t\t\text = \"zip\";\n\t\t\t} else {\n\t\t\t\text = \"phar.zip\";\n\t\t\t}\n\n\t\t} else if (phar->is_tar) {\n\n\t\t\tswitch (phar->flags) {\n\t\t\t\tcase PHAR_FILE_COMPRESSED_GZ:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar.gz\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar.gz\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHAR_FILE_COMPRESSED_BZ2:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar.bz2\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar.bz2\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar\";\n\t\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\n\t\t\tswitch (phar->flags) {\n\t\t\t\tcase PHAR_FILE_COMPRESSED_GZ:\n\t\t\t\t\text = \"phar.gz\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHAR_FILE_COMPRESSED_BZ2:\n\t\t\t\t\text = \"phar.bz2\";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\text = \"phar\";\n\t\t\t}\n\t\t}\n\t} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {\n\n\t\tif (phar->is_data) {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t} else {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tif (ext[0] == '.') {\n\t\t++ext;\n\t}\n\n\toldpath = estrndup(phar->fname, phar->fname_len);\n\toldname = zend_memrchr(phar->fname, '/', phar->fname_len);\n\t++oldname;\n\toldname_len = strlen(oldname);\n\n\tbasename = estrndup(oldname, oldname_len);\n\tspprintf(&newname, 0, \"%s.%s\", strtok(basename, \".\"), ext);\n\tefree(basename);\n\n\t\n\n\tbasepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));\n\tphar->fname_len = spprintf(&newpath, 0, \"%s%s\", basepath, newname);\n\tphar->fname = newpath;\n\tphar->ext = newpath + phar->fname_len - strlen(ext) - 1;\n\tefree(basepath);\n\tefree(newname);\n\n\tif (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, new phar name is in phar.cache_list\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tif (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {\n\t\tif ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {\n\t\t\tif (!zend_hash_num_elements(&phar->manifest)) {\n\t\t\t\t(*pphar)->is_tar = phar->is_tar;\n\t\t\t\t(*pphar)->is_zip = phar->is_zip;\n\t\t\t\t(*pphar)->is_data = phar->is_data;\n\t\t\t\t(*pphar)->flags = phar->flags;\n\t\t\t\t(*pphar)->fp = phar->fp;\n\t\t\t\tphar->fp = NULL;\n\t\t\t\tphar_destroy_phar_data(phar TSRMLS_CC);\n\t\t\t\tphar = *pphar;\n\t\t\t\tphar->refcount++;\n\t\t\t\tnewpath = oldpath;\n\t\t\t\tgoto its_ok;\n\t\t\t}\n\t\t}\n\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, a phar with that name already exists\", phar->fname);\n\t\treturn NULL;\n\t}\nits_ok:\n\tif (SUCCESS == php_stream_stat_path(newpath, &ssb)) {\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" exists and must be unlinked prior to conversion\", newpath);\n\t\treturn NULL;\n\t}\n\tif (!phar->is_data) {\n\t\tif (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {\n\t\t\tefree(oldpath);\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (phar->alias) {\n\t\t\tif (phar->is_temporary_alias) {\n\t\t\t\tphar->alias = NULL;\n\t\t\t\tphar->alias_len = 0;\n\t\t\t} else {\n\t\t\t\tphar->alias = estrndup(newpath, strlen(newpath));\n\t\t\t\tphar->alias_len = strlen(newpath);\n\t\t\t\tphar->is_temporary_alias = 1;\n\t\t\t\tzend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);\n\t\t\t}\n\t\t}\n\n\t} else {\n\n\t\tif (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {\n\t\t\tefree(oldpath);\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tphar->alias = NULL;\n\t\tphar->alias_len = 0;\n\t}\n\n\tif ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tphar_flush(phar, 0, 0, 1, &error TSRMLS_CC);\n\n\tif (error) {\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"%s\", error);\n\t\tefree(error);\n\t\tefree(oldpath);\n\t\treturn NULL;\n\t}\n\n\tefree(oldpath);\n\n\tif (phar->is_data) {\n\t\tce = phar_ce_data;\n\t} else {\n\t\tce = phar_ce_archive;\n\t}\n\n\tMAKE_STD_ZVAL(ret);\n\n\tif (SUCCESS != object_init_ex(ret, ce)) {\n\t\tzval_dtor(ret);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate phar object when converting archive \\\"%s\\\"\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tINIT_PZVAL(&arg1);\n\tZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);\n\n\tzend_call_method_with_1_params(&ret, ce, &ce->constructor, \"__construct\", NULL, &arg1);\n\treturn ret;\n}", "project": "php-src", "hash": 55514648493563640623085659819286233714, "size": 194, "commit_id": "b2cf3f064b8f5efef89bb084521b61318c71781b", "message": "Fixed bug #68901 (use after free)", "target": 1, "dataset": "other", "idx": 208677}
  776. {"func": "static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */\n{\n\tconst char *oldname = NULL;\n\tchar *oldpath = NULL;\n\tchar *basename = NULL, *basepath = NULL;\n\tchar *newname = NULL, *newpath = NULL;\n\tzval *ret, arg1;\n\tzend_class_entry *ce;\n\tchar *error;\n\tconst char *pcr_error;\n\tint ext_len = ext ? strlen(ext) : 0;\n\tint oldname_len;\n\tphar_archive_data **pphar = NULL;\n\tphp_stream_statbuf ssb;\n\n\tif (!ext) {\n\t\tif (phar->is_zip) {\n\n\t\t\tif (phar->is_data) {\n\t\t\t\text = \"zip\";\n\t\t\t} else {\n\t\t\t\text = \"phar.zip\";\n\t\t\t}\n\n\t\t} else if (phar->is_tar) {\n\n\t\t\tswitch (phar->flags) {\n\t\t\t\tcase PHAR_FILE_COMPRESSED_GZ:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar.gz\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar.gz\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHAR_FILE_COMPRESSED_BZ2:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar.bz2\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar.bz2\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tif (phar->is_data) {\n\t\t\t\t\t\text = \"tar\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\text = \"phar.tar\";\n\t\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\n\t\t\tswitch (phar->flags) {\n\t\t\t\tcase PHAR_FILE_COMPRESSED_GZ:\n\t\t\t\t\text = \"phar.gz\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHAR_FILE_COMPRESSED_BZ2:\n\t\t\t\t\text = \"phar.bz2\";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\text = \"phar\";\n\t\t\t}\n\t\t}\n\t} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {\n\n\t\tif (phar->is_data) {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t} else {\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tif (ext[0] == '.') {\n\t\t++ext;\n\t}\n\n\toldpath = estrndup(phar->fname, phar->fname_len);\n\toldname = zend_memrchr(phar->fname, '/', phar->fname_len);\n\t++oldname;\n\toldname_len = strlen(oldname);\n\n\tbasename = estrndup(oldname, oldname_len);\n\tspprintf(&newname, 0, \"%s.%s\", strtok(basename, \".\"), ext);\n\tefree(basename);\n\n\t\n\n\tbasepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));\n\tphar->fname_len = spprintf(&newpath, 0, \"%s%s\", basepath, newname);\n\tphar->fname = newpath;\n\tphar->ext = newpath + phar->fname_len - strlen(ext) - 1;\n\tefree(basepath);\n\tefree(newname);\n\n\tif (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, new phar name is in phar.cache_list\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tif (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {\n\t\tif ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {\n\t\t\tif (!zend_hash_num_elements(&phar->manifest)) {\n\t\t\t\t(*pphar)->is_tar = phar->is_tar;\n\t\t\t\t(*pphar)->is_zip = phar->is_zip;\n\t\t\t\t(*pphar)->is_data = phar->is_data;\n\t\t\t\t(*pphar)->flags = phar->flags;\n\t\t\t\t(*pphar)->fp = phar->fp;\n\t\t\t\tphar->fp = NULL;\n\t\t\t\tphar_destroy_phar_data(phar TSRMLS_CC);\n\t\t\t\tphar = *pphar;\n\t\t\t\tphar->refcount++;\n\t\t\t\tnewpath = oldpath;\n\t\t\t\tgoto its_ok;\n\t\t\t}\n\t\t}\n\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, a phar with that name already exists\", phar->fname);\n\t\treturn NULL;\n\t}\nits_ok:\n\tif (SUCCESS == php_stream_stat_path(newpath, &ssb)) {\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" exists and must be unlinked prior to conversion\", newpath);\n\t\tefree(oldpath);\n\t\treturn NULL;\n\t}\n\tif (!phar->is_data) {\n\t\tif (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {\n\t\t\tefree(oldpath);\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (phar->alias) {\n\t\t\tif (phar->is_temporary_alias) {\n\t\t\t\tphar->alias = NULL;\n\t\t\t\tphar->alias_len = 0;\n\t\t\t} else {\n\t\t\t\tphar->alias = estrndup(newpath, strlen(newpath));\n\t\t\t\tphar->alias_len = strlen(newpath);\n\t\t\t\tphar->is_temporary_alias = 1;\n\t\t\t\tzend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);\n\t\t\t}\n\t\t}\n\n\t} else {\n\n\t\tif (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {\n\t\t\tefree(oldpath);\n\t\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tphar->alias = NULL;\n\t\tphar->alias_len = 0;\n\t}\n\n\tif ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {\n\t\tefree(oldpath);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tphar_flush(phar, 0, 0, 1, &error TSRMLS_CC);\n\n\tif (error) {\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"%s\", error);\n\t\tefree(error);\n\t\tefree(oldpath);\n\t\treturn NULL;\n\t}\n\n\tefree(oldpath);\n\n\tif (phar->is_data) {\n\t\tce = phar_ce_data;\n\t} else {\n\t\tce = phar_ce_archive;\n\t}\n\n\tMAKE_STD_ZVAL(ret);\n\n\tif (SUCCESS != object_init_ex(ret, ce)) {\n\t\tzval_dtor(ret);\n\t\tzend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate phar object when converting archive \\\"%s\\\"\", phar->fname);\n\t\treturn NULL;\n\t}\n\n\tINIT_PZVAL(&arg1);\n\tZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);\n\n\tzend_call_method_with_1_params(&ret, ce, &ce->constructor, \"__construct\", NULL, &arg1);\n\treturn ret;\n}", "project": "php-src", "hash": 85820391847910228353825170949751953610, "size": 194, "commit_id": "b2cf3f064b8f5efef89bb084521b61318c71781b", "message": "Fixed bug #68901 (use after free)", "target": 0, "dataset": "other", "idx": 413459}
  777. {"func": "rndr_quote(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;\n\n\tBUFPUTSL(ob, \"<q>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</q>\");\n\n\treturn 1;\n}", "project": "redcarpet", "hash": 339130827029288585257779128996016727908, "size": 11, "commit_id": "a699c82292b17c8e6a62e1914d5eccc252272793", "message": "Fix a security issue using `:quote` with `:escape_html`\n\nReported by @johan-smits.", "target": 1, "dataset": "other", "idx": 208718}
  778. {"func": "rndr_underline(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;\n\n\tBUFPUTSL(ob, \"<u>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</u>\");\n\n\treturn 1;\n}", "project": "redcarpet", "hash": 84760104797261814325900181895738182717, "size": 11, "commit_id": "a699c82292b17c8e6a62e1914d5eccc252272793", "message": "Fix a security issue using `:quote` with `:escape_html`\n\nReported by @johan-smits.", "target": 0, "dataset": "other", "idx": 414517}
  779. {"func": "ppm_load_read_header(FILE *fp,\n pnm_struct *img)\n{\n /* PPM Headers Variable Declaration */\n gchar *ptr;\n //gchar *retval;\n gchar header[MAX_CHARS_IN_ROW];\n gint maxval;\n\n /* Check the PPM file Type P2 or P5 */\n fgets (header,MAX_CHARS_IN_ROW,fp);\n\n if (header[0] != ASCII_P ||\n (header[1] != PIXMAP_ASCII &&\n header[1] != PIXMAP_RAW))\n {\n g_warning (\"Image is not a portable pixmap\");\n return FALSE;\n }\n\n img->type = header[1];\n\n /* Check the Comments */\n fgets (header,MAX_CHARS_IN_ROW,fp);\n while(header[0] == '#')\n {\n fgets (header,MAX_CHARS_IN_ROW,fp);\n }\n\n /* Get Width and Height */\n img->width = strtol (header,&ptr,0);\n img->height = atoi (ptr);\n\n fgets (header,MAX_CHARS_IN_ROW,fp);\n maxval = strtol (header,&ptr,0);\n\n if ((maxval != 255) && (maxval != 65535))\n {\n g_warning (\"Image is not an 8-bit or 16-bit portable pixmap\");\n return FALSE;\n }\n\n switch (maxval)\n {\n case 255:\n img->bpc = sizeof (guchar);\n break;\n\n case 65535:\n img->bpc = sizeof (gushort);\n break;\n\n default:\n g_warning (\"%s: Programmer stupidity error\", G_STRLOC);\n }\n\n /* Later on, img->numsamples is multiplied with img->bpc to allocate\n * memory. Ensure it doesn't overflow. */\n if (!img->width || !img->height ||\n G_MAXSIZE / img->width / img->height / CHANNEL_COUNT < img->bpc)\n {\n g_warning (\"Illegal width/height: %ld/%ld\", img->width, img->height);\n return FALSE;\n }\n img->numsamples = img->width * img->height * CHANNEL_COUNT;\n\n return TRUE;\n}", "project": "gegl", "hash": 156544789859611251475411793449672138344, "size": 68, "commit_id": "4757cdf73d3675478d645a3ec8250ba02168a230", "message": "ppm-load: CVE-2012-4433: add plausibility checks for header fields\n\nRefuse values that are non-decimal, negative or overflow the target\ntype.", "target": 1, "dataset": "other", "idx": 208743}
  780. {"func": "ppm_load_read_header(FILE *fp,\n pnm_struct *img)\n{\n /* PPM Headers Variable Declaration */\n gchar *ptr;\n //gchar *retval;\n gchar header[MAX_CHARS_IN_ROW];\n gint maxval;\n\n /* Check the PPM file Type P2 or P5 */\n fgets (header,MAX_CHARS_IN_ROW,fp);\n\n if (header[0] != ASCII_P ||\n (header[1] != PIXMAP_ASCII &&\n header[1] != PIXMAP_RAW))\n {\n g_warning (\"Image is not a portable pixmap\");\n return FALSE;\n }\n\n img->type = header[1];\n\n /* Check the Comments */\n fgets (header,MAX_CHARS_IN_ROW,fp);\n while(header[0] == '#')\n {\n fgets (header,MAX_CHARS_IN_ROW,fp);\n }\n\n /* Get Width and Height */\n errno = 0;\n img->width = strtol (header,&ptr,10);\n if (errno)\n {\n g_warning (\"Error reading width: %s\", strerror(errno));\n return FALSE;\n }\n else if (img->width < 0)\n {\n g_warning (\"Error: width is negative\");\n return FALSE;\n }\n\n img->height = strtol (ptr,&ptr,10);\n if (errno)\n {\n g_warning (\"Error reading height: %s\", strerror(errno));\n return FALSE;\n }\n else if (img->width < 0)\n {\n g_warning (\"Error: height is negative\");\n return FALSE;\n }\n\n fgets (header,MAX_CHARS_IN_ROW,fp);\n maxval = strtol (header,&ptr,10);\n\n if ((maxval != 255) && (maxval != 65535))\n {\n g_warning (\"Image is not an 8-bit or 16-bit portable pixmap\");\n return FALSE;\n }\n\n switch (maxval)\n {\n case 255:\n img->bpc = sizeof (guchar);\n break;\n\n case 65535:\n img->bpc = sizeof (gushort);\n break;\n\n default:\n g_warning (\"%s: Programmer stupidity error\", G_STRLOC);\n }\n\n /* Later on, img->numsamples is multiplied with img->bpc to allocate\n * memory. Ensure it doesn't overflow. */\n if (!img->width || !img->height ||\n G_MAXSIZE / img->width / img->height / CHANNEL_COUNT < img->bpc)\n {\n g_warning (\"Illegal width/height: %ld/%ld\", img->width, img->height);\n return FALSE;\n }\n img->numsamples = img->width * img->height * CHANNEL_COUNT;\n\n return TRUE;\n}", "project": "gegl", "hash": 2766754304084121512241040743874346746, "size": 90, "commit_id": "4757cdf73d3675478d645a3ec8250ba02168a230", "message": "ppm-load: CVE-2012-4433: add plausibility checks for header fields\n\nRefuse values that are non-decimal, negative or overflow the target\ntype.", "target": 0, "dataset": "other", "idx": 414969}
  781. {"func": "enum_func_status\nphp_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields,\n\t\t\t\t\t\t\t\t\tunsigned int field_count, const MYSQLND_FIELD * fields_metadata,\n\t\t\t\t\t\t\t\t\tzend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC)\n{\n\t\n\tunsigned int i;\n\tzend_bool last_field_was_string = FALSE;\n\tzval **current_field, **end_field, **start_field;\n\tzend_uchar * p = row_buffer->ptr;\n\tsize_t data_size = row_buffer->app;\n\tzend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */\n\n\tDBG_ENTER(\"php_mysqlnd_rowp_read_text_protocol_aux\");\n\n\tif (!fields) {\n\t\tDBG_RETURN(FAIL);\n\t}\n\n\tend_field = (start_field = fields) + field_count;\n\n\tfor (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {\n\t\tDBG_INF(\"Directly creating zval\");\n\t\tMAKE_STD_ZVAL(*current_field);\n\t\tif (!*current_field) {\n\t\t\tDBG_RETURN(FAIL);\n\t\t}\n\t}\n\n\tfor (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {\n\t\t/* Don't reverse the order. It is significant!*/\n\t\tzend_uchar *this_field_len_pos = p;\n\t\t/* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */\n\t\tunsigned long len = php_mysqlnd_net_field_length(&p);\n\n\t\tif (copy_data == FALSE && current_field > start_field && last_field_was_string) {\n\t\t\t/*\n\t\t\t Normal queries:\n\t\t\t We have to put \\0 now to the end of the previous field, if it was\n\t\t\t a string. IS_NULL doesn't matter. Because we have already read our\n\t\t\t length, then we can overwrite it in the row buffer.\n\t\t\t This statement terminates the previous field, not the current one.\n\n\t\t\t NULL_LENGTH is encoded in one byte, so we can stick a \\0 there.\n\t\t\t Any string's length is encoded in at least one byte, so we can stick\n\t\t\t a \\0 there.\n\t\t\t*/\n\n\t\t\t*this_field_len_pos = '\\0';\n\t\t}\n\n\t\t/* NULL or NOT NULL, this is the question! */\n\t\tif (len == MYSQLND_NULL_LENGTH) {\n\t\t\tZVAL_NULL(*current_field);\n\t\t\tlast_field_was_string = FALSE;\n\t\t} else {\n#if defined(MYSQLND_STRING_TO_INT_CONVERSION)\n\t\t\tstruct st_mysqlnd_perm_bind perm_bind =\n\t\t\t\t\tmysqlnd_ps_fetch_functions[fields_metadata[i].type];\n#endif\n\t\t\tif (MYSQLND_G(collect_statistics)) {\n\t\t\t\tenum_mysqlnd_collected_stats statistic;\n\t\t\t\tswitch (fields_metadata[i].type) {\n\t\t\t\t\tcase MYSQL_TYPE_DECIMAL:\tstatistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;\n\t\t\t\t\tcase MYSQL_TYPE_TINY:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT8; break;\n\t\t\t\t\tcase MYSQL_TYPE_SHORT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT16; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONG:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT32; break;\n\t\t\t\t\tcase MYSQL_TYPE_FLOAT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break;\n\t\t\t\t\tcase MYSQL_TYPE_DOUBLE:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break;\n\t\t\t\t\tcase MYSQL_TYPE_NULL:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_NULL; break;\n\t\t\t\t\tcase MYSQL_TYPE_TIMESTAMP:\tstatistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONGLONG:\tstatistic = STAT_TEXT_TYPE_FETCHED_INT64; break;\n\t\t\t\t\tcase MYSQL_TYPE_INT24:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT24; break;\n\t\t\t\t\tcase MYSQL_TYPE_DATE:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_DATE; break;\n\t\t\t\t\tcase MYSQL_TYPE_TIME:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_TIME; break;\n\t\t\t\t\tcase MYSQL_TYPE_DATETIME:\tstatistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break;\n\t\t\t\t\tcase MYSQL_TYPE_YEAR:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_YEAR; break;\n\t\t\t\t\tcase MYSQL_TYPE_NEWDATE:\tstatistic = STAT_TEXT_TYPE_FETCHED_DATE; break;\n\t\t\t\t\tcase MYSQL_TYPE_VARCHAR:\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_BIT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_BIT; break;\n\t\t\t\t\tcase MYSQL_TYPE_NEWDECIMAL:\tstatistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;\n\t\t\t\t\tcase MYSQL_TYPE_ENUM:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_ENUM; break;\n\t\t\t\t\tcase MYSQL_TYPE_SET:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_SET; break;\n\t\t\t\t\tcase MYSQL_TYPE_JSON:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_JSON; break;\n\t\t\t\t\tcase MYSQL_TYPE_TINY_BLOB:\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONG_BLOB:\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_BLOB:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_VAR_STRING:\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_STRING:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_GEOMETRY:\tstatistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break;\n\t\t\t\t\tdefault: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break;\n\t\t\t\t}\n\t\t\t\tMYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len);\n\t\t\t}\n#ifdef MYSQLND_STRING_TO_INT_CONVERSION\n\t\t\tif (as_int_or_float && perm_bind.php_type == IS_LONG) {\n\t\t\t\tzend_uchar save = *(p + len);\n\t\t\t\t/* We have to make it ASCIIZ temporarily */\n\t\t\t\t*(p + len) = '\\0';\n\t\t\t\tif (perm_bind.pack_len < SIZEOF_LONG) {\n\t\t\t\t\t/* direct conversion */\n\t\t\t\t\tint64_t v =\n#ifndef PHP_WIN32\n\t\t\t\t\t\tatoll((char *) p);\n#else\n\t\t\t\t\t\t_atoi64((char *) p);\n#endif\n\t\t\t\t\tZVAL_LONG(*current_field, (long) v); /* the cast is safe */\n\t\t\t\t} else {\n\t\t\t\t\tuint64_t v =\n#ifndef PHP_WIN32\n\t\t\t\t\t\t(uint64_t) atoll((char *) p);\n#else\n\t\t\t\t\t\t(uint64_t) _atoi64((char *) p);\n#endif\n\t\t\t\t\tzend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE;\n\t\t\t\t\t/* We have to make it ASCIIZ temporarily */\n#if SIZEOF_LONG==8\n\t\t\t\t\tif (uns == TRUE && v > 9223372036854775807L)\n#elif SIZEOF_LONG==4\n\t\t\t\t\tif ((uns == TRUE && v > L64(2147483647)) ||\n\t\t\t\t\t\t(uns == FALSE && (( L64(2147483647) < (int64_t) v) ||\n\t\t\t\t\t\t(L64(-2147483648) > (int64_t) v))))\n#else\n#error Need fix for this architecture\n#endif /* SIZEOF */\n\t\t\t\t\t{\n\t\t\t\t\t\tZVAL_STRINGL(*current_field, (char *)p, len, 0);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tZVAL_LONG(*current_field, (long) v); /* the cast is safe */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t*(p + len) = save;\n\t\t\t} else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) {\n\t\t\t\tzend_uchar save = *(p + len);\n\t\t\t\t/* We have to make it ASCIIZ temporarily */\n\t\t\t\t*(p + len) = '\\0';\n\t\t\t\tZVAL_DOUBLE(*current_field, atof((char *) p));\n\t\t\t\t*(p + len) = save;\n\t\t\t} else\n#endif /* MYSQLND_STRING_TO_INT_CONVERSION */\n\t\t\tif (fields_metadata[i].type == MYSQL_TYPE_BIT) {\n\t\t\t\t/*\n\t\t\t\t BIT fields are specially handled. As they come as bit mask, we have\n\t\t\t\t to convert it to human-readable representation. As the bits take\n\t\t\t\t less space in the protocol than the numbers they represent, we don't\n\t\t\t\t have enough space in the packet buffer to overwrite inside.\n\t\t\t\t Thus, a bit more space is pre-allocated at the end of the buffer,\n\t\t\t\t see php_mysqlnd_rowp_read(). And we add the strings at the end.\n\t\t\t\t Definitely not nice, _hackish_ :(, but works.\n\t\t\t\t*/\n\t\t\t\tzend_uchar *start = bit_area;\n\t\t\t\tps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC);\n\t\t\t\t/*\n\t\t\t\t We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because\n\t\t\t\t later in this function there will be an advancement.\n\t\t\t\t*/\n\t\t\t\tp -= len;\n\t\t\t\tif (Z_TYPE_PP(current_field) == IS_LONG) {\n\t\t\t\t\tbit_area += 1 + sprintf((char *)start, \"%ld\", Z_LVAL_PP(current_field));\n\t\t\t\t\tZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);\n\t\t\t\t} else if (Z_TYPE_PP(current_field) == IS_STRING){\n\t\t\t\t\tmemcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field));\n\t\t\t\t\tbit_area += Z_STRLEN_PP(current_field);\n\t\t\t\t\t*bit_area++ = '\\0';\n\t\t\t\t\tzval_dtor(*current_field);\n\t\t\t\t\tZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tZVAL_STRINGL(*current_field, (char *)p, len, copy_data);\n\t\t\t}\n\t\t\tp += len;\n\t\t\tlast_field_was_string = TRUE;\n\t\t}\n\t}\n\tif (copy_data == FALSE && last_field_was_string) {\n\t\t/* Normal queries: The buffer has one more byte at the end, because we need it */\n\t\trow_buffer->ptr[data_size] = '\\0';\n\t}\n\n\tDBG_RETURN(PASS);", "project": "php-src", "hash": 185803420179456454427036827670396437100, "size": 182, "commit_id": "28f80baf3c53e267c9ce46a2a0fadbb981585132", "message": "Fix bug #72293 - Heap overflow in mysqlnd related to BIT fields", "target": 1, "dataset": "other", "idx": 208933}
  782. {"func": "enum_func_status\nphp_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields,\n\t\t\t\t\t\t\t\t\tunsigned int field_count, const MYSQLND_FIELD * fields_metadata,\n\t\t\t\t\t\t\t\t\tzend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC)\n{\n\t\n\tunsigned int i;\n\tzend_bool last_field_was_string = FALSE;\n\tzval **current_field, **end_field, **start_field;\n\tzend_uchar * p = row_buffer->ptr;\n\tsize_t data_size = row_buffer->app;\n\tzend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */\n\tconst zend_uchar * const packet_end = (zend_uchar*) row_buffer->ptr + data_size;\n\n\tDBG_ENTER(\"php_mysqlnd_rowp_read_text_protocol_aux\");\n\n\tif (!fields) {\n\t\tDBG_RETURN(FAIL);\n\t}\n\n\tend_field = (start_field = fields) + field_count;\n\n\tfor (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {\n\t\tDBG_INF(\"Directly creating zval\");\n\t\tMAKE_STD_ZVAL(*current_field);\n\t\tif (!*current_field) {\n\t\t\tDBG_RETURN(FAIL);\n\t\t}\n\t}\n\n\tfor (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {\n\t\t/* Don't reverse the order. It is significant!*/\n\t\tzend_uchar *this_field_len_pos = p;\n\t\t/* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */\n\t\tconst unsigned long len = php_mysqlnd_net_field_length(&p);\n\n\t\tif (len != MYSQLND_NULL_LENGTH && ((p + len) > packet_end)) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Malformed server packet. Field length pointing \"MYSQLND_SZ_T_SPEC\n\t\t\t\t\t\t\t\t\t\t\t \" bytes after end of packet\", (p + len) - packet_end - 1);\n\t\t\tDBG_RETURN(FAIL);\n\t\t}\n\t\tif (copy_data == FALSE && current_field > start_field && last_field_was_string) {\n\t\t\t/*\n\t\t\t Normal queries:\n\t\t\t We have to put \\0 now to the end of the previous field, if it was\n\t\t\t a string. IS_NULL doesn't matter. Because we have already read our\n\t\t\t length, then we can overwrite it in the row buffer.\n\t\t\t This statement terminates the previous field, not the current one.\n\n\t\t\t NULL_LENGTH is encoded in one byte, so we can stick a \\0 there.\n\t\t\t Any string's length is encoded in at least one byte, so we can stick\n\t\t\t a \\0 there.\n\t\t\t*/\n\n\t\t\t*this_field_len_pos = '\\0';\n\t\t}\n\n\t\t/* NULL or NOT NULL, this is the question! */\n\t\tif (len == MYSQLND_NULL_LENGTH) {\n\t\t\tZVAL_NULL(*current_field);\n\t\t\tlast_field_was_string = FALSE;\n\t\t} else {\n#if defined(MYSQLND_STRING_TO_INT_CONVERSION)\n\t\t\tstruct st_mysqlnd_perm_bind perm_bind =\n\t\t\t\t\tmysqlnd_ps_fetch_functions[fields_metadata[i].type];\n#endif\n\t\t\tif (MYSQLND_G(collect_statistics)) {\n\t\t\t\tenum_mysqlnd_collected_stats statistic;\n\t\t\t\tswitch (fields_metadata[i].type) {\n\t\t\t\t\tcase MYSQL_TYPE_DECIMAL:\tstatistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;\n\t\t\t\t\tcase MYSQL_TYPE_TINY:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT8; break;\n\t\t\t\t\tcase MYSQL_TYPE_SHORT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT16; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONG:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT32; break;\n\t\t\t\t\tcase MYSQL_TYPE_FLOAT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break;\n\t\t\t\t\tcase MYSQL_TYPE_DOUBLE:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break;\n\t\t\t\t\tcase MYSQL_TYPE_NULL:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_NULL; break;\n\t\t\t\t\tcase MYSQL_TYPE_TIMESTAMP:\tstatistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONGLONG:\tstatistic = STAT_TEXT_TYPE_FETCHED_INT64; break;\n\t\t\t\t\tcase MYSQL_TYPE_INT24:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_INT24; break;\n\t\t\t\t\tcase MYSQL_TYPE_DATE:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_DATE; break;\n\t\t\t\t\tcase MYSQL_TYPE_TIME:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_TIME; break;\n\t\t\t\t\tcase MYSQL_TYPE_DATETIME:\tstatistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break;\n\t\t\t\t\tcase MYSQL_TYPE_YEAR:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_YEAR; break;\n\t\t\t\t\tcase MYSQL_TYPE_NEWDATE:\tstatistic = STAT_TEXT_TYPE_FETCHED_DATE; break;\n\t\t\t\t\tcase MYSQL_TYPE_VARCHAR:\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_BIT:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_BIT; break;\n\t\t\t\t\tcase MYSQL_TYPE_NEWDECIMAL:\tstatistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;\n\t\t\t\t\tcase MYSQL_TYPE_ENUM:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_ENUM; break;\n\t\t\t\t\tcase MYSQL_TYPE_SET:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_SET; break;\n\t\t\t\t\tcase MYSQL_TYPE_JSON:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_JSON; break;\n\t\t\t\t\tcase MYSQL_TYPE_TINY_BLOB:\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_LONG_BLOB:\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_BLOB:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;\n\t\t\t\t\tcase MYSQL_TYPE_VAR_STRING:\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_STRING:\t\tstatistic = STAT_TEXT_TYPE_FETCHED_STRING; break;\n\t\t\t\t\tcase MYSQL_TYPE_GEOMETRY:\tstatistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break;\n\t\t\t\t\tdefault: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break;\n\t\t\t\t}\n\t\t\t\tMYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len);\n\t\t\t}\n#ifdef MYSQLND_STRING_TO_INT_CONVERSION\n\t\t\tif (as_int_or_float && perm_bind.php_type == IS_LONG) {\n\t\t\t\tzend_uchar save = *(p + len);\n\t\t\t\t/* We have to make it ASCIIZ temporarily */\n\t\t\t\t*(p + len) = '\\0';\n\t\t\t\tif (perm_bind.pack_len < SIZEOF_LONG) {\n\t\t\t\t\t/* direct conversion */\n\t\t\t\t\tint64_t v =\n#ifndef PHP_WIN32\n\t\t\t\t\t\tatoll((char *) p);\n#else\n\t\t\t\t\t\t_atoi64((char *) p);\n#endif\n\t\t\t\t\tZVAL_LONG(*current_field, (long) v); /* the cast is safe */\n\t\t\t\t} else {\n\t\t\t\t\tuint64_t v =\n#ifndef PHP_WIN32\n\t\t\t\t\t\t(uint64_t) atoll((char *) p);\n#else\n\t\t\t\t\t\t(uint64_t) _atoi64((char *) p);\n#endif\n\t\t\t\t\tzend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE;\n\t\t\t\t\t/* We have to make it ASCIIZ temporarily */\n#if SIZEOF_LONG==8\n\t\t\t\t\tif (uns == TRUE && v > 9223372036854775807L)\n#elif SIZEOF_LONG==4\n\t\t\t\t\tif ((uns == TRUE && v > L64(2147483647)) ||\n\t\t\t\t\t\t(uns == FALSE && (( L64(2147483647) < (int64_t) v) ||\n\t\t\t\t\t\t(L64(-2147483648) > (int64_t) v))))\n#else\n#error Need fix for this architecture\n#endif /* SIZEOF */\n\t\t\t\t\t{\n\t\t\t\t\t\tZVAL_STRINGL(*current_field, (char *)p, len, 0);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tZVAL_LONG(*current_field, (long) v); /* the cast is safe */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t*(p + len) = save;\n\t\t\t} else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) {\n\t\t\t\tzend_uchar save = *(p + len);\n\t\t\t\t/* We have to make it ASCIIZ temporarily */\n\t\t\t\t*(p + len) = '\\0';\n\t\t\t\tZVAL_DOUBLE(*current_field, atof((char *) p));\n\t\t\t\t*(p + len) = save;\n\t\t\t} else\n#endif /* MYSQLND_STRING_TO_INT_CONVERSION */\n\t\t\tif (fields_metadata[i].type == MYSQL_TYPE_BIT) {\n\t\t\t\t/*\n\t\t\t\t BIT fields are specially handled. As they come as bit mask, we have\n\t\t\t\t to convert it to human-readable representation. As the bits take\n\t\t\t\t less space in the protocol than the numbers they represent, we don't\n\t\t\t\t have enough space in the packet buffer to overwrite inside.\n\t\t\t\t Thus, a bit more space is pre-allocated at the end of the buffer,\n\t\t\t\t see php_mysqlnd_rowp_read(). And we add the strings at the end.\n\t\t\t\t Definitely not nice, _hackish_ :(, but works.\n\t\t\t\t*/\n\t\t\t\tzend_uchar *start = bit_area;\n\t\t\t\tps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC);\n\t\t\t\t/*\n\t\t\t\t We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because\n\t\t\t\t later in this function there will be an advancement.\n\t\t\t\t*/\n\t\t\t\tp -= len;\n\t\t\t\tif (Z_TYPE_PP(current_field) == IS_LONG) {\n\t\t\t\t\tbit_area += 1 + sprintf((char *)start, \"%ld\", Z_LVAL_PP(current_field));\n\t\t\t\t\tZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);\n\t\t\t\t} else if (Z_TYPE_PP(current_field) == IS_STRING){\n\t\t\t\t\tmemcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field));\n\t\t\t\t\tbit_area += Z_STRLEN_PP(current_field);\n\t\t\t\t\t*bit_area++ = '\\0';\n\t\t\t\t\tzval_dtor(*current_field);\n\t\t\t\t\tZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tZVAL_STRINGL(*current_field, (char *)p, len, copy_data);\n\t\t\t}\n\t\t\tp += len;\n\t\t\tlast_field_was_string = TRUE;\n\t\t}\n\t}\n\tif (copy_data == FALSE && last_field_was_string) {\n\t\t/* Normal queries: The buffer has one more byte at the end, because we need it */\n\t\trow_buffer->ptr[data_size] = '\\0';\n\t}\n\n\tDBG_RETURN(PASS);", "project": "php-src", "hash": 325703409906620959975800534935313037728, "size": 188, "commit_id": "28f80baf3c53e267c9ce46a2a0fadbb981585132", "message": "Fix bug #72293 - Heap overflow in mysqlnd related to BIT fields", "target": 0, "dataset": "other", "idx": 416671}
  783. {"func": "static void cil_reset_classperms_set(struct cil_classperms_set *cp_set)\n{\n\tcil_reset_classpermission(cp_set->set);\n}", "project": "selinux", "hash": 228898186887741153148874390102479645011, "size": 4, "commit_id": "c49a8ea09501ad66e799ea41b8154b6770fec2c8", "message": "libsepol/cil: cil_reset_classperms_set() should not reset classpermission\n\nIn struct cil_classperms_set, the set field is a pointer to a\nstruct cil_classpermission which is looked up in the symbol table.\nSince the cil_classperms_set does not create the cil_classpermission,\nit should not reset it.\n\nSet the set field to NULL instead of resetting the classpermission\nthat it points to.\n\nSigned-off-by: James Carter <jwcart2@gmail.com>", "target": 1, "dataset": "other", "idx": 208940}
  784. {"func": "static void cil_reset_classpermissionset(struct cil_classpermissionset *cps)\n{\n\tcil_reset_classperms_list(cps->classperms);\n}", "project": "selinux", "hash": 235137699480676414178363936394519566185, "size": 4, "commit_id": "c49a8ea09501ad66e799ea41b8154b6770fec2c8", "message": "libsepol/cil: cil_reset_classperms_set() should not reset classpermission\n\nIn struct cil_classperms_set, the set field is a pointer to a\nstruct cil_classpermission which is looked up in the symbol table.\nSince the cil_classperms_set does not create the cil_classpermission,\nit should not reset it.\n\nSet the set field to NULL instead of resetting the classpermission\nthat it points to.\n\nSigned-off-by: James Carter <jwcart2@gmail.com>", "target": 0, "dataset": "other", "idx": 416786}
  785. {"func": "void APar_ExtractDetails(FILE *isofile, uint8_t optional_output) {\n char uint32_buffer[5];\n Trackage track = {0};\n\n AtomicInfo *mvhdAtom = APar_FindAtom(\"moov.mvhd\", false, VERSIONED_ATOM, 0);\n if (mvhdAtom != NULL) {\n APar_ExtractMovieDetails(uint32_buffer, isofile, mvhdAtom);\n fprintf(stdout,\n \"Movie duration: %.3lf seconds (%s) - %.2lf* kbp/sec bitrate \"\n \"(*=approximate)\\n\",\n movie_info.seconds,\n secsTOtime(movie_info.seconds),\n movie_info.simple_bitrate_calc);\n if (optional_output & SHOW_DATE_INFO) {\n fprintf(stdout,\n \" Presentation Creation Date (UTC): %s\\n\",\n APar_extract_UTC(movie_info.creation_time));\n fprintf(stdout,\n \" Presentation Modification Date (UTC): %s\\n\",\n APar_extract_UTC(movie_info.modified_time));\n }\n }\n\n AtomicInfo *iodsAtom = APar_FindAtom(\"moov.iods\", false, VERSIONED_ATOM, 0);\n if (iodsAtom != NULL) {\n movie_info.contains_iods = true;\n APar_Extract_iods_Info(isofile, iodsAtom);\n }\n\n if (optional_output & SHOW_TRACK_INFO) {\n APar_TrackLevelInfo(&track,\n NULL); // With track_num set to 0, it will return the\n // total trak atom into total_tracks here.\n\n fprintf(\n stdout, \"Low-level details. Total tracks: %u\\n\", track.total_tracks);\n fprintf(stdout,\n \"Trk Type Handler Kind Lang Bytes\\n\");\n\n if (track.total_tracks > 0) {\n while (track.total_tracks > track.track_num) {\n track.track_num += 1;\n TrackInfo track_info = {0};\n\n // tracknum, handler type, handler name\n APar_ExtractTrackDetails(uint32_buffer, isofile, &track, &track_info);\n uint16_t more_whitespace =\n purge_extraneous_characters(track_info.track_hdlr_name);\n\n if (strlen(track_info.track_hdlr_name) == 0) {\n memcpy(track_info.track_hdlr_name, \"[none listed]\", 13);\n }\n fprintf(stdout,\n \"%u %s %s\",\n track.track_num,\n uint32tochar4(track_info.track_type, uint32_buffer),\n track_info.track_hdlr_name);\n\n uint16_t handler_len = strlen(track_info.track_hdlr_name);\n if (handler_len < 25 + more_whitespace) {\n for (uint16_t i = handler_len; i < 25 + more_whitespace; i++) {\n fprintf(stdout, \" \");\n }\n }\n\n // codec, language\n fprintf(stdout,\n \" %s %s %\" PRIu64,\n uint32tochar4(track_info.track_codec, uint32_buffer),\n track_info.unpacked_lang,\n track_info.sample_aggregate);\n\n if (track_info.encoder_name[0] != 0 && track_info.contains_esds) {\n purge_extraneous_characters(track_info.encoder_name);\n fprintf(stdout, \" Encoder: %s\", track_info.encoder_name);\n }\n if (track_info.type_of_track & DRM_PROTECTED_TRACK) {\n fprintf(stdout,\n \" (protected %s)\",\n uint32tochar4(track_info.protected_codec, uint32_buffer));\n }\n\n fprintf(stdout, \"\\n\");\n /*---------------------------------*/\n\n if (track_info.type_of_track & VIDEO_TRACK ||\n track_info.type_of_track & AUDIO_TRACK) {\n APar_Print_TrackDetails(&track_info);\n }\n\n if (optional_output & SHOW_DATE_INFO) {\n fprintf(stdout,\n \" Creation Date (UTC): %s\\n\",\n APar_extract_UTC(track_info.creation_time));\n fprintf(stdout,\n \" Modification Date (UTC): %s\\n\",\n APar_extract_UTC(track_info.modified_time));\n }\n }\n }\n }\n}", "project": "atomicparsley", "hash": 235760196453077041717585104526456578938, "size": 102, "commit_id": "d72ccf06c98259d7261e0f3ac4fd8717778782c1", "message": "Avoid stack overflow\n\nrefs: https://github.com/wez/atomicparsley/issues/32", "target": 1, "dataset": "other", "idx": 208981}
  786. {"func": "void APar_ExtractDetails(FILE *isofile, uint8_t optional_output) {\n char uint32_buffer[8];\n Trackage track = {0};\n\n AtomicInfo *mvhdAtom = APar_FindAtom(\"moov.mvhd\", false, VERSIONED_ATOM, 0);\n if (mvhdAtom != NULL) {\n APar_ExtractMovieDetails(uint32_buffer, isofile, mvhdAtom);\n fprintf(stdout,\n \"Movie duration: %.3lf seconds (%s) - %.2lf* kbp/sec bitrate \"\n \"(*=approximate)\\n\",\n movie_info.seconds,\n secsTOtime(movie_info.seconds),\n movie_info.simple_bitrate_calc);\n if (optional_output & SHOW_DATE_INFO) {\n fprintf(stdout,\n \" Presentation Creation Date (UTC): %s\\n\",\n APar_extract_UTC(movie_info.creation_time));\n fprintf(stdout,\n \" Presentation Modification Date (UTC): %s\\n\",\n APar_extract_UTC(movie_info.modified_time));\n }\n }\n\n AtomicInfo *iodsAtom = APar_FindAtom(\"moov.iods\", false, VERSIONED_ATOM, 0);\n if (iodsAtom != NULL) {\n movie_info.contains_iods = true;\n APar_Extract_iods_Info(isofile, iodsAtom);\n }\n\n if (optional_output & SHOW_TRACK_INFO) {\n APar_TrackLevelInfo(&track,\n NULL); // With track_num set to 0, it will return the\n // total trak atom into total_tracks here.\n\n fprintf(\n stdout, \"Low-level details. Total tracks: %u\\n\", track.total_tracks);\n fprintf(stdout,\n \"Trk Type Handler Kind Lang Bytes\\n\");\n\n if (track.total_tracks > 0) {\n while (track.total_tracks > track.track_num) {\n track.track_num += 1;\n TrackInfo track_info = {0};\n\n // tracknum, handler type, handler name\n APar_ExtractTrackDetails(uint32_buffer, isofile, &track, &track_info);\n uint16_t more_whitespace =\n purge_extraneous_characters(track_info.track_hdlr_name);\n\n if (strlen(track_info.track_hdlr_name) == 0) {\n memcpy(track_info.track_hdlr_name, \"[none listed]\", 13);\n }\n fprintf(stdout,\n \"%u %s %s\",\n track.track_num,\n uint32tochar4(track_info.track_type, uint32_buffer),\n track_info.track_hdlr_name);\n\n uint16_t handler_len = strlen(track_info.track_hdlr_name);\n if (handler_len < 25 + more_whitespace) {\n for (uint16_t i = handler_len; i < 25 + more_whitespace; i++) {\n fprintf(stdout, \" \");\n }\n }\n\n // codec, language\n fprintf(stdout,\n \" %s %s %\" PRIu64,\n uint32tochar4(track_info.track_codec, uint32_buffer),\n track_info.unpacked_lang,\n track_info.sample_aggregate);\n\n if (track_info.encoder_name[0] != 0 && track_info.contains_esds) {\n purge_extraneous_characters(track_info.encoder_name);\n fprintf(stdout, \" Encoder: %s\", track_info.encoder_name);\n }\n if (track_info.type_of_track & DRM_PROTECTED_TRACK) {\n fprintf(stdout,\n \" (protected %s)\",\n uint32tochar4(track_info.protected_codec, uint32_buffer));\n }\n\n fprintf(stdout, \"\\n\");\n /*---------------------------------*/\n\n if (track_info.type_of_track & VIDEO_TRACK ||\n track_info.type_of_track & AUDIO_TRACK) {\n APar_Print_TrackDetails(&track_info);\n }\n\n if (optional_output & SHOW_DATE_INFO) {\n fprintf(stdout,\n \" Creation Date (UTC): %s\\n\",\n APar_extract_UTC(track_info.creation_time));\n fprintf(stdout,\n \" Modification Date (UTC): %s\\n\",\n APar_extract_UTC(track_info.modified_time));\n }\n }\n }\n }\n}", "project": "atomicparsley", "hash": 27305014511647361793546293488526992046, "size": 102, "commit_id": "d72ccf06c98259d7261e0f3ac4fd8717778782c1", "message": "Avoid stack overflow\n\nrefs: https://github.com/wez/atomicparsley/issues/32", "target": 0, "dataset": "other", "idx": 417017}
  787. {"func": "_gnutls_ciphertext2compressed (gnutls_session_t session,\n\t\t\t opaque * compress_data,\n\t\t\t int compress_size,\n\t\t\t gnutls_datum_t ciphertext, uint8_t type)\n{\n uint8_t MAC[MAX_HASH_SIZE];\n uint16_t c_length;\n uint8_t pad;\n int length;\n digest_hd_st td;\n uint16_t blocksize;\n int ret, i, pad_failed = 0;\n uint8_t major, minor;\n gnutls_protocol_t ver;\n int hash_size =\n _gnutls_hash_get_algo_len (session->security_parameters.\n\t\t\t read_mac_algorithm);\n\n ver = gnutls_protocol_get_version (session);\n minor = _gnutls_version_get_minor (ver);\n major = _gnutls_version_get_major (ver);\n\n blocksize = _gnutls_cipher_get_block_size (session->security_parameters.\n\t\t\t\t\t read_bulk_cipher_algorithm);\n\n /* initialize MAC \n */\n ret = mac_init (&td, session->security_parameters.read_mac_algorithm,\n\t\t session->connection_state.read_mac_secret.data,\n\t\t session->connection_state.read_mac_secret.size, ver);\n\n if (ret < 0\n && session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)\n {\n gnutls_assert ();\n return GNUTLS_E_INTERNAL_ERROR;\n }\n\n if (ciphertext.size < (unsigned) blocksize + hash_size)\n {\n _gnutls_record_log\n\t(\"REC[%x]: Short record length %d < %d + %d (under attack?)\\n\",\n\t session, ciphertext.size, blocksize, hash_size);\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n\n /* actual decryption (inplace)\n */\n switch (_gnutls_cipher_is_block\n\t (session->security_parameters.read_bulk_cipher_algorithm))\n {\n case CIPHER_STREAM:\n if ((ret = _gnutls_cipher_decrypt (&session->connection_state.\n\t\t\t\t\t read_cipher_state,\n\t\t\t\t\t ciphertext.data,\n\t\t\t\t\t ciphertext.size)) < 0)\n\t{\n\t gnutls_assert ();\n\t return ret;\n\t}\n\n length = ciphertext.size - hash_size;\n\n break;\n case CIPHER_BLOCK:\n if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))\n\t{\n\t gnutls_assert ();\n\t return GNUTLS_E_DECRYPTION_FAILED;\n\t}\n\n if ((ret = _gnutls_cipher_decrypt (&session->connection_state.\n\t\t\t\t\t read_cipher_state,\n\t\t\t\t\t ciphertext.data,\n\t\t\t\t\t ciphertext.size)) < 0)\n\t{\n\t gnutls_assert ();\n\t return ret;\n\t}\n\n /* ignore the IV in TLS 1.1.\n */\n if (session->security_parameters.version >= GNUTLS_TLS1_1)\n\t{\n\t ciphertext.size -= blocksize;\n\t ciphertext.data += blocksize;\n\n\t if (ciphertext.size == 0)\n\t {\n\t gnutls_assert ();\n\t return GNUTLS_E_DECRYPTION_FAILED;\n\t }\n\t}\n\n pad = ciphertext.data[ciphertext.size - 1] + 1;\t/* pad */\n\n if ((int)pad > (int)ciphertext.size - hash_size)\n\t{\n\t gnutls_assert ();\n\t /* We do not fail here. We check below for the\n\t * the pad_failed. If zero means success.\n\t */\n\t pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n\t}\n\n length = ciphertext.size - hash_size - pad;\n\n /* Check the pading bytes (TLS 1.x)\n */\n if (ver >= GNUTLS_TLS1 && pad_failed == 0)\n\tfor (i = 2; i < pad; i++)\n\t {\n\t if (ciphertext.data[ciphertext.size - i] !=\n\t\tciphertext.data[ciphertext.size - 1])\n\t pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n\t }\n break;\n default:\n gnutls_assert ();\n return GNUTLS_E_INTERNAL_ERROR;\n }\n\n if (length < 0)\n length = 0;\n c_length = _gnutls_conv_uint16 ((uint16_t) length);\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n if (session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)\n {\n _gnutls_hmac (&td,\n\t\t UINT64DATA (session->connection_state.\n\t\t\t\tread_sequence_number), 8);\n\n _gnutls_hmac (&td, &type, 1);\n if (ver >= GNUTLS_TLS1)\n\t{\t\t\t/* TLS 1.x */\n\t _gnutls_hmac (&td, &major, 1);\n\t _gnutls_hmac (&td, &minor, 1);\n\t}\n _gnutls_hmac (&td, &c_length, 2);\n\n if (length > 0)\n\t_gnutls_hmac (&td, ciphertext.data, length);\n\n mac_deinit (&td, MAC, ver);\n }\n\n /* This one was introduced to avoid a timing attack against the TLS\n * 1.0 protocol.\n */\n if (pad_failed != 0)\n return pad_failed;\n\n /* HMAC was not the same. \n */\n if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n\n /* copy the decrypted stuff to compress_data.\n */\n if (compress_size < length)\n {\n gnutls_assert ();\n return GNUTLS_E_DECOMPRESSION_FAILED;\n }\n memcpy (compress_data, ciphertext.data, length);\n\n return length;\n}", "project": "gnutls", "hash": 133466176970244054302162994213823627570, "size": 175, "commit_id": "d223040e498bd50a4b9e0aa493e78587ae1ed653", "message": "Fix broken debug check for GNUTLS-SA-2008-1.", "target": 1, "dataset": "other", "idx": 209003}
  788. {"func": "_gnutls_ciphertext2compressed (gnutls_session_t session,\n\t\t\t opaque * compress_data,\n\t\t\t int compress_size,\n\t\t\t gnutls_datum_t ciphertext, uint8_t type)\n{\n uint8_t MAC[MAX_HASH_SIZE];\n uint16_t c_length;\n uint8_t pad;\n int length;\n digest_hd_st td;\n uint16_t blocksize;\n int ret, i, pad_failed = 0;\n uint8_t major, minor;\n gnutls_protocol_t ver;\n int hash_size =\n _gnutls_hash_get_algo_len (session->security_parameters.\n\t\t\t read_mac_algorithm);\n\n ver = gnutls_protocol_get_version (session);\n minor = _gnutls_version_get_minor (ver);\n major = _gnutls_version_get_major (ver);\n\n blocksize = _gnutls_cipher_get_block_size (session->security_parameters.\n\t\t\t\t\t read_bulk_cipher_algorithm);\n\n /* initialize MAC \n */\n ret = mac_init (&td, session->security_parameters.read_mac_algorithm,\n\t\t session->connection_state.read_mac_secret.data,\n\t\t session->connection_state.read_mac_secret.size, ver);\n\n if (ret < 0\n && session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)\n {\n gnutls_assert ();\n return GNUTLS_E_INTERNAL_ERROR;\n }\n\n /* actual decryption (inplace)\n */\n switch (_gnutls_cipher_is_block\n\t (session->security_parameters.read_bulk_cipher_algorithm))\n {\n case CIPHER_STREAM:\n if ((ret = _gnutls_cipher_decrypt (&session->connection_state.\n\t\t\t\t\t read_cipher_state,\n\t\t\t\t\t ciphertext.data,\n\t\t\t\t\t ciphertext.size)) < 0)\n\t{\n\t gnutls_assert ();\n\t return ret;\n\t}\n\n length = ciphertext.size - hash_size;\n\n break;\n case CIPHER_BLOCK:\n if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))\n\t{\n\t gnutls_assert ();\n\t return GNUTLS_E_DECRYPTION_FAILED;\n\t}\n\n if ((ret = _gnutls_cipher_decrypt (&session->connection_state.\n\t\t\t\t\t read_cipher_state,\n\t\t\t\t\t ciphertext.data,\n\t\t\t\t\t ciphertext.size)) < 0)\n\t{\n\t gnutls_assert ();\n\t return ret;\n\t}\n\n /* ignore the IV in TLS 1.1.\n */\n if (session->security_parameters.version >= GNUTLS_TLS1_1)\n\t{\n\t ciphertext.size -= blocksize;\n\t ciphertext.data += blocksize;\n\n\t if (ciphertext.size == 0)\n\t {\n\t gnutls_assert ();\n\t return GNUTLS_E_DECRYPTION_FAILED;\n\t }\n\t}\n\n pad = ciphertext.data[ciphertext.size - 1] + 1;\t/* pad */\n\n if ((int)pad > (int)ciphertext.size - hash_size)\n\t{\n\t gnutls_assert ();\n\t _gnutls_record_log\n\t (\"REC[%x]: Short record length %d > %d - %d (under attack?)\\n\",\n\t session, pad, ciphertext.size, hash_size);\n\t /* We do not fail here. We check below for the\n\t * the pad_failed. If zero means success.\n\t */\n\t pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n\t}\n\n length = ciphertext.size - hash_size - pad;\n\n /* Check the pading bytes (TLS 1.x)\n */\n if (ver >= GNUTLS_TLS1 && pad_failed == 0)\n\tfor (i = 2; i < pad; i++)\n\t {\n\t if (ciphertext.data[ciphertext.size - i] !=\n\t\tciphertext.data[ciphertext.size - 1])\n\t pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n\t }\n break;\n default:\n gnutls_assert ();\n return GNUTLS_E_INTERNAL_ERROR;\n }\n\n if (length < 0)\n length = 0;\n c_length = _gnutls_conv_uint16 ((uint16_t) length);\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n if (session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)\n {\n _gnutls_hmac (&td,\n\t\t UINT64DATA (session->connection_state.\n\t\t\t\tread_sequence_number), 8);\n\n _gnutls_hmac (&td, &type, 1);\n if (ver >= GNUTLS_TLS1)\n\t{\t\t\t/* TLS 1.x */\n\t _gnutls_hmac (&td, &major, 1);\n\t _gnutls_hmac (&td, &minor, 1);\n\t}\n _gnutls_hmac (&td, &c_length, 2);\n\n if (length > 0)\n\t_gnutls_hmac (&td, ciphertext.data, length);\n\n mac_deinit (&td, MAC, ver);\n }\n\n /* This one was introduced to avoid a timing attack against the TLS\n * 1.0 protocol.\n */\n if (pad_failed != 0)\n return pad_failed;\n\n /* HMAC was not the same. \n */\n if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n\n /* copy the decrypted stuff to compress_data.\n */\n if (compress_size < length)\n {\n gnutls_assert ();\n return GNUTLS_E_DECOMPRESSION_FAILED;\n }\n memcpy (compress_data, ciphertext.data, length);\n\n return length;\n}", "project": "gnutls", "hash": 71075734724174952553502640199265785099, "size": 169, "commit_id": "d223040e498bd50a4b9e0aa493e78587ae1ed653", "message": "Fix broken debug check for GNUTLS-SA-2008-1.", "target": 0, "dataset": "other", "idx": 417234}
  789. {"func": "bool SFD_GetFontMetaData( FILE *sfd,\n\t\t\t char *tok,\n\t\t\t SplineFont *sf,\n\t\t\t SFD_GetFontMetaDataData* d )\n{\n int ch;\n int i;\n KernClass* kc = 0;\n int old;\n char val[2000];\n\n // This allows us to assume we can dereference d\n // at all times\n static SFD_GetFontMetaDataData my_static_d;\n static int my_static_d_is_virgin = 1;\n if( !d )\n {\n\tif( my_static_d_is_virgin )\n\t{\n\t my_static_d_is_virgin = 0;\n\t SFD_GetFontMetaDataData_Init( &my_static_d );\n\t}\n\td = &my_static_d;\n }\n\n if ( strmatch(tok,\"FontName:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->fontname = copy(val);\n }\n else if ( strmatch(tok,\"FullName:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->fullname = copy(val);\n }\n else if ( strmatch(tok,\"FamilyName:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->familyname = copy(val);\n }\n else if ( strmatch(tok,\"DefaultBaseFilename:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->defbasefilename = copy(val);\n }\n else if ( strmatch(tok,\"Weight:\")==0 )\n {\n\tgetprotectedname(sfd,val);\n\tsf->weight = copy(val);\n }\n else if ( strmatch(tok,\"Copyright:\")==0 )\n {\n\tsf->copyright = getquotedeol(sfd);\n }\n else if ( strmatch(tok,\"Comments:\")==0 )\n {\n\tchar *temp = getquotedeol(sfd);\n\tsf->comments = latin1_2_utf8_copy(temp);\n\tfree(temp);\n }\n else if ( strmatch(tok,\"UComments:\")==0 )\n {\n\tsf->comments = SFDReadUTF7Str(sfd);\n }\n else if ( strmatch(tok,\"FontLog:\")==0 )\n {\n\tsf->fontlog = SFDReadUTF7Str(sfd);\n }\n else if ( strmatch(tok,\"Version:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->version = copy(val);\n }\n else if ( strmatch(tok,\"StyleMapFamilyName:\")==0 )\n {\n sf->styleMapFamilyName = SFDReadUTF7Str(sfd);\n }\n /* Legacy attribute for StyleMapFamilyName. Deprecated. */\n else if ( strmatch(tok,\"OS2FamilyName:\")==0 )\n {\n if (sf->styleMapFamilyName == NULL)\n sf->styleMapFamilyName = SFDReadUTF7Str(sfd);\n }\n else if ( strmatch(tok,\"FONDName:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->fondname = copy(val);\n }\n else if ( strmatch(tok,\"ItalicAngle:\")==0 )\n {\n\tgetreal(sfd,&sf->italicangle);\n }\n else if ( strmatch(tok,\"StrokeWidth:\")==0 )\n {\n\tgetreal(sfd,&sf->strokewidth);\n }\n else if ( strmatch(tok,\"UnderlinePosition:\")==0 )\n {\n\tgetreal(sfd,&sf->upos);\n }\n else if ( strmatch(tok,\"UnderlineWidth:\")==0 )\n {\n\tgetreal(sfd,&sf->uwidth);\n }\n else if ( strmatch(tok,\"ModificationTime:\")==0 )\n {\n\tgetlonglong(sfd,&sf->modificationtime);\n }\n else if ( strmatch(tok,\"CreationTime:\")==0 )\n {\n\tgetlonglong(sfd,&sf->creationtime);\n\td->hadtimes = true;\n }\n else if ( strmatch(tok,\"PfmFamily:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->pfminfo.pfmfamily = temp;\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"LangName:\")==0 )\n {\n\tsf->names = SFDGetLangName(sfd,sf->names);\n }\n else if ( strmatch(tok,\"GaspTable:\")==0 )\n {\n\tSFDGetGasp(sfd,sf);\n }\n else if ( strmatch(tok,\"DesignSize:\")==0 )\n {\n\tSFDGetDesignSize(sfd,sf);\n }\n else if ( strmatch(tok,\"OtfFeatName:\")==0 )\n {\n\tSFDGetOtfFeatName(sfd,sf);\n }\n else if ( strmatch(tok,\"PfmWeight:\")==0 || strmatch(tok,\"TTFWeight:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.weight);\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"TTFWidth:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.width);\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"Panose:\")==0 )\n {\n\tint temp,i;\n\tfor ( i=0; i<10; ++i )\n\t{\n\t getint(sfd,&temp);\n\t sf->pfminfo.panose[i] = temp;\n\t}\n\tsf->pfminfo.panose_set = true;\n }\n else if ( strmatch(tok,\"LineGap:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.linegap);\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"VLineGap:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.vlinegap);\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"HheadAscent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.hhead_ascent);\n }\n else if ( strmatch(tok,\"HheadAOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.hheadascent_add = temp;\n }\n else if ( strmatch(tok,\"HheadDescent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.hhead_descent);\n }\n else if ( strmatch(tok,\"HheadDOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.hheaddescent_add = temp;\n }\n else if ( strmatch(tok,\"OS2TypoLinegap:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_typolinegap);\n }\n else if ( strmatch(tok,\"OS2TypoAscent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_typoascent);\n }\n else if ( strmatch(tok,\"OS2TypoAOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.typoascent_add = temp;\n }\n else if ( strmatch(tok,\"OS2TypoDescent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_typodescent);\n }\n else if ( strmatch(tok,\"OS2TypoDOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.typodescent_add = temp;\n }\n else if ( strmatch(tok,\"OS2WinAscent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_winascent);\n }\n else if ( strmatch(tok,\"OS2WinDescent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_windescent);\n }\n else if ( strmatch(tok,\"OS2WinAOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.winascent_add = temp;\n }\n else if ( strmatch(tok,\"OS2WinDOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.windescent_add = temp;\n }\n else if ( strmatch(tok,\"HHeadAscent:\")==0 )\n {\n\t// DUPLICATE OF ABOVE\n\tgetsint(sfd,&sf->pfminfo.hhead_ascent);\n }\n else if ( strmatch(tok,\"HHeadDescent:\")==0 )\n {\n\t// DUPLICATE OF ABOVE\n\tgetsint(sfd,&sf->pfminfo.hhead_descent);\n }\n\n else if ( strmatch(tok,\"HHeadAOffset:\")==0 )\n {\n\t// DUPLICATE OF ABOVE\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.hheadascent_add = temp;\n }\n else if ( strmatch(tok,\"HHeadDOffset:\")==0 )\n {\n\t// DUPLICATE OF ABOVE\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.hheaddescent_add = temp;\n }\n else if ( strmatch(tok,\"MacStyle:\")==0 )\n {\n\tgetsint(sfd,&sf->macstyle);\n }\n else if ( strmatch(tok,\"OS2SubXSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_subxsize);\n\tsf->pfminfo.subsuper_set = true;\n }\n else if ( strmatch(tok,\"OS2SubYSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_subysize);\n }\n else if ( strmatch(tok,\"OS2SubXOff:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_subxoff);\n }\n else if ( strmatch(tok,\"OS2SubYOff:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_subyoff);\n }\n else if ( strmatch(tok,\"OS2SupXSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_supxsize);\n }\n else if ( strmatch(tok,\"OS2SupYSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_supysize);\n }\n else if ( strmatch(tok,\"OS2SupXOff:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_supxoff);\n }\n else if ( strmatch(tok,\"OS2SupYOff:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_supyoff);\n }\n else if ( strmatch(tok,\"OS2StrikeYSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_strikeysize);\n }\n else if ( strmatch(tok,\"OS2StrikeYPos:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_strikeypos);\n }\n else if ( strmatch(tok,\"OS2CapHeight:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_capheight);\n }\n else if ( strmatch(tok,\"OS2XHeight:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_xheight);\n }\n else if ( strmatch(tok,\"OS2FamilyClass:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_family_class);\n }\n else if ( strmatch(tok,\"OS2Vendor:\")==0 )\n {\n\twhile ( isspace(nlgetc(sfd)));\n\tsf->pfminfo.os2_vendor[0] = nlgetc(sfd);\n\tsf->pfminfo.os2_vendor[1] = nlgetc(sfd);\n\tsf->pfminfo.os2_vendor[2] = nlgetc(sfd);\n\tsf->pfminfo.os2_vendor[3] = nlgetc(sfd);\n\t(void) nlgetc(sfd);\n }\n else if ( strmatch(tok,\"OS2CodePages:\")==0 )\n {\n\tgethexints(sfd,sf->pfminfo.codepages,2);\n\tsf->pfminfo.hascodepages = true;\n }\n else if ( strmatch(tok,\"OS2UnicodeRanges:\")==0 )\n {\n\tgethexints(sfd,sf->pfminfo.unicoderanges,4);\n\tsf->pfminfo.hasunicoderanges = true;\n }\n else if ( strmatch(tok,\"TopEncoding:\")==0 )\n {\n\t/* Obsolete */\n\tgetint(sfd,&sf->top_enc);\n }\n else if ( strmatch(tok,\"Ascent:\")==0 )\n {\n\tgetint(sfd,&sf->ascent);\n }\n else if ( strmatch(tok,\"Descent:\")==0 )\n {\n\tgetint(sfd,&sf->descent);\n }\n else if ( strmatch(tok,\"InvalidEm:\")==0 )\n {\n\tgetint(sfd,&sf->invalidem);\n }\n else if ( strmatch(tok,\"woffMajor:\")==0 )\n {\n\tgetint(sfd,&sf->woffMajor);\n }\n else if ( strmatch(tok,\"woffMinor:\")==0 )\n {\n\tgetint(sfd,&sf->woffMinor);\n }\n else if ( strmatch(tok,\"woffMetadata:\")==0 )\n {\n\tsf->woffMetadata = SFDReadUTF7Str(sfd);\n }\n else if ( strmatch(tok,\"UFOAscent:\")==0 )\n {\n\t getreal(sfd,&sf->ufo_ascent);\n }\n else if ( strmatch(tok,\"UFODescent:\")==0 )\n {\n\tgetreal(sfd,&sf->ufo_descent);\n }\n else if ( strmatch(tok,\"sfntRevision:\")==0 )\n {\n\tgethex(sfd,(uint32 *)&sf->sfntRevision);\n }\n else if ( strmatch(tok,\"LayerCount:\")==0 )\n {\n\td->had_layer_cnt = true;\n\tgetint(sfd,&sf->layer_cnt);\n\tif ( sf->layer_cnt>2 ) {\n\t sf->layers = realloc(sf->layers,sf->layer_cnt*sizeof(LayerInfo));\n\t memset(sf->layers+2,0,(sf->layer_cnt-2)*sizeof(LayerInfo));\n\t}\n }\n else if ( strmatch(tok,\"Layer:\")==0 )\n {\n // TODO: Read the U. F. O. path.\n\tint layer, o2, bk;\n\tgetint(sfd,&layer);\n\tif ( layer>=sf->layer_cnt ) {\n\t sf->layers = realloc(sf->layers,(layer+1)*sizeof(LayerInfo));\n\t memset(sf->layers+sf->layer_cnt,0,((layer+1)-sf->layer_cnt)*sizeof(LayerInfo));\n\t sf->layer_cnt = layer+1;\n\t}\n\tgetint(sfd,&o2);\n\tsf->layers[layer].order2 = o2;\n\tsf->layers[layer].background = layer==ly_back;\n\t/* Used briefly, now background is after layer name */\n\twhile ( (ch=nlgetc(sfd))==' ' );\n\tungetc(ch,sfd);\n\tif ( ch!='\"' ) {\n\t getint(sfd,&bk);\n\t sf->layers[layer].background = bk;\n\t}\n\t/* end of section for obsolete format */\n\tsf->layers[layer].name = SFDReadUTF7Str(sfd);\n\twhile ( (ch=nlgetc(sfd))==' ' );\n\tungetc(ch,sfd);\n\tif ( ch!='\\n' ) {\n\t getint(sfd,&bk);\n\t sf->layers[layer].background = bk;\n\t}\n\twhile ( (ch=nlgetc(sfd))==' ' );\n\tungetc(ch,sfd);\n\tif ( ch!='\\n' ) { sf->layers[layer].ufo_path = SFDReadUTF7Str(sfd); }\n }\n else if ( strmatch(tok,\"PreferredKerning:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->preferred_kerning = temp;\n }\n else if ( strmatch(tok,\"StrokedFont:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->strokedfont = temp;\n }\n else if ( strmatch(tok,\"MultiLayer:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->multilayer = temp;\n }\n else if ( strmatch(tok,\"NeedsXUIDChange:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->changed_since_xuidchanged = temp;\n }\n else if ( strmatch(tok,\"VerticalOrigin:\")==0 )\n {\n\t// this doesn't seem to be written ever.\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->hasvmetrics = true;\n }\n else if ( strmatch(tok,\"HasVMetrics:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->hasvmetrics = temp;\n }\n else if ( strmatch(tok,\"Justify:\")==0 )\n {\n\tSFDParseJustify(sfd,sf,tok);\n }\n else if ( strmatch(tok,\"BaseHoriz:\")==0 )\n {\n\tsf->horiz_base = SFDParseBase(sfd);\n\td->last_base = sf->horiz_base;\n\td->last_base_script = NULL;\n }\n else if ( strmatch(tok,\"BaseVert:\")==0 )\n {\n\tsf->vert_base = SFDParseBase(sfd);\n\td->last_base = sf->vert_base;\n\td->last_base_script = NULL;\n }\n else if ( strmatch(tok,\"BaseScript:\")==0 )\n {\n\tstruct basescript *bs = SFDParseBaseScript(sfd,d->last_base);\n\tif ( d->last_base==NULL )\n\t{\n\t BaseScriptFree(bs);\n\t bs = NULL;\n\t}\n\telse if ( d->last_base_script!=NULL )\n\t d->last_base_script->next = bs;\n\telse\n\t d->last_base->scripts = bs;\n\td->last_base_script = bs;\n }\n else if ( strmatch(tok,\"StyleMap:\")==0 )\n {\n gethex(sfd,(uint32 *)&sf->pfminfo.stylemap);\n }\n /* Legacy attribute for StyleMap. Deprecated. */\n else if ( strmatch(tok,\"OS2StyleName:\")==0 )\n {\n char* sname = SFDReadUTF7Str(sfd);\n if (sf->pfminfo.stylemap == -1) {\n if (strcmp(sname,\"bold italic\")==0) sf->pfminfo.stylemap = 0x21;\n else if (strcmp(sname,\"bold\")==0) sf->pfminfo.stylemap = 0x20;\n else if (strcmp(sname,\"italic\")==0) sf->pfminfo.stylemap = 0x01;\n else if (strcmp(sname,\"regular\")==0) sf->pfminfo.stylemap = 0x40;\n }\n free(sname);\n }\n else if ( strmatch(tok,\"FSType:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.fstype);\n }\n else if ( strmatch(tok,\"OS2Version:\")==0 )\n {\n\tgetsint(sfd,&sf->os2_version);\n }\n else if ( strmatch(tok,\"OS2_WeightWidthSlopeOnly:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->weight_width_slope_only = temp;\n }\n else if ( strmatch(tok,\"OS2_UseTypoMetrics:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->use_typo_metrics = temp;\n }\n else if ( strmatch(tok,\"UseUniqueID:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->use_uniqueid = temp;\n }\n else if ( strmatch(tok,\"UseXUID:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->use_xuid = temp;\n }\n else if ( strmatch(tok,\"UniqueID:\")==0 )\n {\n\tgetint(sfd,&sf->uniqueid);\n }\n else if ( strmatch(tok,\"XUID:\")==0 )\n {\n\tgeteol(sfd,tok);\n\tsf->xuid = copy(tok);\n }\n else if ( strmatch(tok,\"Lookup:\")==0 )\n {\n\tOTLookup *otl;\n\tint temp;\n\tif ( sf->sfd_version<2 ) {\n\t IError( \"Lookups should not happen in version 1 sfd files.\" );\n\t exit(1);\n\t}\n\totl = chunkalloc(sizeof(OTLookup));\n\tgetint(sfd,&temp); otl->lookup_type = temp;\n\tgetint(sfd,&temp); otl->lookup_flags = temp;\n\tgetint(sfd,&temp); otl->store_in_afm = temp;\n\totl->lookup_name = SFDReadUTF7Str(sfd);\n\tif ( otl->lookup_type<gpos_single ) {\n\t if ( d->lastsotl==NULL )\n\t\tsf->gsub_lookups = otl;\n\t else\n\t\td->lastsotl->next = otl;\n\t d->lastsotl = otl;\n\t} else {\n\t if ( d->lastpotl==NULL )\n\t\tsf->gpos_lookups = otl;\n\t else\n\t\td->lastpotl->next = otl;\n\t d->lastpotl = otl;\n\t}\n\tSFDParseLookup(sfd,otl);\n }\n else if ( strmatch(tok,\"MarkAttachClasses:\")==0 )\n {\n\tgetint(sfd,&sf->mark_class_cnt);\n\tsf->mark_classes = malloc(sf->mark_class_cnt*sizeof(char *));\n\tsf->mark_class_names = malloc(sf->mark_class_cnt*sizeof(char *));\n\tsf->mark_classes[0] = NULL; sf->mark_class_names[0] = NULL;\n\tfor ( i=1; i<sf->mark_class_cnt; ++i )\n\t{\n\t /* Class 0 is unused */\n\t int temp;\n\t while ( (temp=nlgetc(sfd))=='\\n' || temp=='\\r' ); ungetc(temp,sfd);\n\t sf->mark_class_names[i] = SFDReadUTF7Str(sfd);\n\t getint(sfd,&temp);\n\t sf->mark_classes[i] = malloc(temp+1); sf->mark_classes[i][temp] = '\\0';\n\t nlgetc(sfd);\t/* skip space */\n\t fread(sf->mark_classes[i],1,temp,sfd);\n\t}\n }\n else if ( strmatch(tok,\"MarkAttachSets:\")==0 )\n {\n\tgetint(sfd,&sf->mark_set_cnt);\n\tsf->mark_sets = malloc(sf->mark_set_cnt*sizeof(char *));\n\tsf->mark_set_names = malloc(sf->mark_set_cnt*sizeof(char *));\n\tfor ( i=0; i<sf->mark_set_cnt; ++i )\n\t{\n\t /* Set 0 is used */\n\t int temp;\n\t while ( (temp=nlgetc(sfd))=='\\n' || temp=='\\r' ); ungetc(temp,sfd);\n\t sf->mark_set_names[i] = SFDReadUTF7Str(sfd);\n\t getint(sfd,&temp);\n\t sf->mark_sets[i] = malloc(temp+1); sf->mark_sets[i][temp] = '\\0';\n\t nlgetc(sfd);\t/* skip space */\n\t fread(sf->mark_sets[i],1,temp,sfd);\n\t}\n }\n else if ( strmatch(tok,\"KernClass2:\")==0 || strmatch(tok,\"VKernClass2:\")==0 ||\n\t strmatch(tok,\"KernClass:\")==0 || strmatch(tok,\"VKernClass:\")==0 ||\n\t strmatch(tok,\"KernClass3:\")==0 || strmatch(tok,\"VKernClass3:\")==0 )\n {\n\tint kernclassversion = 0;\n\tint isv = tok[0]=='V';\n\tint kcvoffset = (isv ? 10 : 9); //Offset to read kerning class version\n\tif (isdigit(tok[kcvoffset])) kernclassversion = tok[kcvoffset] - '0';\n\tint temp, classstart=1;\n\tint old = (kernclassversion == 0);\n\n\tif ( (sf->sfd_version<2)!=old ) {\n\t IError( \"Version mixup in Kerning Classes of sfd file.\" );\n\t exit(1);\n\t}\n\tkc = chunkalloc(old ? sizeof(KernClass1) : sizeof(KernClass));\n\tgetint(sfd,&kc->first_cnt);\n\tch=nlgetc(sfd);\n\tif ( ch=='+' )\n\t classstart = 0;\n\telse\n\t ungetc(ch,sfd);\n\tgetint(sfd,&kc->second_cnt);\n\tif ( old ) {\n\t getint(sfd,&temp); ((KernClass1 *) kc)->sli = temp;\n\t getint(sfd,&temp); ((KernClass1 *) kc)->flags = temp;\n\t} else {\n\t kc->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd));\n\t if ( kc->subtable!=NULL && kc->subtable->kc==NULL )\n\t\tkc->subtable->kc = kc;\n\t else {\n\t\tif ( kc->subtable==NULL )\n\t\t LogError(_(\"Bad SFD file, missing subtable in kernclass defn.\\n\") );\n\t\telse\n\t\t LogError(_(\"Bad SFD file, two kerning classes assigned to the same subtable: %s\\n\"), kc->subtable->subtable_name );\n\t\tkc->subtable = NULL;\n\t }\n\t}\n\tkc->firsts = calloc(kc->first_cnt,sizeof(char *));\n\tkc->seconds = calloc(kc->second_cnt,sizeof(char *));\n\tkc->offsets = calloc(kc->first_cnt*kc->second_cnt,sizeof(int16));\n\tkc->adjusts = calloc(kc->first_cnt*kc->second_cnt,sizeof(DeviceTable));\n\tif (kernclassversion >= 3) {\n\t kc->firsts_flags = calloc(kc->first_cnt, sizeof(int));\n\t kc->seconds_flags = calloc(kc->second_cnt, sizeof(int));\n\t kc->offsets_flags = calloc(kc->first_cnt*kc->second_cnt, sizeof(int));\n\t kc->firsts_names = calloc(kc->first_cnt, sizeof(char*));\n\t kc->seconds_names = calloc(kc->second_cnt, sizeof(char*));\n\t}\n\tkc->firsts[0] = NULL;\n\tfor ( i=classstart; i<kc->first_cnt; ++i ) {\n\t if (kernclassversion < 3) {\n\t getint(sfd,&temp);\n\t kc->firsts[i] = malloc(temp+1); kc->firsts[i][temp] = '\\0';\n\t nlgetc(sfd);\t/* skip space */\n\t fread(kc->firsts[i],1,temp,sfd);\n\t } else {\n\t getint(sfd,&kc->firsts_flags[i]);\n\t while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\\n' || ch == EOF) continue;\n\t kc->firsts_names[i] = SFDReadUTF7Str(sfd);\n\t while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\\n' || ch == EOF) continue;\n\t kc->firsts[i] = SFDReadUTF7Str(sfd);\n if (kc->firsts[i] == NULL) kc->firsts[i] = copy(\"\"); // In certain places, this must be defined.\n\t while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n\t }\n\t}\n\tkc->seconds[0] = NULL;\n\tfor ( i=1; i<kc->second_cnt; ++i ) {\n\t if (kernclassversion < 3) {\n\t getint(sfd,&temp);\n\t kc->seconds[i] = malloc(temp+1); kc->seconds[i][temp] = '\\0';\n\t nlgetc(sfd);\t/* skip space */\n\t fread(kc->seconds[i],1,temp,sfd);\n\t } else {\n\t getint(sfd,&temp);\n\t kc->seconds_flags[i] = temp;\n\t while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\\n' || ch == EOF) continue;\n\t kc->seconds_names[i] = SFDReadUTF7Str(sfd);\n\t while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\\n' || ch == EOF) continue;\n\t kc->seconds[i] = SFDReadUTF7Str(sfd);\n if (kc->seconds[i] == NULL) kc->seconds[i] = copy(\"\"); // In certain places, this must be defined.\n\t while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n\t }\n\t}\n\tfor ( i=0; i<kc->first_cnt*kc->second_cnt; ++i ) {\n\t if (kernclassversion >= 3) {\n\t getint(sfd,&temp);\n\t kc->offsets_flags[i] = temp;\n\t }\n\t getint(sfd,&temp);\n\t kc->offsets[i] = temp;\n\t SFDReadDeviceTable(sfd,&kc->adjusts[i]);\n\t}\n\tif ( !old && kc->subtable == NULL ) {\n\t /* Error. Ignore it. Free it. Whatever */;\n\t} else if ( !isv ) {\n\t if ( d->lastkc==NULL )\n\t\tsf->kerns = kc;\n\t else\n\t\td->lastkc->next = kc;\n\t d->lastkc = kc;\n\t} else {\n\t if ( d->lastvkc==NULL )\n\t\tsf->vkerns = kc;\n\t else\n\t\td->lastvkc->next = kc;\n\t d->lastvkc = kc;\n\t}\n }\n else if ( strmatch(tok,\"ContextPos2:\")==0 || strmatch(tok,\"ContextSub2:\")==0 ||\n\t strmatch(tok,\"ChainPos2:\")==0 || strmatch(tok,\"ChainSub2:\")==0 ||\n\t strmatch(tok,\"ReverseChain2:\")==0 ||\n\t strmatch(tok,\"ContextPos:\")==0 || strmatch(tok,\"ContextSub:\")==0 ||\n\t strmatch(tok,\"ChainPos:\")==0 || strmatch(tok,\"ChainSub:\")==0 ||\n\t strmatch(tok,\"ReverseChain:\")==0 )\n {\n\tFPST *fpst;\n\tint old;\n\tif ( strchr(tok,'2')!=NULL ) {\n\t old = false;\n\t fpst = chunkalloc(sizeof(FPST));\n\t} else {\n\t old = true;\n\t fpst = chunkalloc(sizeof(FPST1));\n\t}\n\tif ( (sf->sfd_version<2)!=old ) {\n\t IError( \"Version mixup in FPST of sfd file.\" );\n\t exit(1);\n\t}\n\tif ( d->lastfp==NULL )\n\t sf->possub = fpst;\n\telse\n\t d->lastfp->next = fpst;\n\td->lastfp = fpst;\n\tSFDParseChainContext(sfd,sf,fpst,tok,old);\n }\n else if ( strmatch(tok,\"Group:\")==0 ) {\n struct ff_glyphclasses *grouptmp = calloc(1, sizeof(struct ff_glyphclasses));\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n grouptmp->classname = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n grouptmp->glyphs = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n if (d->lastgroup != NULL) d->lastgroup->next = grouptmp; else sf->groups = grouptmp;\n d->lastgroup = grouptmp;\n }\n else if ( strmatch(tok,\"GroupKern:\")==0 ) {\n int temp = 0;\n struct ff_rawoffsets *kerntmp = calloc(1, sizeof(struct ff_rawoffsets));\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n kerntmp->left = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n kerntmp->right = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n getint(sfd,&temp);\n kerntmp->offset = temp;\n while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n if (d->lastgroupkern != NULL) d->lastgroupkern->next = kerntmp; else sf->groupkerns = kerntmp;\n d->lastgroupkern = kerntmp;\n }\n else if ( strmatch(tok,\"GroupVKern:\")==0 ) {\n int temp = 0;\n struct ff_rawoffsets *kerntmp = calloc(1, sizeof(struct ff_rawoffsets));\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n kerntmp->left = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n kerntmp->right = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n getint(sfd,&temp);\n kerntmp->offset = temp;\n while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n if (d->lastgroupvkern != NULL) d->lastgroupvkern->next = kerntmp; else sf->groupvkerns = kerntmp;\n d->lastgroupvkern = kerntmp;\n }\n else if ( strmatch(tok,\"MacIndic2:\")==0 || strmatch(tok,\"MacContext2:\")==0 ||\n\t strmatch(tok,\"MacLigature2:\")==0 || strmatch(tok,\"MacSimple2:\")==0 ||\n\t strmatch(tok,\"MacKern2:\")==0 || strmatch(tok,\"MacInsert2:\")==0 ||\n\t strmatch(tok,\"MacIndic:\")==0 || strmatch(tok,\"MacContext:\")==0 ||\n\t strmatch(tok,\"MacLigature:\")==0 || strmatch(tok,\"MacSimple:\")==0 ||\n\t strmatch(tok,\"MacKern:\")==0 || strmatch(tok,\"MacInsert:\")==0 )\n {\n\tASM *sm;\n\tif ( strchr(tok,'2')!=NULL ) {\n\t old = false;\n\t sm = chunkalloc(sizeof(ASM));\n\t} else {\n\t old = true;\n\t sm = chunkalloc(sizeof(ASM1));\n\t}\n\tif ( (sf->sfd_version<2)!=old ) {\n\t IError( \"Version mixup in state machine of sfd file.\" );\n\t exit(1);\n\t}\n\tif ( d->lastsm==NULL )\n\t sf->sm = sm;\n\telse\n\t d->lastsm->next = sm;\n\td->lastsm = sm;\n\tSFDParseStateMachine(sfd,sf,sm,tok,old);\n }\n else if ( strmatch(tok,\"MacFeat:\")==0 )\n {\n\tsf->features = SFDParseMacFeatures(sfd,tok);\n }\n else if ( strmatch(tok,\"TtfTable:\")==0 )\n {\n\t/* Old, binary format */\n\t/* still used for maxp and unknown tables */\n\tSFDGetTtfTable(sfd,sf,d->lastttf);\n }\n else if ( strmatch(tok,\"TtTable:\")==0 )\n {\n\t/* text instruction format */\n\tSFDGetTtTable(sfd,sf,d->lastttf);\n }\n\n\n ///////////////////\n\n else if ( strmatch(tok,\"ShortTable:\")==0 )\n {\n\t// only read, not written.\n\t/* text number format */\n\tSFDGetShortTable(sfd,sf,d->lastttf);\n }\n else\n {\n //\n // We didn't have a match ourselves.\n //\n return false;\n }\n return true;\n}", "project": "fontforge", "hash": 174470206429737553728553607144275060858, "size": 826, "commit_id": "048a91e2682c1a8936ae34dbc7bd70291ec05410", "message": "Fix for #4084 Use-after-free (heap) in the SFD_GetFontMetaData() function\nFix for #4086 NULL pointer dereference in the SFDGetSpiros() function\nFix for #4088 NULL pointer dereference in the SFD_AssignLookups() function\nAdd empty sf->fontname string if it isn't set, fixing #4089 #4090 and many\n other potential issues (many downstream calls to strlen() on the value).", "target": 1, "dataset": "other", "idx": 209042}
  790. {"func": "bool SFD_GetFontMetaData( FILE *sfd,\n\t\t\t char *tok,\n\t\t\t SplineFont *sf,\n\t\t\t SFD_GetFontMetaDataData* d )\n{\n int ch;\n int i;\n KernClass* kc = 0;\n int old;\n char val[2000];\n\n // This allows us to assume we can dereference d\n // at all times\n static SFD_GetFontMetaDataData my_static_d;\n static int my_static_d_is_virgin = 1;\n if( !d )\n {\n\tif( my_static_d_is_virgin )\n\t{\n\t my_static_d_is_virgin = 0;\n\t SFD_GetFontMetaDataData_Init( &my_static_d );\n\t}\n\td = &my_static_d;\n }\n\n if ( strmatch(tok,\"FontName:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->fontname = copy(val);\n }\n else if ( strmatch(tok,\"FullName:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->fullname = copy(val);\n }\n else if ( strmatch(tok,\"FamilyName:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->familyname = copy(val);\n }\n else if ( strmatch(tok,\"DefaultBaseFilename:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->defbasefilename = copy(val);\n }\n else if ( strmatch(tok,\"Weight:\")==0 )\n {\n\tgetprotectedname(sfd,val);\n\tsf->weight = copy(val);\n }\n else if ( strmatch(tok,\"Copyright:\")==0 )\n {\n\tsf->copyright = getquotedeol(sfd);\n }\n else if ( strmatch(tok,\"Comments:\")==0 )\n {\n\tchar *temp = getquotedeol(sfd);\n\tsf->comments = latin1_2_utf8_copy(temp);\n\tfree(temp);\n }\n else if ( strmatch(tok,\"UComments:\")==0 )\n {\n\tsf->comments = SFDReadUTF7Str(sfd);\n }\n else if ( strmatch(tok,\"FontLog:\")==0 )\n {\n\tsf->fontlog = SFDReadUTF7Str(sfd);\n }\n else if ( strmatch(tok,\"Version:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->version = copy(val);\n }\n else if ( strmatch(tok,\"StyleMapFamilyName:\")==0 )\n {\n sf->styleMapFamilyName = SFDReadUTF7Str(sfd);\n }\n /* Legacy attribute for StyleMapFamilyName. Deprecated. */\n else if ( strmatch(tok,\"OS2FamilyName:\")==0 )\n {\n if (sf->styleMapFamilyName == NULL)\n sf->styleMapFamilyName = SFDReadUTF7Str(sfd);\n }\n else if ( strmatch(tok,\"FONDName:\")==0 )\n {\n\tgeteol(sfd,val);\n\tsf->fondname = copy(val);\n }\n else if ( strmatch(tok,\"ItalicAngle:\")==0 )\n {\n\tgetreal(sfd,&sf->italicangle);\n }\n else if ( strmatch(tok,\"StrokeWidth:\")==0 )\n {\n\tgetreal(sfd,&sf->strokewidth);\n }\n else if ( strmatch(tok,\"UnderlinePosition:\")==0 )\n {\n\tgetreal(sfd,&sf->upos);\n }\n else if ( strmatch(tok,\"UnderlineWidth:\")==0 )\n {\n\tgetreal(sfd,&sf->uwidth);\n }\n else if ( strmatch(tok,\"ModificationTime:\")==0 )\n {\n\tgetlonglong(sfd,&sf->modificationtime);\n }\n else if ( strmatch(tok,\"CreationTime:\")==0 )\n {\n\tgetlonglong(sfd,&sf->creationtime);\n\td->hadtimes = true;\n }\n else if ( strmatch(tok,\"PfmFamily:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->pfminfo.pfmfamily = temp;\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"LangName:\")==0 )\n {\n\tsf->names = SFDGetLangName(sfd,sf->names);\n }\n else if ( strmatch(tok,\"GaspTable:\")==0 )\n {\n\tSFDGetGasp(sfd,sf);\n }\n else if ( strmatch(tok,\"DesignSize:\")==0 )\n {\n\tSFDGetDesignSize(sfd,sf);\n }\n else if ( strmatch(tok,\"OtfFeatName:\")==0 )\n {\n\tSFDGetOtfFeatName(sfd,sf);\n }\n else if ( strmatch(tok,\"PfmWeight:\")==0 || strmatch(tok,\"TTFWeight:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.weight);\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"TTFWidth:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.width);\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"Panose:\")==0 )\n {\n\tint temp,i;\n\tfor ( i=0; i<10; ++i )\n\t{\n\t getint(sfd,&temp);\n\t sf->pfminfo.panose[i] = temp;\n\t}\n\tsf->pfminfo.panose_set = true;\n }\n else if ( strmatch(tok,\"LineGap:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.linegap);\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"VLineGap:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.vlinegap);\n\tsf->pfminfo.pfmset = true;\n }\n else if ( strmatch(tok,\"HheadAscent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.hhead_ascent);\n }\n else if ( strmatch(tok,\"HheadAOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.hheadascent_add = temp;\n }\n else if ( strmatch(tok,\"HheadDescent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.hhead_descent);\n }\n else if ( strmatch(tok,\"HheadDOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.hheaddescent_add = temp;\n }\n else if ( strmatch(tok,\"OS2TypoLinegap:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_typolinegap);\n }\n else if ( strmatch(tok,\"OS2TypoAscent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_typoascent);\n }\n else if ( strmatch(tok,\"OS2TypoAOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.typoascent_add = temp;\n }\n else if ( strmatch(tok,\"OS2TypoDescent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_typodescent);\n }\n else if ( strmatch(tok,\"OS2TypoDOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.typodescent_add = temp;\n }\n else if ( strmatch(tok,\"OS2WinAscent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_winascent);\n }\n else if ( strmatch(tok,\"OS2WinDescent:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_windescent);\n }\n else if ( strmatch(tok,\"OS2WinAOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.winascent_add = temp;\n }\n else if ( strmatch(tok,\"OS2WinDOffset:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.windescent_add = temp;\n }\n else if ( strmatch(tok,\"HHeadAscent:\")==0 )\n {\n\t// DUPLICATE OF ABOVE\n\tgetsint(sfd,&sf->pfminfo.hhead_ascent);\n }\n else if ( strmatch(tok,\"HHeadDescent:\")==0 )\n {\n\t// DUPLICATE OF ABOVE\n\tgetsint(sfd,&sf->pfminfo.hhead_descent);\n }\n\n else if ( strmatch(tok,\"HHeadAOffset:\")==0 )\n {\n\t// DUPLICATE OF ABOVE\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.hheadascent_add = temp;\n }\n else if ( strmatch(tok,\"HHeadDOffset:\")==0 )\n {\n\t// DUPLICATE OF ABOVE\n\tint temp;\n\tgetint(sfd,&temp); sf->pfminfo.hheaddescent_add = temp;\n }\n else if ( strmatch(tok,\"MacStyle:\")==0 )\n {\n\tgetsint(sfd,&sf->macstyle);\n }\n else if ( strmatch(tok,\"OS2SubXSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_subxsize);\n\tsf->pfminfo.subsuper_set = true;\n }\n else if ( strmatch(tok,\"OS2SubYSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_subysize);\n }\n else if ( strmatch(tok,\"OS2SubXOff:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_subxoff);\n }\n else if ( strmatch(tok,\"OS2SubYOff:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_subyoff);\n }\n else if ( strmatch(tok,\"OS2SupXSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_supxsize);\n }\n else if ( strmatch(tok,\"OS2SupYSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_supysize);\n }\n else if ( strmatch(tok,\"OS2SupXOff:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_supxoff);\n }\n else if ( strmatch(tok,\"OS2SupYOff:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_supyoff);\n }\n else if ( strmatch(tok,\"OS2StrikeYSize:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_strikeysize);\n }\n else if ( strmatch(tok,\"OS2StrikeYPos:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_strikeypos);\n }\n else if ( strmatch(tok,\"OS2CapHeight:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_capheight);\n }\n else if ( strmatch(tok,\"OS2XHeight:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_xheight);\n }\n else if ( strmatch(tok,\"OS2FamilyClass:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.os2_family_class);\n }\n else if ( strmatch(tok,\"OS2Vendor:\")==0 )\n {\n\twhile ( isspace(nlgetc(sfd)));\n\tsf->pfminfo.os2_vendor[0] = nlgetc(sfd);\n\tsf->pfminfo.os2_vendor[1] = nlgetc(sfd);\n\tsf->pfminfo.os2_vendor[2] = nlgetc(sfd);\n\tsf->pfminfo.os2_vendor[3] = nlgetc(sfd);\n\t(void) nlgetc(sfd);\n }\n else if ( strmatch(tok,\"OS2CodePages:\")==0 )\n {\n\tgethexints(sfd,sf->pfminfo.codepages,2);\n\tsf->pfminfo.hascodepages = true;\n }\n else if ( strmatch(tok,\"OS2UnicodeRanges:\")==0 )\n {\n\tgethexints(sfd,sf->pfminfo.unicoderanges,4);\n\tsf->pfminfo.hasunicoderanges = true;\n }\n else if ( strmatch(tok,\"TopEncoding:\")==0 )\n {\n\t/* Obsolete */\n\tgetint(sfd,&sf->top_enc);\n }\n else if ( strmatch(tok,\"Ascent:\")==0 )\n {\n\tgetint(sfd,&sf->ascent);\n }\n else if ( strmatch(tok,\"Descent:\")==0 )\n {\n\tgetint(sfd,&sf->descent);\n }\n else if ( strmatch(tok,\"InvalidEm:\")==0 )\n {\n\tgetint(sfd,&sf->invalidem);\n }\n else if ( strmatch(tok,\"woffMajor:\")==0 )\n {\n\tgetint(sfd,&sf->woffMajor);\n }\n else if ( strmatch(tok,\"woffMinor:\")==0 )\n {\n\tgetint(sfd,&sf->woffMinor);\n }\n else if ( strmatch(tok,\"woffMetadata:\")==0 )\n {\n\tsf->woffMetadata = SFDReadUTF7Str(sfd);\n }\n else if ( strmatch(tok,\"UFOAscent:\")==0 )\n {\n\t getreal(sfd,&sf->ufo_ascent);\n }\n else if ( strmatch(tok,\"UFODescent:\")==0 )\n {\n\tgetreal(sfd,&sf->ufo_descent);\n }\n else if ( strmatch(tok,\"sfntRevision:\")==0 )\n {\n\tgethex(sfd,(uint32 *)&sf->sfntRevision);\n }\n else if ( strmatch(tok,\"LayerCount:\")==0 )\n {\n\td->had_layer_cnt = true;\n\tint layer_cnt_tmp;\n\tgetint(sfd,&layer_cnt_tmp);\n\tif ( layer_cnt_tmp>2 ) {\n\t sf->layers = realloc(sf->layers,sf->layer_cnt*sizeof(LayerInfo));\n\t memset(sf->layers+2,0,(sf->layer_cnt-2)*sizeof(LayerInfo));\n\t sf->layer_cnt = layer_cnt_tmp;\n\t}\n }\n else if ( strmatch(tok,\"Layer:\")==0 )\n {\n // TODO: Read the U. F. O. path.\n\tint layer, o2, bk;\n\tgetint(sfd,&layer);\n\tif ( layer>=sf->layer_cnt ) {\n\t sf->layers = realloc(sf->layers,(layer+1)*sizeof(LayerInfo));\n\t memset(sf->layers+sf->layer_cnt,0,((layer+1)-sf->layer_cnt)*sizeof(LayerInfo));\n\t sf->layer_cnt = layer+1;\n\t}\n\tgetint(sfd,&o2);\n\tsf->layers[layer].order2 = o2;\n\tsf->layers[layer].background = layer==ly_back;\n\t/* Used briefly, now background is after layer name */\n\twhile ( (ch=nlgetc(sfd))==' ' );\n\tungetc(ch,sfd);\n\tif ( ch!='\"' ) {\n\t getint(sfd,&bk);\n\t sf->layers[layer].background = bk;\n\t}\n\t/* end of section for obsolete format */\n\tsf->layers[layer].name = SFDReadUTF7Str(sfd);\n\twhile ( (ch=nlgetc(sfd))==' ' );\n\tungetc(ch,sfd);\n\tif ( ch!='\\n' ) {\n\t getint(sfd,&bk);\n\t sf->layers[layer].background = bk;\n\t}\n\twhile ( (ch=nlgetc(sfd))==' ' );\n\tungetc(ch,sfd);\n\tif ( ch!='\\n' ) { sf->layers[layer].ufo_path = SFDReadUTF7Str(sfd); }\n }\n else if ( strmatch(tok,\"PreferredKerning:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->preferred_kerning = temp;\n }\n else if ( strmatch(tok,\"StrokedFont:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->strokedfont = temp;\n }\n else if ( strmatch(tok,\"MultiLayer:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->multilayer = temp;\n }\n else if ( strmatch(tok,\"NeedsXUIDChange:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->changed_since_xuidchanged = temp;\n }\n else if ( strmatch(tok,\"VerticalOrigin:\")==0 )\n {\n\t// this doesn't seem to be written ever.\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->hasvmetrics = true;\n }\n else if ( strmatch(tok,\"HasVMetrics:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->hasvmetrics = temp;\n }\n else if ( strmatch(tok,\"Justify:\")==0 )\n {\n\tSFDParseJustify(sfd,sf,tok);\n }\n else if ( strmatch(tok,\"BaseHoriz:\")==0 )\n {\n\tsf->horiz_base = SFDParseBase(sfd);\n\td->last_base = sf->horiz_base;\n\td->last_base_script = NULL;\n }\n else if ( strmatch(tok,\"BaseVert:\")==0 )\n {\n\tsf->vert_base = SFDParseBase(sfd);\n\td->last_base = sf->vert_base;\n\td->last_base_script = NULL;\n }\n else if ( strmatch(tok,\"BaseScript:\")==0 )\n {\n\tstruct basescript *bs = SFDParseBaseScript(sfd,d->last_base);\n\tif ( d->last_base==NULL )\n\t{\n\t BaseScriptFree(bs);\n\t bs = NULL;\n\t}\n\telse if ( d->last_base_script!=NULL )\n\t d->last_base_script->next = bs;\n\telse\n\t d->last_base->scripts = bs;\n\td->last_base_script = bs;\n }\n else if ( strmatch(tok,\"StyleMap:\")==0 )\n {\n gethex(sfd,(uint32 *)&sf->pfminfo.stylemap);\n }\n /* Legacy attribute for StyleMap. Deprecated. */\n else if ( strmatch(tok,\"OS2StyleName:\")==0 )\n {\n char* sname = SFDReadUTF7Str(sfd);\n if (sf->pfminfo.stylemap == -1) {\n if (strcmp(sname,\"bold italic\")==0) sf->pfminfo.stylemap = 0x21;\n else if (strcmp(sname,\"bold\")==0) sf->pfminfo.stylemap = 0x20;\n else if (strcmp(sname,\"italic\")==0) sf->pfminfo.stylemap = 0x01;\n else if (strcmp(sname,\"regular\")==0) sf->pfminfo.stylemap = 0x40;\n }\n free(sname);\n }\n else if ( strmatch(tok,\"FSType:\")==0 )\n {\n\tgetsint(sfd,&sf->pfminfo.fstype);\n }\n else if ( strmatch(tok,\"OS2Version:\")==0 )\n {\n\tgetsint(sfd,&sf->os2_version);\n }\n else if ( strmatch(tok,\"OS2_WeightWidthSlopeOnly:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->weight_width_slope_only = temp;\n }\n else if ( strmatch(tok,\"OS2_UseTypoMetrics:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->use_typo_metrics = temp;\n }\n else if ( strmatch(tok,\"UseUniqueID:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->use_uniqueid = temp;\n }\n else if ( strmatch(tok,\"UseXUID:\")==0 )\n {\n\tint temp;\n\tgetint(sfd,&temp);\n\tsf->use_xuid = temp;\n }\n else if ( strmatch(tok,\"UniqueID:\")==0 )\n {\n\tgetint(sfd,&sf->uniqueid);\n }\n else if ( strmatch(tok,\"XUID:\")==0 )\n {\n\tgeteol(sfd,tok);\n\tsf->xuid = copy(tok);\n }\n else if ( strmatch(tok,\"Lookup:\")==0 )\n {\n\tOTLookup *otl;\n\tint temp;\n\tif ( sf->sfd_version<2 ) {\n\t IError( \"Lookups should not happen in version 1 sfd files.\" );\n\t exit(1);\n\t}\n\totl = chunkalloc(sizeof(OTLookup));\n\tgetint(sfd,&temp); otl->lookup_type = temp;\n\tgetint(sfd,&temp); otl->lookup_flags = temp;\n\tgetint(sfd,&temp); otl->store_in_afm = temp;\n\totl->lookup_name = SFDReadUTF7Str(sfd);\n\tif ( otl->lookup_type<gpos_single ) {\n\t if ( d->lastsotl==NULL )\n\t\tsf->gsub_lookups = otl;\n\t else\n\t\td->lastsotl->next = otl;\n\t d->lastsotl = otl;\n\t} else {\n\t if ( d->lastpotl==NULL )\n\t\tsf->gpos_lookups = otl;\n\t else\n\t\td->lastpotl->next = otl;\n\t d->lastpotl = otl;\n\t}\n\tSFDParseLookup(sfd,otl);\n }\n else if ( strmatch(tok,\"MarkAttachClasses:\")==0 )\n {\n\tgetint(sfd,&sf->mark_class_cnt);\n\tsf->mark_classes = malloc(sf->mark_class_cnt*sizeof(char *));\n\tsf->mark_class_names = malloc(sf->mark_class_cnt*sizeof(char *));\n\tsf->mark_classes[0] = NULL; sf->mark_class_names[0] = NULL;\n\tfor ( i=1; i<sf->mark_class_cnt; ++i )\n\t{\n\t /* Class 0 is unused */\n\t int temp;\n\t while ( (temp=nlgetc(sfd))=='\\n' || temp=='\\r' ); ungetc(temp,sfd);\n\t sf->mark_class_names[i] = SFDReadUTF7Str(sfd);\n\t getint(sfd,&temp);\n\t sf->mark_classes[i] = malloc(temp+1); sf->mark_classes[i][temp] = '\\0';\n\t nlgetc(sfd);\t/* skip space */\n\t fread(sf->mark_classes[i],1,temp,sfd);\n\t}\n }\n else if ( strmatch(tok,\"MarkAttachSets:\")==0 )\n {\n\tgetint(sfd,&sf->mark_set_cnt);\n\tsf->mark_sets = malloc(sf->mark_set_cnt*sizeof(char *));\n\tsf->mark_set_names = malloc(sf->mark_set_cnt*sizeof(char *));\n\tfor ( i=0; i<sf->mark_set_cnt; ++i )\n\t{\n\t /* Set 0 is used */\n\t int temp;\n\t while ( (temp=nlgetc(sfd))=='\\n' || temp=='\\r' ); ungetc(temp,sfd);\n\t sf->mark_set_names[i] = SFDReadUTF7Str(sfd);\n\t getint(sfd,&temp);\n\t sf->mark_sets[i] = malloc(temp+1); sf->mark_sets[i][temp] = '\\0';\n\t nlgetc(sfd);\t/* skip space */\n\t fread(sf->mark_sets[i],1,temp,sfd);\n\t}\n }\n else if ( strmatch(tok,\"KernClass2:\")==0 || strmatch(tok,\"VKernClass2:\")==0 ||\n\t strmatch(tok,\"KernClass:\")==0 || strmatch(tok,\"VKernClass:\")==0 ||\n\t strmatch(tok,\"KernClass3:\")==0 || strmatch(tok,\"VKernClass3:\")==0 )\n {\n\tint kernclassversion = 0;\n\tint isv = tok[0]=='V';\n\tint kcvoffset = (isv ? 10 : 9); //Offset to read kerning class version\n\tif (isdigit(tok[kcvoffset])) kernclassversion = tok[kcvoffset] - '0';\n\tint temp, classstart=1;\n\tint old = (kernclassversion == 0);\n\n\tif ( (sf->sfd_version<2)!=old ) {\n\t IError( \"Version mixup in Kerning Classes of sfd file.\" );\n\t exit(1);\n\t}\n\tkc = chunkalloc(old ? sizeof(KernClass1) : sizeof(KernClass));\n\tgetint(sfd,&kc->first_cnt);\n\tch=nlgetc(sfd);\n\tif ( ch=='+' )\n\t classstart = 0;\n\telse\n\t ungetc(ch,sfd);\n\tgetint(sfd,&kc->second_cnt);\n\tif ( old ) {\n\t getint(sfd,&temp); ((KernClass1 *) kc)->sli = temp;\n\t getint(sfd,&temp); ((KernClass1 *) kc)->flags = temp;\n\t} else {\n\t kc->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd));\n\t if ( kc->subtable!=NULL && kc->subtable->kc==NULL )\n\t\tkc->subtable->kc = kc;\n\t else {\n\t\tif ( kc->subtable==NULL )\n\t\t LogError(_(\"Bad SFD file, missing subtable in kernclass defn.\\n\") );\n\t\telse\n\t\t LogError(_(\"Bad SFD file, two kerning classes assigned to the same subtable: %s\\n\"), kc->subtable->subtable_name );\n\t\tkc->subtable = NULL;\n\t }\n\t}\n\tkc->firsts = calloc(kc->first_cnt,sizeof(char *));\n\tkc->seconds = calloc(kc->second_cnt,sizeof(char *));\n\tkc->offsets = calloc(kc->first_cnt*kc->second_cnt,sizeof(int16));\n\tkc->adjusts = calloc(kc->first_cnt*kc->second_cnt,sizeof(DeviceTable));\n\tif (kernclassversion >= 3) {\n\t kc->firsts_flags = calloc(kc->first_cnt, sizeof(int));\n\t kc->seconds_flags = calloc(kc->second_cnt, sizeof(int));\n\t kc->offsets_flags = calloc(kc->first_cnt*kc->second_cnt, sizeof(int));\n\t kc->firsts_names = calloc(kc->first_cnt, sizeof(char*));\n\t kc->seconds_names = calloc(kc->second_cnt, sizeof(char*));\n\t}\n\tkc->firsts[0] = NULL;\n\tfor ( i=classstart; i<kc->first_cnt; ++i ) {\n\t if (kernclassversion < 3) {\n\t getint(sfd,&temp);\n\t kc->firsts[i] = malloc(temp+1); kc->firsts[i][temp] = '\\0';\n\t nlgetc(sfd);\t/* skip space */\n\t fread(kc->firsts[i],1,temp,sfd);\n\t } else {\n\t getint(sfd,&kc->firsts_flags[i]);\n\t while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\\n' || ch == EOF) continue;\n\t kc->firsts_names[i] = SFDReadUTF7Str(sfd);\n\t while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\\n' || ch == EOF) continue;\n\t kc->firsts[i] = SFDReadUTF7Str(sfd);\n if (kc->firsts[i] == NULL) kc->firsts[i] = copy(\"\"); // In certain places, this must be defined.\n\t while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n\t }\n\t}\n\tkc->seconds[0] = NULL;\n\tfor ( i=1; i<kc->second_cnt; ++i ) {\n\t if (kernclassversion < 3) {\n\t getint(sfd,&temp);\n\t kc->seconds[i] = malloc(temp+1); kc->seconds[i][temp] = '\\0';\n\t nlgetc(sfd);\t/* skip space */\n\t fread(kc->seconds[i],1,temp,sfd);\n\t } else {\n\t getint(sfd,&temp);\n\t kc->seconds_flags[i] = temp;\n\t while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\\n' || ch == EOF) continue;\n\t kc->seconds_names[i] = SFDReadUTF7Str(sfd);\n\t while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\\n' || ch == EOF) continue;\n\t kc->seconds[i] = SFDReadUTF7Str(sfd);\n if (kc->seconds[i] == NULL) kc->seconds[i] = copy(\"\"); // In certain places, this must be defined.\n\t while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n\t }\n\t}\n\tfor ( i=0; i<kc->first_cnt*kc->second_cnt; ++i ) {\n\t if (kernclassversion >= 3) {\n\t getint(sfd,&temp);\n\t kc->offsets_flags[i] = temp;\n\t }\n\t getint(sfd,&temp);\n\t kc->offsets[i] = temp;\n\t SFDReadDeviceTable(sfd,&kc->adjusts[i]);\n\t}\n\tif ( !old && kc->subtable == NULL ) {\n\t /* Error. Ignore it. Free it. Whatever */;\n\t} else if ( !isv ) {\n\t if ( d->lastkc==NULL )\n\t\tsf->kerns = kc;\n\t else\n\t\td->lastkc->next = kc;\n\t d->lastkc = kc;\n\t} else {\n\t if ( d->lastvkc==NULL )\n\t\tsf->vkerns = kc;\n\t else\n\t\td->lastvkc->next = kc;\n\t d->lastvkc = kc;\n\t}\n }\n else if ( strmatch(tok,\"ContextPos2:\")==0 || strmatch(tok,\"ContextSub2:\")==0 ||\n\t strmatch(tok,\"ChainPos2:\")==0 || strmatch(tok,\"ChainSub2:\")==0 ||\n\t strmatch(tok,\"ReverseChain2:\")==0 ||\n\t strmatch(tok,\"ContextPos:\")==0 || strmatch(tok,\"ContextSub:\")==0 ||\n\t strmatch(tok,\"ChainPos:\")==0 || strmatch(tok,\"ChainSub:\")==0 ||\n\t strmatch(tok,\"ReverseChain:\")==0 )\n {\n\tFPST *fpst;\n\tint old;\n\tif ( strchr(tok,'2')!=NULL ) {\n\t old = false;\n\t fpst = chunkalloc(sizeof(FPST));\n\t} else {\n\t old = true;\n\t fpst = chunkalloc(sizeof(FPST1));\n\t}\n\tif ( (sf->sfd_version<2)!=old ) {\n\t IError( \"Version mixup in FPST of sfd file.\" );\n\t exit(1);\n\t}\n\tif ( d->lastfp==NULL )\n\t sf->possub = fpst;\n\telse\n\t d->lastfp->next = fpst;\n\td->lastfp = fpst;\n\tSFDParseChainContext(sfd,sf,fpst,tok,old);\n }\n else if ( strmatch(tok,\"Group:\")==0 ) {\n struct ff_glyphclasses *grouptmp = calloc(1, sizeof(struct ff_glyphclasses));\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n grouptmp->classname = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n grouptmp->glyphs = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n if (d->lastgroup != NULL) d->lastgroup->next = grouptmp; else sf->groups = grouptmp;\n d->lastgroup = grouptmp;\n }\n else if ( strmatch(tok,\"GroupKern:\")==0 ) {\n int temp = 0;\n struct ff_rawoffsets *kerntmp = calloc(1, sizeof(struct ff_rawoffsets));\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n kerntmp->left = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n kerntmp->right = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n getint(sfd,&temp);\n kerntmp->offset = temp;\n while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n if (d->lastgroupkern != NULL) d->lastgroupkern->next = kerntmp; else sf->groupkerns = kerntmp;\n d->lastgroupkern = kerntmp;\n }\n else if ( strmatch(tok,\"GroupVKern:\")==0 ) {\n int temp = 0;\n struct ff_rawoffsets *kerntmp = calloc(1, sizeof(struct ff_rawoffsets));\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n kerntmp->left = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n kerntmp->right = SFDReadUTF7Str(sfd);\n while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd);\n getint(sfd,&temp);\n kerntmp->offset = temp;\n while ((ch=nlgetc(sfd)) == ' ' || ch == '\\n'); ungetc(ch, sfd);\n if (d->lastgroupvkern != NULL) d->lastgroupvkern->next = kerntmp; else sf->groupvkerns = kerntmp;\n d->lastgroupvkern = kerntmp;\n }\n else if ( strmatch(tok,\"MacIndic2:\")==0 || strmatch(tok,\"MacContext2:\")==0 ||\n\t strmatch(tok,\"MacLigature2:\")==0 || strmatch(tok,\"MacSimple2:\")==0 ||\n\t strmatch(tok,\"MacKern2:\")==0 || strmatch(tok,\"MacInsert2:\")==0 ||\n\t strmatch(tok,\"MacIndic:\")==0 || strmatch(tok,\"MacContext:\")==0 ||\n\t strmatch(tok,\"MacLigature:\")==0 || strmatch(tok,\"MacSimple:\")==0 ||\n\t strmatch(tok,\"MacKern:\")==0 || strmatch(tok,\"MacInsert:\")==0 )\n {\n\tASM *sm;\n\tif ( strchr(tok,'2')!=NULL ) {\n\t old = false;\n\t sm = chunkalloc(sizeof(ASM));\n\t} else {\n\t old = true;\n\t sm = chunkalloc(sizeof(ASM1));\n\t}\n\tif ( (sf->sfd_version<2)!=old ) {\n\t IError( \"Version mixup in state machine of sfd file.\" );\n\t exit(1);\n\t}\n\tif ( d->lastsm==NULL )\n\t sf->sm = sm;\n\telse\n\t d->lastsm->next = sm;\n\td->lastsm = sm;\n\tSFDParseStateMachine(sfd,sf,sm,tok,old);\n }\n else if ( strmatch(tok,\"MacFeat:\")==0 )\n {\n\tsf->features = SFDParseMacFeatures(sfd,tok);\n }\n else if ( strmatch(tok,\"TtfTable:\")==0 )\n {\n\t/* Old, binary format */\n\t/* still used for maxp and unknown tables */\n\tSFDGetTtfTable(sfd,sf,d->lastttf);\n }\n else if ( strmatch(tok,\"TtTable:\")==0 )\n {\n\t/* text instruction format */\n\tSFDGetTtTable(sfd,sf,d->lastttf);\n }\n\n\n ///////////////////\n\n else if ( strmatch(tok,\"ShortTable:\")==0 )\n {\n\t// only read, not written.\n\t/* text number format */\n\tSFDGetShortTable(sfd,sf,d->lastttf);\n }\n else\n {\n //\n // We didn't have a match ourselves.\n //\n return false;\n }\n return true;\n}", "project": "fontforge", "hash": 325003590001280455271075128217041102898, "size": 828, "commit_id": "048a91e2682c1a8936ae34dbc7bd70291ec05410", "message": "Fix for #4084 Use-after-free (heap) in the SFD_GetFontMetaData() function\nFix for #4086 NULL pointer dereference in the SFDGetSpiros() function\nFix for #4088 NULL pointer dereference in the SFD_AssignLookups() function\nAdd empty sf->fontname string if it isn't set, fixing #4089 #4090 and many\n other potential issues (many downstream calls to strlen() on the value).", "target": 0, "dataset": "other", "idx": 417765}
  791. {"func": "int flb_gzip_compress(void *in_data, size_t in_len,\n void **out_data, size_t *out_len)\n{\n int flush;\n int status;\n int footer_start;\n uint8_t *pb;\n size_t out_size;\n void *out_buf;\n z_stream strm;\n mz_ulong crc;\n\n out_size = in_len + 32;\n out_buf = flb_malloc(out_size);\n if (!out_buf) {\n flb_errno();\n flb_error(\"[gzip] could not allocate outgoing buffer\");\n return -1;\n }\n\n /* Initialize streaming buffer context */\n memset(&strm, '\\0', sizeof(strm));\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.next_in = in_data;\n strm.avail_in = in_len;\n strm.total_out = 0;\n\n /* Deflate mode */\n deflateInit2(&strm, Z_DEFAULT_COMPRESSION,\n Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY);\n\n /*\n * Miniz don't support GZip format directly, instead we will:\n *\n * - append manual GZip magic bytes\n * - deflate raw content\n * - append manual CRC32 data\n */\n gzip_header(out_buf);\n\n /* Header offset */\n pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET;\n\n flush = Z_NO_FLUSH;\n while (1) {\n strm.next_out = pb + strm.total_out;\n strm.avail_out = out_size - (pb - (uint8_t *) out_buf);\n\n if (strm.avail_in == 0) {\n flush = Z_FINISH;\n }\n\n status = deflate(&strm, flush);\n if (status == Z_STREAM_END) {\n break;\n }\n else if (status != Z_OK) {\n deflateEnd(&strm);\n return -1;\n }\n }\n\n if (deflateEnd(&strm) != Z_OK) {\n flb_free(out_buf);\n return -1;\n }\n *out_len = strm.total_out;\n\n /* Construct the gzip checksum (CRC32 footer) */\n footer_start = FLB_GZIP_HEADER_OFFSET + *out_len;\n pb = (uint8_t *) out_buf + footer_start;\n\n crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len);\n *pb++ = crc & 0xFF;\n *pb++ = (crc >> 8) & 0xFF;\n *pb++ = (crc >> 16) & 0xFF;\n *pb++ = (crc >> 24) & 0xFF;\n *pb++ = in_len & 0xFF;\n *pb++ = (in_len >> 8) & 0xFF;\n *pb++ = (in_len >> 16) & 0xFF;\n *pb++ = (in_len >> 24) & 0xFF;\n\n /* Set the real buffer size for the caller */\n *out_len += FLB_GZIP_HEADER_OFFSET + 8;\n *out_data = out_buf;\n\n return 0;\n}", "project": "fluent-bit", "hash": 298785041176571465256262117903103760897, "size": 90, "commit_id": "cadff53c093210404aed01c4cf586adb8caa07af", "message": "gzip: fix compression size calculation (oss-fuzz 27261)\n\nSigned-off-by: davkor <david@adalogics.com>", "target": 1, "dataset": "other", "idx": 209045}
  792. {"func": "int flb_gzip_compress(void *in_data, size_t in_len,\n void **out_data, size_t *out_len)\n{\n int flush;\n int status;\n int footer_start;\n uint8_t *pb;\n size_t out_size;\n void *out_buf;\n z_stream strm;\n mz_ulong crc;\n\n\n /*\n * GZIP relies on an algorithm with worst-case expansion\n * of 5 bytes per 32KB data. This means we need to create a variable\n * length output, that depends on the input length.\n * See RFC 1951 for details.\n */\n int max_input_expansion = ((int)(in_len / 32000) + 1) * 5;\n\n /*\n * Max compressed size is equal to sum of:\n * 10 byte header\n * 8 byte foot\n * max input expansion\n * size of input\n */\n out_size = 10 + 8 + max_input_expansion + in_len;\n out_buf = flb_malloc(out_size);\n\n if (!out_buf) {\n flb_errno();\n flb_error(\"[gzip] could not allocate outgoing buffer\");\n return -1;\n }\n\n /* Initialize streaming buffer context */\n memset(&strm, '\\0', sizeof(strm));\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.next_in = in_data;\n strm.avail_in = in_len;\n strm.total_out = 0;\n\n /* Deflate mode */\n deflateInit2(&strm, Z_DEFAULT_COMPRESSION,\n Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY);\n\n /*\n * Miniz don't support GZip format directly, instead we will:\n *\n * - append manual GZip magic bytes\n * - deflate raw content\n * - append manual CRC32 data\n */\n gzip_header(out_buf);\n\n /* Header offset */\n pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET;\n\n flush = Z_NO_FLUSH;\n while (1) {\n strm.next_out = pb + strm.total_out;\n strm.avail_out = out_size - (pb - (uint8_t *) out_buf);\n\n if (strm.avail_in == 0) {\n flush = Z_FINISH;\n }\n\n status = deflate(&strm, flush);\n if (status == Z_STREAM_END) {\n break;\n }\n else if (status != Z_OK) {\n deflateEnd(&strm);\n return -1;\n }\n }\n\n if (deflateEnd(&strm) != Z_OK) {\n flb_free(out_buf);\n return -1;\n }\n *out_len = strm.total_out;\n\n /* Construct the gzip checksum (CRC32 footer) */\n footer_start = FLB_GZIP_HEADER_OFFSET + *out_len;\n pb = (uint8_t *) out_buf + footer_start;\n\n crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len);\n *pb++ = crc & 0xFF;\n *pb++ = (crc >> 8) & 0xFF;\n *pb++ = (crc >> 16) & 0xFF;\n *pb++ = (crc >> 24) & 0xFF;\n *pb++ = in_len & 0xFF;\n *pb++ = (in_len >> 8) & 0xFF;\n *pb++ = (in_len >> 16) & 0xFF;\n *pb++ = (in_len >> 24) & 0xFF;\n\n /* Set the real buffer size for the caller */\n *out_len += FLB_GZIP_HEADER_OFFSET + 8;\n *out_data = out_buf;\n\n return 0;\n}", "project": "fluent-bit", "hash": 330549964469517458967295596525565164446, "size": 107, "commit_id": "cadff53c093210404aed01c4cf586adb8caa07af", "message": "gzip: fix compression size calculation (oss-fuzz 27261)\n\nSigned-off-by: davkor <david@adalogics.com>", "target": 0, "dataset": "other", "idx": 417948}
  793. {"func": "filter_session_io(struct io *io, int evt, void *arg)\n{\n\tstruct filter_session *fs = arg;\n\tchar *line = NULL;\n\tssize_t len;\n\n\tlog_trace(TRACE_IO, \"filter session: %p: %s %s\", fs, io_strevent(evt),\n\t io_strio(io));\n\n\tswitch (evt) {\n\tcase IO_DATAIN:\n\tnextline:\n\t\tline = io_getline(fs->io, &len);\n\t\t/* No complete line received */\n\t\tif (line == NULL)\n\t\t\treturn;\n\n\t\tfilter_data(fs->id, line);\n\n\t\tgoto nextline;\n\n\tcase IO_DISCONNECTED:\n\t\tio_free(fs->io);\n\t\tfs->io = NULL;\n\t\tbreak;\n\t}\n}", "project": "src", "hash": 83839070917012004449638635653379607384, "size": 27, "commit_id": "6c3220444ed06b5796dedfd53a0f4becd903c0d1", "message": "smtpd's filter state machine can prematurely release resources\nleading to a crash. From gilles@", "target": 1, "dataset": "other", "idx": 209807}
  794. {"func": "filter_session_io(struct io *io, int evt, void *arg)\n{\n\tstruct filter_session *fs = arg;\n\tchar *line = NULL;\n\tssize_t len;\n\n\tlog_trace(TRACE_IO, \"filter session: %p: %s %s\", fs, io_strevent(evt),\n\t io_strio(io));\n\n\tswitch (evt) {\n\tcase IO_DATAIN:\n\tnextline:\n\t\tline = io_getline(fs->io, &len);\n\t\t/* No complete line received */\n\t\tif (line == NULL)\n\t\t\treturn;\n\n\t\tfilter_data(fs->id, line);\n\n\t\tgoto nextline;\n\t}\n}", "project": "src", "hash": 4978771540234783063665004784258488512, "size": 22, "commit_id": "6c3220444ed06b5796dedfd53a0f4becd903c0d1", "message": "smtpd's filter state machine can prematurely release resources\nleading to a crash. From gilles@", "target": 0, "dataset": "other", "idx": 421514}
  795. {"func": "ipmi_lan_alert_set(struct ipmi_intf * intf, uint8_t chan, uint8_t alert,\n\t\t int argc, char ** argv)\n{\n\tstruct lan_param * p;\n\tuint8_t data[32], temp[32];\n\tint rc = 0;\n\n\tif (argc < 2) {\n\t\tprint_lan_alert_set_usage();\n\t\treturn (-1);\n\t}\n\n\tif (strncmp(argv[0], \"help\", 4) == 0 ||\n\t strncmp(argv[1], \"help\", 4) == 0) {\n\t\tprint_lan_alert_set_usage();\n\t\treturn 0;\n\t}\n\n\tmemset(data, 0, sizeof(data));\n\tmemset(temp, 0, sizeof(temp));\n\n\t/* alert destination ip address */\n\tif (strncasecmp(argv[0], \"ipaddr\", 6) == 0 &&\n\t (get_cmdline_ipaddr(argv[1], temp) == 0)) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, p->data_len);\n\t\t/* set new ipaddr */\n\t\tmemcpy(data+3, temp, 4);\n\t\tprintf(\"Setting LAN Alert %d IP Address to %d.%d.%d.%d\\n\", alert,\n\t\t data[3], data[4], data[5], data[6]);\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);\n\t}\n\t/* alert destination mac address */\n\telse if (strncasecmp(argv[0], \"macaddr\", 7) == 0 &&\n\t\t (str2mac(argv[1], temp) == 0)) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, p->data_len);\n\t\t/* set new macaddr */\n\t\tmemcpy(data+7, temp, 6);\n\t\tprintf(\"Setting LAN Alert %d MAC Address to \"\n\t\t \"%s\\n\", alert, mac2str(&data[7]));\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);\n\t}\n\t/* alert destination gateway selector */\n\telse if (strncasecmp(argv[0], \"gateway\", 7) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, p->data_len);\n\n\t\tif (strncasecmp(argv[1], \"def\", 3) == 0 ||\n\t\t strncasecmp(argv[1], \"default\", 7) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d to use Default Gateway\\n\", alert);\n\t\t\tdata[2] = 0;\n\t\t}\n\t\telse if (strncasecmp(argv[1], \"bak\", 3) == 0 ||\n\t\t\t strncasecmp(argv[1], \"backup\", 6) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d to use Backup Gateway\\n\", alert);\n\t\t\tdata[2] = 1;\n\t\t}\n\t\telse {\n\t\t\tprint_lan_alert_set_usage();\n\t\t\treturn -1;\n\t\t}\n\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);\n\t}\n\t/* alert acknowledgement */\n\telse if (strncasecmp(argv[0], \"ack\", 3) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, p->data_len);\n\n\t\tif (strncasecmp(argv[1], \"on\", 2) == 0 ||\n\t\t strncasecmp(argv[1], \"yes\", 3) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d to Acknowledged\\n\", alert);\n\t\t\tdata[1] |= 0x80;\n\t\t}\n\t\telse if (strncasecmp(argv[1], \"off\", 3) == 0 ||\n\t\t\t strncasecmp(argv[1], \"no\", 2) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d to Unacknowledged\\n\", alert);\n\t\t\tdata[1] &= ~0x80;\n\t\t}\n\t\telse {\n\t\t\tprint_lan_alert_set_usage();\n\t\t\treturn -1;\n\t\t}\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);\n\t}\n\t/* alert destination type */\n\telse if (strncasecmp(argv[0], \"type\", 4) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, p->data_len);\n\n\t\tif (strncasecmp(argv[1], \"pet\", 3) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d destination to PET Trap\\n\", alert);\n\t\t\tdata[1] &= ~0x07;\n\t\t}\n\t\telse if (strncasecmp(argv[1], \"oem1\", 4) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d destination to OEM 1\\n\", alert);\n\t\t\tdata[1] &= ~0x07;\n\t\t\tdata[1] |= 0x06;\n\t\t}\n\t\telse if (strncasecmp(argv[1], \"oem2\", 4) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d destination to OEM 2\\n\", alert);\n\t\t\tdata[1] |= 0x07;\n\t\t}\n\t\telse {\n\t\t\tprint_lan_alert_set_usage();\n\t\t\treturn -1;\n\t\t}\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);\n\t}\n\t/* alert acknowledge timeout or retry interval */\n\telse if (strncasecmp(argv[0], \"time\", 4) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, p->data_len);\n\n\t\tif (str2uchar(argv[1], &data[2]) != 0) {\n\t\t\tlprintf(LOG_ERR, \"Invalid time: %s\", argv[1]);\n\t\t\treturn (-1);\n\t\t}\n\t\tprintf(\"Setting LAN Alert %d timeout/retry to %d seconds\\n\", alert, data[2]);\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);\n\t}\n\t/* number of retries */\n\telse if (strncasecmp(argv[0], \"retry\", 5) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, p->data_len);\n\n\t\tif (str2uchar(argv[1], &data[3]) != 0) {\n\t\t\tlprintf(LOG_ERR, \"Invalid retry: %s\", argv[1]);\n\t\t\treturn (-1);\n\t\t}\n\t\tdata[3] = data[3] & 0x7;\n\t\tprintf(\"Setting LAN Alert %d number of retries to %d\\n\", alert, data[3]);\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);\n\t}\n\telse {\n\t\tprint_lan_alert_set_usage();\n\t\treturn -1;\n\t}\n\n\treturn rc;\n}", "project": "ipmitool", "hash": 84380158635072339554778817955037156665, "size": 170, "commit_id": "d45572d71e70840e0d4c50bf48218492b79c1a10", "message": "lanp: Fix buffer overflows in get_lan_param_select\n\nPartial fix for CVE-2020-5208, see\nhttps://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp\n\nThe `get_lan_param_select` function is missing a validation check on the\nresponse\u2019s `data_len`, which it then returns to caller functions, where\nstack buffer overflow can occur.", "target": 1, "dataset": "other", "idx": 209813}
  796. {"func": "ipmi_lan_alert_set(struct ipmi_intf * intf, uint8_t chan, uint8_t alert,\n\t\t int argc, char ** argv)\n{\n\tstruct lan_param * p;\n\tuint8_t data[32], temp[32];\n\tint rc = 0;\n\n\tif (argc < 2) {\n\t\tprint_lan_alert_set_usage();\n\t\treturn (-1);\n\t}\n\n\tif (strncmp(argv[0], \"help\", 4) == 0 ||\n\t strncmp(argv[1], \"help\", 4) == 0) {\n\t\tprint_lan_alert_set_usage();\n\t\treturn 0;\n\t}\n\n\tmemset(data, 0, sizeof(data));\n\tmemset(temp, 0, sizeof(temp));\n\n\t/* alert destination ip address */\n\tif (strncasecmp(argv[0], \"ipaddr\", 6) == 0 &&\n\t (get_cmdline_ipaddr(argv[1], temp) == 0)) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, __min(p->data_len, sizeof(data)));\n\t\t/* set new ipaddr */\n\t\tmemcpy(data+3, temp, 4);\n\t\tprintf(\"Setting LAN Alert %d IP Address to %d.%d.%d.%d\\n\", alert,\n\t\t data[3], data[4], data[5], data[6]);\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);\n\t}\n\t/* alert destination mac address */\n\telse if (strncasecmp(argv[0], \"macaddr\", 7) == 0 &&\n\t\t (str2mac(argv[1], temp) == 0)) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, __min(p->data_len, sizeof(data)));\n\t\t/* set new macaddr */\n\t\tmemcpy(data+7, temp, 6);\n\t\tprintf(\"Setting LAN Alert %d MAC Address to \"\n\t\t \"%s\\n\", alert, mac2str(&data[7]));\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);\n\t}\n\t/* alert destination gateway selector */\n\telse if (strncasecmp(argv[0], \"gateway\", 7) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_ADDR, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, __min(p->data_len, sizeof(data)));\n\n\t\tif (strncasecmp(argv[1], \"def\", 3) == 0 ||\n\t\t strncasecmp(argv[1], \"default\", 7) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d to use Default Gateway\\n\", alert);\n\t\t\tdata[2] = 0;\n\t\t}\n\t\telse if (strncasecmp(argv[1], \"bak\", 3) == 0 ||\n\t\t\t strncasecmp(argv[1], \"backup\", 6) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d to use Backup Gateway\\n\", alert);\n\t\t\tdata[2] = 1;\n\t\t}\n\t\telse {\n\t\t\tprint_lan_alert_set_usage();\n\t\t\treturn -1;\n\t\t}\n\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_ADDR, data, p->data_len);\n\t}\n\t/* alert acknowledgement */\n\telse if (strncasecmp(argv[0], \"ack\", 3) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, __min(p->data_len, sizeof(data)));\n\n\t\tif (strncasecmp(argv[1], \"on\", 2) == 0 ||\n\t\t strncasecmp(argv[1], \"yes\", 3) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d to Acknowledged\\n\", alert);\n\t\t\tdata[1] |= 0x80;\n\t\t}\n\t\telse if (strncasecmp(argv[1], \"off\", 3) == 0 ||\n\t\t\t strncasecmp(argv[1], \"no\", 2) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d to Unacknowledged\\n\", alert);\n\t\t\tdata[1] &= ~0x80;\n\t\t}\n\t\telse {\n\t\t\tprint_lan_alert_set_usage();\n\t\t\treturn -1;\n\t\t}\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);\n\t}\n\t/* alert destination type */\n\telse if (strncasecmp(argv[0], \"type\", 4) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, __min(p->data_len, sizeof(data)));\n\n\t\tif (strncasecmp(argv[1], \"pet\", 3) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d destination to PET Trap\\n\", alert);\n\t\t\tdata[1] &= ~0x07;\n\t\t}\n\t\telse if (strncasecmp(argv[1], \"oem1\", 4) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d destination to OEM 1\\n\", alert);\n\t\t\tdata[1] &= ~0x07;\n\t\t\tdata[1] |= 0x06;\n\t\t}\n\t\telse if (strncasecmp(argv[1], \"oem2\", 4) == 0) {\n\t\t\tprintf(\"Setting LAN Alert %d destination to OEM 2\\n\", alert);\n\t\t\tdata[1] |= 0x07;\n\t\t}\n\t\telse {\n\t\t\tprint_lan_alert_set_usage();\n\t\t\treturn -1;\n\t\t}\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);\n\t}\n\t/* alert acknowledge timeout or retry interval */\n\telse if (strncasecmp(argv[0], \"time\", 4) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, __min(p->data_len, sizeof(data)));\n\n\t\tif (str2uchar(argv[1], &data[2]) != 0) {\n\t\t\tlprintf(LOG_ERR, \"Invalid time: %s\", argv[1]);\n\t\t\treturn (-1);\n\t\t}\n\t\tprintf(\"Setting LAN Alert %d timeout/retry to %d seconds\\n\", alert, data[2]);\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);\n\t}\n\t/* number of retries */\n\telse if (strncasecmp(argv[0], \"retry\", 5) == 0) {\n\t\t/* get current parameter */\n\t\tp = get_lan_param_select(intf, chan, IPMI_LANP_DEST_TYPE, alert);\n\t\tif (!p) {\n\t\t\treturn (-1);\n\t\t}\n\t\tmemcpy(data, p->data, __min(p->data_len, sizeof(data)));\n\n\t\tif (str2uchar(argv[1], &data[3]) != 0) {\n\t\t\tlprintf(LOG_ERR, \"Invalid retry: %s\", argv[1]);\n\t\t\treturn (-1);\n\t\t}\n\t\tdata[3] = data[3] & 0x7;\n\t\tprintf(\"Setting LAN Alert %d number of retries to %d\\n\", alert, data[3]);\n\t\trc = set_lan_param_nowait(intf, chan, IPMI_LANP_DEST_TYPE, data, p->data_len);\n\t}\n\telse {\n\t\tprint_lan_alert_set_usage();\n\t\treturn -1;\n\t}\n\n\treturn rc;\n}", "project": "ipmitool", "hash": 128890414513340911964604109333752466918, "size": 170, "commit_id": "d45572d71e70840e0d4c50bf48218492b79c1a10", "message": "lanp: Fix buffer overflows in get_lan_param_select\n\nPartial fix for CVE-2020-5208, see\nhttps://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp\n\nThe `get_lan_param_select` function is missing a validation check on the\nresponse\u2019s `data_len`, which it then returns to caller functions, where\nstack buffer overflow can occur.", "target": 0, "dataset": "other", "idx": 421797}
  797. {"func": "CairoFont *CairoFont::create(GfxFont *gfxFont, XRef *xref, FT_Library lib, GBool useCIDs) {\n Ref embRef;\n Object refObj, strObj;\n GooString *tmpFileName, *fileName,*tmpFileName2;\n DisplayFontParam *dfp;\n FILE *tmpFile;\n int c, i, n;\n GfxFontType fontType;\n char **enc;\n char *name;\n FoFiTrueType *ff;\n FoFiType1C *ff1c;\n Ref ref;\n static cairo_user_data_key_t cairo_font_face_key;\n cairo_font_face_t *cairo_font_face;\n FT_Face face;\n\n Gushort *codeToGID;\n int codeToGIDLen;\n \n dfp = NULL;\n codeToGID = NULL;\n codeToGIDLen = 0;\n cairo_font_face = NULL;\n \n ref = *gfxFont->getID();\n fontType = gfxFont->getType();\n\n tmpFileName = NULL;\n\n if (gfxFont->getEmbeddedFontID(&embRef)) {\n if (!openTempFile(&tmpFileName, &tmpFile, \"wb\", NULL)) {\n error(-1, \"Couldn't create temporary font file\");\n goto err2;\n }\n \n refObj.initRef(embRef.num, embRef.gen);\n refObj.fetch(xref, &strObj);\n refObj.free();\n strObj.streamReset();\n while ((c = strObj.streamGetChar()) != EOF) {\n fputc(c, tmpFile);\n }\n strObj.streamClose();\n strObj.free();\n fclose(tmpFile);\n fileName = tmpFileName;\n \n } else if (!(fileName = gfxFont->getExtFontFile())) {\n // look for a display font mapping or a substitute font\n dfp = NULL;\n if (gfxFont->getName()) {\n dfp = globalParams->getDisplayFont(gfxFont);\n }\n if (!dfp) {\n error(-1, \"Couldn't find a font for '%s'\",\n\t gfxFont->getName() ? gfxFont->getName()->getCString()\n\t : \"(unnamed)\");\n goto err2;\n }\n switch (dfp->kind) {\n case displayFontT1:\n fileName = dfp->t1.fileName;\n fontType = gfxFont->isCIDFont() ? fontCIDType0 : fontType1;\n break;\n case displayFontTT:\n fileName = dfp->tt.fileName;\n fontType = gfxFont->isCIDFont() ? fontCIDType2 : fontTrueType;\n break;\n }\n }\n\n switch (fontType) {\n case fontType1:\n case fontType1C:\n if (FT_New_Face(lib, fileName->getCString(), 0, &face)) {\n error(-1, \"could not create type1 face\");\n goto err2;\n }\n \n enc = ((Gfx8BitFont *)gfxFont)->getEncoding();\n \n codeToGID = (Gushort *)gmallocn(256, sizeof(int));\n codeToGIDLen = 256;\n for (i = 0; i < 256; ++i) {\n codeToGID[i] = 0;\n if ((name = enc[i])) {\n\tcodeToGID[i] = (Gushort)FT_Get_Name_Index(face, name);\n }\n }\n break;\n \n case fontCIDType2:\n codeToGID = NULL;\n n = 0;\n if (((GfxCIDFont *)gfxFont)->getCIDToGID()) {\n n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen();\n if (n) {\n\tcodeToGID = (Gushort *)gmallocn(n, sizeof(Gushort));\n\tmemcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(),\n\t\tn * sizeof(Gushort));\n }\n } else {\n ff = FoFiTrueType::load(fileName->getCString());\n if (! ff)\n\tgoto err2;\n codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff, &n);\n delete ff;\n }\n codeToGIDLen = n;\n /* Fall through */\n case fontTrueType:\n if (!(ff = FoFiTrueType::load(fileName->getCString()))) {\n error(-1, \"failed to load truetype font\\n\");\n goto err2;\n }\n /* This might be set already for the CIDType2 case */\n if (fontType == fontTrueType) {\n codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff);\n codeToGIDLen = 256;\n }\n if (!openTempFile(&tmpFileName2, &tmpFile, \"wb\", NULL)) {\n delete ff;\n error(-1, \"failed to open truetype tempfile\\n\");\n goto err2;\n }\n ff->writeTTF(&fileWrite, tmpFile);\n fclose(tmpFile);\n delete ff;\n\n if (FT_New_Face(lib, tmpFileName2->getCString(), 0, &face)) {\n error(-1, \"could not create truetype face\\n\");\n goto err2;\n }\n unlink (tmpFileName2->getCString());\n delete tmpFileName2;\n break;\n \n case fontCIDType0:\n case fontCIDType0C:\n\n codeToGID = NULL;\n codeToGIDLen = 0;\n\n if (!useCIDs)\n {\n if ((ff1c = FoFiType1C::load(fileName->getCString()))) {\n codeToGID = ff1c->getCIDToGIDMap(&codeToGIDLen);\n delete ff1c;\n }\n }\n\n if (FT_New_Face(lib, fileName->getCString(), 0, &face)) {\n gfree(codeToGID);\n codeToGID = NULL;\n error(-1, \"could not create cid face\\n\");\n goto err2;\n }\n break;\n \n default:\n printf (\"font type not handled\\n\");\n goto err2;\n break;\n }\n\n // delete the (temporary) font file -- with Unix hard link\n // semantics, this will remove the last link; otherwise it will\n // return an error, leaving the file to be deleted later\n if (fileName == tmpFileName) {\n unlink (fileName->getCString());\n delete tmpFileName;\n }\n\n cairo_font_face = cairo_ft_font_face_create_for_ft_face (face,\n\t\t\t\t\t\t\t FT_LOAD_NO_HINTING |\n\t\t\t\t\t\t\t FT_LOAD_NO_BITMAP);\n if (cairo_font_face == NULL) {\n error(-1, \"could not create cairo font\\n\");\n goto err2; /* this doesn't do anything, but it looks like we're\n\t\t* handling the error */\n } {\n CairoFont *ret = new CairoFont(ref, cairo_font_face, face, codeToGID, codeToGIDLen);\n cairo_font_face_set_user_data (cairo_font_face, \n\t\t\t\t &cairo_font_face_key,\n\t\t\t\t ret,\n\t\t\t\t cairo_font_face_destroy);\n\n return ret;\n }\n err2:\n /* hmm? */\n printf (\"some font thing failed\\n\");\n return NULL;\n}", "project": "poppler", "hash": 294666036737394333902439398055542844956, "size": 195, "commit_id": "1a531dcfee1c6fc79a414c38cbe7327fbf9a59d8", "message": "Fix a crash with invalid embedded fonts", "target": 1, "dataset": "other", "idx": 209818}
  798. {"func": "CairoFont *CairoFont::create(GfxFont *gfxFont, XRef *xref, FT_Library lib, GBool useCIDs) {\n Ref embRef;\n Object refObj, strObj;\n GooString *tmpFileName, *fileName,*tmpFileName2;\n DisplayFontParam *dfp;\n FILE *tmpFile;\n int c, i, n;\n GfxFontType fontType;\n char **enc;\n char *name;\n FoFiTrueType *ff;\n FoFiType1C *ff1c;\n Ref ref;\n static cairo_user_data_key_t cairo_font_face_key;\n cairo_font_face_t *cairo_font_face;\n FT_Face face;\n\n Gushort *codeToGID;\n int codeToGIDLen;\n \n dfp = NULL;\n codeToGID = NULL;\n codeToGIDLen = 0;\n cairo_font_face = NULL;\n \n ref = *gfxFont->getID();\n fontType = gfxFont->getType();\n\n tmpFileName = NULL;\n\n if (gfxFont->getEmbeddedFontID(&embRef)) {\n if (!openTempFile(&tmpFileName, &tmpFile, \"wb\", NULL)) {\n error(-1, \"Couldn't create temporary font file\");\n goto err2;\n }\n \n refObj.initRef(embRef.num, embRef.gen);\n refObj.fetch(xref, &strObj);\n refObj.free();\n if (!strObj.isStream()) {\n error(-1, \"Embedded font object is wrong type\");\n strObj.free();\n fclose(tmpFile);\n goto err2;\n }\n strObj.streamReset();\n while ((c = strObj.streamGetChar()) != EOF) {\n fputc(c, tmpFile);\n }\n strObj.streamClose();\n strObj.free();\n fclose(tmpFile);\n fileName = tmpFileName;\n \n } else if (!(fileName = gfxFont->getExtFontFile())) {\n // look for a display font mapping or a substitute font\n dfp = NULL;\n if (gfxFont->getName()) {\n dfp = globalParams->getDisplayFont(gfxFont);\n }\n if (!dfp) {\n error(-1, \"Couldn't find a font for '%s'\",\n\t gfxFont->getName() ? gfxFont->getName()->getCString()\n\t : \"(unnamed)\");\n goto err2;\n }\n switch (dfp->kind) {\n case displayFontT1:\n fileName = dfp->t1.fileName;\n fontType = gfxFont->isCIDFont() ? fontCIDType0 : fontType1;\n break;\n case displayFontTT:\n fileName = dfp->tt.fileName;\n fontType = gfxFont->isCIDFont() ? fontCIDType2 : fontTrueType;\n break;\n }\n }\n\n switch (fontType) {\n case fontType1:\n case fontType1C:\n if (FT_New_Face(lib, fileName->getCString(), 0, &face)) {\n error(-1, \"could not create type1 face\");\n goto err2;\n }\n \n enc = ((Gfx8BitFont *)gfxFont)->getEncoding();\n \n codeToGID = (Gushort *)gmallocn(256, sizeof(int));\n codeToGIDLen = 256;\n for (i = 0; i < 256; ++i) {\n codeToGID[i] = 0;\n if ((name = enc[i])) {\n\tcodeToGID[i] = (Gushort)FT_Get_Name_Index(face, name);\n }\n }\n break;\n \n case fontCIDType2:\n codeToGID = NULL;\n n = 0;\n if (((GfxCIDFont *)gfxFont)->getCIDToGID()) {\n n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen();\n if (n) {\n\tcodeToGID = (Gushort *)gmallocn(n, sizeof(Gushort));\n\tmemcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(),\n\t\tn * sizeof(Gushort));\n }\n } else {\n ff = FoFiTrueType::load(fileName->getCString());\n if (! ff)\n\tgoto err2;\n codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff, &n);\n delete ff;\n }\n codeToGIDLen = n;\n /* Fall through */\n case fontTrueType:\n if (!(ff = FoFiTrueType::load(fileName->getCString()))) {\n error(-1, \"failed to load truetype font\\n\");\n goto err2;\n }\n /* This might be set already for the CIDType2 case */\n if (fontType == fontTrueType) {\n codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff);\n codeToGIDLen = 256;\n }\n if (!openTempFile(&tmpFileName2, &tmpFile, \"wb\", NULL)) {\n delete ff;\n error(-1, \"failed to open truetype tempfile\\n\");\n goto err2;\n }\n ff->writeTTF(&fileWrite, tmpFile);\n fclose(tmpFile);\n delete ff;\n\n if (FT_New_Face(lib, tmpFileName2->getCString(), 0, &face)) {\n error(-1, \"could not create truetype face\\n\");\n goto err2;\n }\n unlink (tmpFileName2->getCString());\n delete tmpFileName2;\n break;\n \n case fontCIDType0:\n case fontCIDType0C:\n\n codeToGID = NULL;\n codeToGIDLen = 0;\n\n if (!useCIDs)\n {\n if ((ff1c = FoFiType1C::load(fileName->getCString()))) {\n codeToGID = ff1c->getCIDToGIDMap(&codeToGIDLen);\n delete ff1c;\n }\n }\n\n if (FT_New_Face(lib, fileName->getCString(), 0, &face)) {\n gfree(codeToGID);\n codeToGID = NULL;\n error(-1, \"could not create cid face\\n\");\n goto err2;\n }\n break;\n \n default:\n printf (\"font type not handled\\n\");\n goto err2;\n break;\n }\n\n // delete the (temporary) font file -- with Unix hard link\n // semantics, this will remove the last link; otherwise it will\n // return an error, leaving the file to be deleted later\n if (fileName == tmpFileName) {\n unlink (fileName->getCString());\n delete tmpFileName;\n }\n\n cairo_font_face = cairo_ft_font_face_create_for_ft_face (face,\n\t\t\t\t\t\t\t FT_LOAD_NO_HINTING |\n\t\t\t\t\t\t\t FT_LOAD_NO_BITMAP);\n if (cairo_font_face == NULL) {\n error(-1, \"could not create cairo font\\n\");\n goto err2; /* this doesn't do anything, but it looks like we're\n\t\t* handling the error */\n } {\n CairoFont *ret = new CairoFont(ref, cairo_font_face, face, codeToGID, codeToGIDLen);\n cairo_font_face_set_user_data (cairo_font_face, \n\t\t\t\t &cairo_font_face_key,\n\t\t\t\t ret,\n\t\t\t\t cairo_font_face_destroy);\n\n return ret;\n }\n err2:\n /* hmm? */\n printf (\"some font thing failed\\n\");\n return NULL;\n}", "project": "poppler", "hash": 117103155606137295047808127184080162393, "size": 201, "commit_id": "1a531dcfee1c6fc79a414c38cbe7327fbf9a59d8", "message": "Fix a crash with invalid embedded fonts", "target": 0, "dataset": "other", "idx": 421892}
  799. {"func": "void RegexMatchExpression::_init() {\n uassert(\n ErrorCodes::BadValue, \"Regular expression is too long\", _regex.size() <= kMaxPatternSize);\n\n uassert(ErrorCodes::BadValue,\n \"Regular expression cannot contain an embedded null byte\",\n _regex.find('\\0') == std::string::npos);\n\n uassert(ErrorCodes::BadValue,\n \"Regular expression options string cannot contain an embedded null byte\",\n _flags.find('\\0') == std::string::npos);\n}", "project": "mongo", "hash": 196906255193958728876698958313286561082, "size": 12, "commit_id": "64095239f41e9f3841d8be9088347db56d35c891", "message": "SERVER-51083 Reject invalid UTF-8 from $regex match expressions", "target": 1, "dataset": "other", "idx": 209844}
  800. {"func": "void RegexMatchExpression::_init() {\n uassert(\n ErrorCodes::BadValue, \"Regular expression is too long\", _regex.size() <= kMaxPatternSize);\n\n uassert(ErrorCodes::BadValue,\n \"Regular expression cannot contain an embedded null byte\",\n _regex.find('\\0') == std::string::npos);\n\n uassert(ErrorCodes::BadValue,\n \"Regular expression options string cannot contain an embedded null byte\",\n _flags.find('\\0') == std::string::npos);\n\n // isValidUTF8() checks for UTF-8 which does not map to a series of codepoints but does not\n // check the validity of the code points themselves. These situations do not cause problems\n // downstream so we do not do additional work to enforce that the code points are valid.\n uassert(\n 5108300, \"Regular expression is invalid UTF-8\", isValidUTF8(_regex) && isValidUTF8(_flags));\n}", "project": "mongo", "hash": 296417704049406944583817007241379160223, "size": 18, "commit_id": "64095239f41e9f3841d8be9088347db56d35c891", "message": "SERVER-51083 Reject invalid UTF-8 from $regex match expressions", "target": 0, "dataset": "other", "idx": 422547}
  801. {"func": "ExecAlterObjectDependsStmt(AlterObjectDependsStmt *stmt, ObjectAddress *refAddress)\n{\n\tObjectAddress address;\n\tObjectAddress refAddr;\n\tRelation\trel;\n\n\taddress =\n\t\tget_object_address_rv(stmt->objectType, stmt->relation, (List *) stmt->object,\n\t\t\t\t\t\t\t &rel, AccessExclusiveLock, false);\n\n\t/*\n\t * If a relation was involved, it would have been opened and locked. We\n\t * don't need the relation here, but we'll retain the lock until commit.\n\t */\n\tif (rel)\n\t\ttable_close(rel, NoLock);\n\n\trefAddr = get_object_address(OBJECT_EXTENSION, (Node *) stmt->extname,\n\t\t\t\t\t\t\t\t &rel, AccessExclusiveLock, false);\n\tAssert(rel == NULL);\n\tif (refAddress)\n\t\t*refAddress = refAddr;\n\n\trecordDependencyOn(&address, &refAddr, DEPENDENCY_AUTO_EXTENSION);\n\n\treturn address;\n}", "project": "postgres", "hash": 24619234578332954271203137488354771057, "size": 27, "commit_id": "b048f558dd7c26a0c630a2cff29d3d8981eaf6b9", "message": "Fix priv checks for ALTER <object> DEPENDS ON EXTENSION\n\nMarking an object as dependant on an extension did not have any\nprivilege check whatsoever; this allowed any user to mark objects as\ndroppable by anyone able to DROP EXTENSION, which could be used to cause\nsystem-wide havoc. Disallow by checking that the calling user owns the\nmentioned object.\n\n(No constraints are placed on the extension.)\n\nSecurity: CVE-2020-1720\nReported-by: Tom Lane\nDiscussion: 31605.1566429043@sss.pgh.pa.us", "target": 1, "dataset": "other", "idx": 209909}
  802. {"func": "ExecAlterObjectDependsStmt(AlterObjectDependsStmt *stmt, ObjectAddress *refAddress)\n{\n\tObjectAddress address;\n\tObjectAddress refAddr;\n\tRelation\trel;\n\n\taddress =\n\t\tget_object_address_rv(stmt->objectType, stmt->relation, (List *) stmt->object,\n\t\t\t\t\t\t\t &rel, AccessExclusiveLock, false);\n\n\t/*\n\t * Verify that the user is entitled to run the command.\n\t *\n\t * We don't check any privileges on the extension, because that's not\n\t * needed. The object owner is stipulating, by running this command, that\n\t * the extension owner can drop the object whenever they feel like it,\n\t * which is not considered a problem.\n\t */\n\tcheck_object_ownership(GetUserId(),\n\t\t\t\t\t\t stmt->objectType, address, stmt->object, rel);\n\n\t/*\n\t * If a relation was involved, it would have been opened and locked. We\n\t * don't need the relation here, but we'll retain the lock until commit.\n\t */\n\tif (rel)\n\t\ttable_close(rel, NoLock);\n\n\trefAddr = get_object_address(OBJECT_EXTENSION, (Node *) stmt->extname,\n\t\t\t\t\t\t\t\t &rel, AccessExclusiveLock, false);\n\tAssert(rel == NULL);\n\tif (refAddress)\n\t\t*refAddress = refAddr;\n\n\trecordDependencyOn(&address, &refAddr, DEPENDENCY_AUTO_EXTENSION);\n\n\treturn address;\n}", "project": "postgres", "hash": 169828503212497787193156423479860345699, "size": 38, "commit_id": "b048f558dd7c26a0c630a2cff29d3d8981eaf6b9", "message": "Fix priv checks for ALTER <object> DEPENDS ON EXTENSION\n\nMarking an object as dependant on an extension did not have any\nprivilege check whatsoever; this allowed any user to mark objects as\ndroppable by anyone able to DROP EXTENSION, which could be used to cause\nsystem-wide havoc. Disallow by checking that the calling user owns the\nmentioned object.\n\n(No constraints are placed on the extension.)\n\nSecurity: CVE-2020-1720\nReported-by: Tom Lane\nDiscussion: 31605.1566429043@sss.pgh.pa.us", "target": 0, "dataset": "other", "idx": 423628}
  803. {"func": "static Image *ReadXPMImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n *grey,\n key[MaxTextExtent],\n target[MaxTextExtent],\n *xpm_buffer;\n\n Image\n *image;\n\n MagickBooleanType\n active,\n status;\n\n register char\n *next,\n *p,\n *q;\n\n register IndexPacket\n *indexes;\n\n register PixelPacket\n *r;\n\n register ssize_t\n x;\n\n size_t\n length;\n\n SplayTreeInfo\n *xpm_colors;\n\n ssize_t\n count,\n j,\n y;\n\n unsigned long\n colors,\n columns,\n rows,\n width;\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 {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read XPM file.\n */\n length=MaxTextExtent;\n xpm_buffer=(char *) AcquireQuantumMemory((size_t) length,sizeof(*xpm_buffer));\n if (xpm_buffer == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *xpm_buffer='\\0';\n p=xpm_buffer;\n while (ReadBlobString(image,p) != (char *) NULL)\n {\n if ((*p == '#') && ((p == xpm_buffer) || (*(p-1) == '\\n')))\n continue;\n if ((*p == '}') && (*(p+1) == ';'))\n break;\n p+=strlen(p);\n if ((size_t) (p-xpm_buffer+MaxTextExtent) < length)\n continue;\n length<<=1;\n xpm_buffer=(char *) ResizeQuantumMemory(xpm_buffer,length+MaxTextExtent,\n sizeof(*xpm_buffer));\n if (xpm_buffer == (char *) NULL)\n break;\n p=xpm_buffer+strlen(xpm_buffer);\n }\n if (xpm_buffer == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Remove comments.\n */\n count=0;\n width=0;\n for (p=xpm_buffer; *p != '\\0'; p++)\n {\n if (*p != '\"')\n continue;\n count=(ssize_t) sscanf(p+1,\"%lu %lu %lu %lu\",&columns,&rows,&colors,&width);\n image->columns=columns;\n image->rows=rows;\n image->colors=colors;\n if (count == 4)\n break;\n }\n if ((count != 4) || (width == 0) || (width > 3) ||\n (image->columns == 0) || (image->rows == 0) ||\n (image->colors == 0) || (image->colors > MaxColormapSize))\n {\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n /*\n Remove unquoted characters.\n */\n active=MagickFalse;\n for (q=xpm_buffer; *p != '\\0'; )\n {\n if (*p++ == '\"')\n {\n if (active != MagickFalse)\n *q++='\\n';\n active=active != MagickFalse ? MagickFalse : MagickTrue;\n }\n if (active != MagickFalse)\n *q++=(*p);\n }\n *q='\\0';\n if (active != MagickFalse)\n {\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n /*\n Initialize image structure.\n */\n xpm_colors=NewSplayTree(CompareXPMColor,RelinquishMagickMemory,\n (void *(*)(void *)) NULL);\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n {\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Read image colormap.\n */\n image->depth=1;\n next=NextXPMLine(xpm_buffer);\n for (j=0; (j < (ssize_t) image->colors) && (next != (char *) NULL); j++)\n {\n char\n symbolic[MagickPathExtent];\n\n MagickPixelPacket\n pixel;\n\n p=next;\n next=NextXPMLine(p);\n if (next == (char *) NULL)\n break;\n length=MagickMin((size_t) width,MagickPathExtent-1);\n if (CopyXPMColor(key,p,length) != (ssize_t) length)\n break;\n status=AddValueToSplayTree(xpm_colors,ConstantString(key),(void *) j);\n /*\n Parse color.\n */\n (void) CopyMagickString(target,\"gray\",MaxTextExtent);\n q=(char *) NULL;\n if (strlen(p) > width)\n q=ParseXPMColor(p+width,MagickTrue);\n *symbolic='\\0';\n if (q != (char *) NULL)\n {\n while ((isspace((int) ((unsigned char) *q)) == 0) && (*q != '\\0'))\n q++;\n if ((next-q) < 0)\n break;\n if (next != (char *) NULL)\n (void) CopyXPMColor(target,q,MagickMin((size_t) (next-q),\n MaxTextExtent-1));\n else\n (void) CopyMagickString(target,q,MaxTextExtent);\n q=ParseXPMColor(target,MagickFalse);\n (void) CopyXPMColor(symbolic,q,MagickMin((size_t) (next-q),\n MagickPathExtent-1));\n if (q != (char *) NULL)\n *q='\\0';\n }\n StripString(target);\n if (*symbolic != '\\0')\n (void) AddValueToSplayTree(xpm_symbolic,ConstantString(target),\n ConstantString(symbolic));\n grey=strstr(target,\"grey\");\n if (grey != (char *) NULL)\n grey[2]='a';\n if (LocaleCompare(target,\"none\") == 0)\n {\n image->storage_class=DirectClass;\n image->matte=MagickTrue;\n }\n status=QueryColorCompliance(target,XPMCompliance,&image->colormap[j],\n exception);\n if (status == MagickFalse)\n break;\n (void) QueryMagickColorCompliance(target,XPMCompliance,&pixel,exception);\n if (image->depth < pixel.depth)\n image->depth=pixel.depth;\n }\n if (j < (ssize_t) image->colors)\n {\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n }\n j=0;\n if (image_info->ping == MagickFalse)\n {\n /*\n Read image pixels.\n */\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n return(DestroyImageList(image));\n }\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=NextXPMLine(p);\n if (p == (char *) NULL)\n break;\n r=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (r == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n ssize_t\n count;\n\n count=CopyXPMColor(key,p,MagickMin(width,MaxTextExtent-1));\n if (count != (ssize_t) width)\n break;\n j=(ssize_t) GetValueFromSplayTree(xpm_colors,key);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(indexes+x,j);\n *r=image->colormap[j];\n p+=count;\n r++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n if (y < (ssize_t) image->rows)\n {\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"NotEnoughPixelData\");\n }\n }\n /*\n Relinquish resources.\n */\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick6", "hash": 259050726019501944998374563698666005017, "size": 275, "commit_id": "26538669546730c5b2dc36e7d48850f1f6928f94", "message": "https://github.com/ImageMagick/ImageMagick/issues/1895", "target": 1, "dataset": "other", "idx": 209922}
  804. {"func": "static Image *ReadXPMImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n *grey,\n key[MaxTextExtent],\n target[MaxTextExtent],\n *xpm_buffer;\n\n Image\n *image;\n\n MagickBooleanType\n active,\n status;\n\n register char\n *next,\n *p,\n *q;\n\n register IndexPacket\n *indexes;\n\n register PixelPacket\n *r;\n\n register ssize_t\n x;\n\n size_t\n length;\n\n SplayTreeInfo\n *xpm_colors;\n\n ssize_t\n count,\n j,\n y;\n\n unsigned long\n colors,\n columns,\n rows,\n width;\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 {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read XPM file.\n */\n length=MaxTextExtent;\n xpm_buffer=(char *) AcquireQuantumMemory((size_t) length,sizeof(*xpm_buffer));\n if (xpm_buffer == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *xpm_buffer='\\0';\n p=xpm_buffer;\n while (ReadBlobString(image,p) != (char *) NULL)\n {\n if ((*p == '#') && ((p == xpm_buffer) || (*(p-1) == '\\n')))\n continue;\n if ((*p == '}') && (*(p+1) == ';'))\n break;\n p+=strlen(p);\n if ((size_t) (p-xpm_buffer+MaxTextExtent) < length)\n continue;\n length<<=1;\n xpm_buffer=(char *) ResizeQuantumMemory(xpm_buffer,length+MaxTextExtent,\n sizeof(*xpm_buffer));\n if (xpm_buffer == (char *) NULL)\n break;\n p=xpm_buffer+strlen(xpm_buffer);\n }\n if (xpm_buffer == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Remove comments.\n */\n count=0;\n width=0;\n for (p=xpm_buffer; *p != '\\0'; p++)\n {\n if (*p != '\"')\n continue;\n count=(ssize_t) sscanf(p+1,\"%lu %lu %lu %lu\",&columns,&rows,&colors,&width);\n image->columns=columns;\n image->rows=rows;\n image->colors=colors;\n if (count == 4)\n break;\n }\n if ((count != 4) || (width == 0) || (width > 3) ||\n (image->columns == 0) || (image->rows == 0) ||\n (image->colors == 0) || (image->colors > MaxColormapSize))\n {\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n /*\n Remove unquoted characters.\n */\n active=MagickFalse;\n for (q=xpm_buffer; *p != '\\0'; )\n {\n if (*p++ == '\"')\n {\n if (active != MagickFalse)\n *q++='\\n';\n active=active != MagickFalse ? MagickFalse : MagickTrue;\n }\n if (active != MagickFalse)\n *q++=(*p);\n }\n *q='\\0';\n if (active != MagickFalse)\n {\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n /*\n Initialize image structure.\n */\n xpm_colors=NewSplayTree(CompareXPMColor,RelinquishMagickMemory,\n (void *(*)(void *)) NULL);\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n {\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Read image colormap.\n */\n image->depth=1;\n next=NextXPMLine(xpm_buffer);\n for (j=0; (j < (ssize_t) image->colors) && (next != (char *) NULL); j++)\n {\n char\n symbolic[MagickPathExtent];\n\n MagickPixelPacket\n pixel;\n\n p=next;\n next=NextXPMLine(p);\n if (next == (char *) NULL)\n break;\n length=MagickMin((size_t) width,MagickPathExtent-1);\n if (CopyXPMColor(key,p,length) != (ssize_t) length)\n break;\n status=AddValueToSplayTree(xpm_colors,ConstantString(key),(void *) j);\n /*\n Parse color.\n */\n (void) memset(target,0,sizeof(target));\n (void) CopyMagickString(target,\"gray\",MaxTextExtent);\n q=(char *) NULL;\n if (strlen(p) > width)\n q=ParseXPMColor(p+width,MagickTrue);\n (void) memset(symbolic,0,sizeof(symbolic));\n *symbolic='\\0';\n if (q != (char *) NULL)\n {\n while ((isspace((int) ((unsigned char) *q)) == 0) && (*q != '\\0'))\n q++;\n if ((next-q) < 0)\n break;\n if (next != (char *) NULL)\n (void) CopyXPMColor(target,q,MagickMin((size_t) (next-q),\n MaxTextExtent-1));\n else\n (void) CopyMagickString(target,q,MaxTextExtent);\n q=ParseXPMColor(target,MagickFalse);\n (void) CopyXPMColor(symbolic,q,MagickMin((size_t) (next-q),\n MagickPathExtent-1));\n if (q != (char *) NULL)\n *q='\\0';\n }\n StripString(target);\n if (*symbolic != '\\0')\n (void) AddValueToSplayTree(xpm_symbolic,ConstantString(target),\n ConstantString(symbolic));\n grey=strstr(target,\"grey\");\n if (grey != (char *) NULL)\n grey[2]='a';\n if (LocaleCompare(target,\"none\") == 0)\n {\n image->storage_class=DirectClass;\n image->matte=MagickTrue;\n }\n status=QueryColorCompliance(target,XPMCompliance,&image->colormap[j],\n exception);\n if (status == MagickFalse)\n break;\n (void) QueryMagickColorCompliance(target,XPMCompliance,&pixel,exception);\n if (image->depth < pixel.depth)\n image->depth=pixel.depth;\n }\n if (j < (ssize_t) image->colors)\n {\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n }\n j=0;\n if (image_info->ping == MagickFalse)\n {\n /*\n Read image pixels.\n */\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n return(DestroyImageList(image));\n }\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=NextXPMLine(p);\n if (p == (char *) NULL)\n break;\n r=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (r == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n ssize_t\n count;\n\n count=CopyXPMColor(key,p,MagickMin(width,MaxTextExtent-1));\n if (count != (ssize_t) width)\n break;\n j=(ssize_t) GetValueFromSplayTree(xpm_colors,key);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(indexes+x,j);\n *r=image->colormap[j];\n p+=count;\n r++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n if (y < (ssize_t) image->rows)\n {\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"NotEnoughPixelData\");\n }\n }\n /*\n Relinquish resources.\n */\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick6", "hash": 89856644996065360037481487117834578276, "size": 277, "commit_id": "26538669546730c5b2dc36e7d48850f1f6928f94", "message": "https://github.com/ImageMagick/ImageMagick/issues/1895", "target": 0, "dataset": "other", "idx": 424306}
  805. {"func": "rfbSetClientColourMapBGR233(rfbClientPtr cl)\n{\n char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2];\n rfbSetColourMapEntriesMsg *scme = (rfbSetColourMapEntriesMsg *)buf;\n uint16_t *rgb = (uint16_t *)(&buf[sz_rfbSetColourMapEntriesMsg]);\n int i, len;\n int r, g, b;\n\n if (cl->format.bitsPerPixel != 8 ) {\n rfbErr(\"%s: client not 8 bits per pixel\\n\",\n \"rfbSetClientColourMapBGR233\");\n rfbCloseClient(cl);\n return FALSE;\n }\n \n scme->type = rfbSetColourMapEntries;\n\n scme->firstColour = Swap16IfLE(0);\n scme->nColours = Swap16IfLE(256);\n\n len = sz_rfbSetColourMapEntriesMsg;\n\n i = 0;\n\n for (b = 0; b < 4; b++) {\n for (g = 0; g < 8; g++) {\n for (r = 0; r < 8; r++) {\n rgb[i++] = Swap16IfLE(r * 65535 / 7);\n rgb[i++] = Swap16IfLE(g * 65535 / 7);\n rgb[i++] = Swap16IfLE(b * 65535 / 3);\n }\n }\n }\n\n len += 256 * 3 * 2;\n\n if (rfbWriteExact(cl, buf, len) < 0) {\n rfbLogPerror(\"rfbSetClientColourMapBGR233: write\");\n rfbCloseClient(cl);\n return FALSE;\n }\n return TRUE;\n}", "project": "libvncserver", "hash": 78377316020899026641978446341637956952, "size": 43, "commit_id": "53073c8d7e232151ea2ecd8a1243124121e10e2d", "message": "libvncserver: fix pointer aliasing/alignment issue\n\nAccessing byte-aligned data through uint16_t pointers can cause crashes\non some platforms or reduce the performance. Therefore ensure a proper\nstack alignment.", "target": 1, "dataset": "other", "idx": 209932}
  806. {"func": "rfbSetClientColourMapBGR233(rfbClientPtr cl)\n{\n union {\n char bytes[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2];\n rfbSetColourMapEntriesMsg msg;\n } buf;\n rfbSetColourMapEntriesMsg *scme = &buf.msg;\n uint16_t *rgb = (uint16_t *)(&buf.bytes[sz_rfbSetColourMapEntriesMsg]);\n int i, len;\n int r, g, b;\n\n if (cl->format.bitsPerPixel != 8 ) {\n rfbErr(\"%s: client not 8 bits per pixel\\n\",\n \"rfbSetClientColourMapBGR233\");\n rfbCloseClient(cl);\n return FALSE;\n }\n \n scme->type = rfbSetColourMapEntries;\n\n scme->firstColour = Swap16IfLE(0);\n scme->nColours = Swap16IfLE(256);\n\n len = sz_rfbSetColourMapEntriesMsg;\n\n i = 0;\n\n for (b = 0; b < 4; b++) {\n for (g = 0; g < 8; g++) {\n for (r = 0; r < 8; r++) {\n rgb[i++] = Swap16IfLE(r * 65535 / 7);\n rgb[i++] = Swap16IfLE(g * 65535 / 7);\n rgb[i++] = Swap16IfLE(b * 65535 / 3);\n }\n }\n }\n\n len += 256 * 3 * 2;\n\n if (rfbWriteExact(cl, buf.bytes, len) < 0) {\n rfbLogPerror(\"rfbSetClientColourMapBGR233: write\");\n rfbCloseClient(cl);\n return FALSE;\n }\n return TRUE;\n}", "project": "libvncserver", "hash": 332019210180149550878360388455728173657, "size": 46, "commit_id": "53073c8d7e232151ea2ecd8a1243124121e10e2d", "message": "libvncserver: fix pointer aliasing/alignment issue\n\nAccessing byte-aligned data through uint16_t pointers can cause crashes\non some platforms or reduce the performance. Therefore ensure a proper\nstack alignment.", "target": 0, "dataset": "other", "idx": 424538}
  807. {"func": "static int ntlm_read_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge)\n{\n\tsize_t size;\n\tStream_Read_UINT8(s, challenge->RespType);\n\tStream_Read_UINT8(s, challenge->HiRespType);\n\tStream_Read_UINT16(s, challenge->Reserved1);\n\tStream_Read_UINT32(s, challenge->Reserved2);\n\tStream_Read(s, challenge->Timestamp, 8);\n\tStream_Read(s, challenge->ClientChallenge, 8);\n\tStream_Read_UINT32(s, challenge->Reserved3);\n\tsize = Stream_Length(s) - Stream_GetPosition(s);\n\n\tif (size > UINT32_MAX)\n\t\treturn -1;\n\n\tchallenge->cbAvPairs = size;\n\tchallenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs);\n\n\tif (!challenge->AvPairs)\n\t\treturn -1;\n\n\tStream_Read(s, challenge->AvPairs, size);\n\treturn 1;\n}", "project": "FreeRDP", "hash": 112521265647314697012790560885353393661, "size": 24, "commit_id": "c098f21fdaadca57ff649eee1674f6cc321a2ec4", "message": "Fixed oob read in ntlm_read_ntlm_v2_response", "target": 1, "dataset": "other", "idx": 209951}
  808. {"func": "static int ntlm_read_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge)\n{\n\tsize_t size;\n\tif (Stream_GetRemainingLength(s) < 28)\n\t\treturn -1;\n\n\tStream_Read_UINT8(s, challenge->RespType);\n\tStream_Read_UINT8(s, challenge->HiRespType);\n\tStream_Read_UINT16(s, challenge->Reserved1);\n\tStream_Read_UINT32(s, challenge->Reserved2);\n\tStream_Read(s, challenge->Timestamp, 8);\n\tStream_Read(s, challenge->ClientChallenge, 8);\n\tStream_Read_UINT32(s, challenge->Reserved3);\n\tsize = Stream_Length(s) - Stream_GetPosition(s);\n\n\tif (size > UINT32_MAX)\n\t\treturn -1;\n\n\tchallenge->cbAvPairs = size;\n\tchallenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs);\n\n\tif (!challenge->AvPairs)\n\t\treturn -1;\n\n\tStream_Read(s, challenge->AvPairs, size);\n\treturn 1;\n}", "project": "FreeRDP", "hash": 325236519997364558892068820772982758036, "size": 27, "commit_id": "c098f21fdaadca57ff649eee1674f6cc321a2ec4", "message": "Fixed oob read in ntlm_read_ntlm_v2_response", "target": 0, "dataset": "other", "idx": 424858}
  809. {"func": "sftp_client_message sftp_get_client_message(sftp_session sftp) {\n ssh_session session = sftp->session;\n sftp_packet packet;\n sftp_client_message msg;\n ssh_buffer payload;\n int rc;\n\n msg = malloc(sizeof (struct sftp_client_message_struct));\n if (msg == NULL) {\n ssh_set_error_oom(session);\n return NULL;\n }\n ZERO_STRUCTP(msg);\n\n packet = sftp_packet_read(sftp);\n if (packet == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n payload = packet->payload;\n msg->type = packet->type;\n msg->sftp = sftp;\n\n /* take a copy of the whole packet */\n msg->complete_message = ssh_buffer_new();\n if (msg->complete_message == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n ssh_buffer_add_data(msg->complete_message,\n ssh_buffer_get(payload),\n ssh_buffer_get_len(payload));\n\n ssh_buffer_get_u32(payload, &msg->id);\n\n switch(msg->type) {\n case SSH_FXP_CLOSE:\n case SSH_FXP_READDIR:\n msg->handle = ssh_buffer_get_ssh_string(payload);\n if (msg->handle == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_READ:\n rc = ssh_buffer_unpack(payload,\n \"Sqd\",\n &msg->handle,\n &msg->offset,\n &msg->len);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_WRITE:\n rc = ssh_buffer_unpack(payload,\n \"SqS\",\n &msg->handle,\n &msg->offset,\n &msg->data);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_REMOVE:\n case SSH_FXP_RMDIR:\n case SSH_FXP_OPENDIR:\n case SSH_FXP_READLINK:\n case SSH_FXP_REALPATH:\n rc = ssh_buffer_unpack(payload,\n \"s\",\n &msg->filename);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_RENAME:\n case SSH_FXP_SYMLINK:\n rc = ssh_buffer_unpack(payload,\n \"sS\",\n &msg->filename,\n &msg->data);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_MKDIR:\n case SSH_FXP_SETSTAT:\n rc = ssh_buffer_unpack(payload,\n \"s\",\n &msg->filename);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n msg->attr = sftp_parse_attr(sftp, payload, 0);\n if (msg->attr == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_FSETSTAT:\n msg->handle = ssh_buffer_get_ssh_string(payload);\n if (msg->handle == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n msg->attr = sftp_parse_attr(sftp, payload, 0);\n if (msg->attr == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_LSTAT:\n case SSH_FXP_STAT:\n rc = ssh_buffer_unpack(payload,\n \"s\",\n &msg->filename);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n if(sftp->version > 3) {\n ssh_buffer_unpack(payload, \"d\", &msg->flags);\n }\n break;\n case SSH_FXP_OPEN:\n rc = ssh_buffer_unpack(payload,\n \"sd\",\n &msg->filename,\n &msg->flags);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n msg->attr = sftp_parse_attr(sftp, payload, 0);\n if (msg->attr == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_FSTAT:\n rc = ssh_buffer_unpack(payload,\n \"S\",\n &msg->handle);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_EXTENDED:\n rc = ssh_buffer_unpack(payload,\n \"s\",\n &msg->submessage);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n if (strcmp(msg->submessage, \"hardlink@openssh.com\") == 0 ||\n strcmp(msg->submessage, \"posix-rename@openssh.com\") == 0) {\n rc = ssh_buffer_unpack(payload,\n \"sS\",\n &msg->filename,\n &msg->data);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n }\n break;\n default:\n ssh_set_error(sftp->session, SSH_FATAL,\n \"Received unhandled sftp message %d\", msg->type);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n return msg;\n}", "project": "libssh-mirror", "hash": 104812262391619336608412301470901113139, "size": 203, "commit_id": "2782cb0495b7450bd8fe43ce4af886b66fea6c40", "message": "sftpserver: Add missing return check for ssh_buffer_add_data()\n\nSigned-off-by: Andreas Schneider <asn@cryptomilk.org>\nReviewed-by: Anderson Toshiyuki Sasaki <ansasaki@redhat.com>\nReviewed-by: Jakub Jelen <jjelen@redhat.com>", "target": 1, "dataset": "other", "idx": 209954}
  810. {"func": "sftp_client_message sftp_get_client_message(sftp_session sftp) {\n ssh_session session = sftp->session;\n sftp_packet packet;\n sftp_client_message msg;\n ssh_buffer payload;\n int rc;\n\n msg = malloc(sizeof (struct sftp_client_message_struct));\n if (msg == NULL) {\n ssh_set_error_oom(session);\n return NULL;\n }\n ZERO_STRUCTP(msg);\n\n packet = sftp_packet_read(sftp);\n if (packet == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n payload = packet->payload;\n msg->type = packet->type;\n msg->sftp = sftp;\n\n /* take a copy of the whole packet */\n msg->complete_message = ssh_buffer_new();\n if (msg->complete_message == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n rc = ssh_buffer_add_data(msg->complete_message,\n ssh_buffer_get(payload),\n ssh_buffer_get_len(payload));\n if (rc < 0) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n ssh_buffer_get_u32(payload, &msg->id);\n\n switch(msg->type) {\n case SSH_FXP_CLOSE:\n case SSH_FXP_READDIR:\n msg->handle = ssh_buffer_get_ssh_string(payload);\n if (msg->handle == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_READ:\n rc = ssh_buffer_unpack(payload,\n \"Sqd\",\n &msg->handle,\n &msg->offset,\n &msg->len);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_WRITE:\n rc = ssh_buffer_unpack(payload,\n \"SqS\",\n &msg->handle,\n &msg->offset,\n &msg->data);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_REMOVE:\n case SSH_FXP_RMDIR:\n case SSH_FXP_OPENDIR:\n case SSH_FXP_READLINK:\n case SSH_FXP_REALPATH:\n rc = ssh_buffer_unpack(payload,\n \"s\",\n &msg->filename);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_RENAME:\n case SSH_FXP_SYMLINK:\n rc = ssh_buffer_unpack(payload,\n \"sS\",\n &msg->filename,\n &msg->data);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_MKDIR:\n case SSH_FXP_SETSTAT:\n rc = ssh_buffer_unpack(payload,\n \"s\",\n &msg->filename);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n msg->attr = sftp_parse_attr(sftp, payload, 0);\n if (msg->attr == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_FSETSTAT:\n msg->handle = ssh_buffer_get_ssh_string(payload);\n if (msg->handle == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n msg->attr = sftp_parse_attr(sftp, payload, 0);\n if (msg->attr == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_LSTAT:\n case SSH_FXP_STAT:\n rc = ssh_buffer_unpack(payload,\n \"s\",\n &msg->filename);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n if(sftp->version > 3) {\n ssh_buffer_unpack(payload, \"d\", &msg->flags);\n }\n break;\n case SSH_FXP_OPEN:\n rc = ssh_buffer_unpack(payload,\n \"sd\",\n &msg->filename,\n &msg->flags);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n msg->attr = sftp_parse_attr(sftp, payload, 0);\n if (msg->attr == NULL) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_FSTAT:\n rc = ssh_buffer_unpack(payload,\n \"S\",\n &msg->handle);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n break;\n case SSH_FXP_EXTENDED:\n rc = ssh_buffer_unpack(payload,\n \"s\",\n &msg->submessage);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n if (strcmp(msg->submessage, \"hardlink@openssh.com\") == 0 ||\n strcmp(msg->submessage, \"posix-rename@openssh.com\") == 0) {\n rc = ssh_buffer_unpack(payload,\n \"sS\",\n &msg->filename,\n &msg->data);\n if (rc != SSH_OK) {\n ssh_set_error_oom(session);\n sftp_client_message_free(msg);\n return NULL;\n }\n }\n break;\n default:\n ssh_set_error(sftp->session, SSH_FATAL,\n \"Received unhandled sftp message %d\", msg->type);\n sftp_client_message_free(msg);\n return NULL;\n }\n\n return msg;\n}", "project": "libssh-mirror", "hash": 111915200315433769761170865971793335091, "size": 208, "commit_id": "2782cb0495b7450bd8fe43ce4af886b66fea6c40", "message": "sftpserver: Add missing return check for ssh_buffer_add_data()\n\nSigned-off-by: Andreas Schneider <asn@cryptomilk.org>\nReviewed-by: Anderson Toshiyuki Sasaki <ansasaki@redhat.com>\nReviewed-by: Jakub Jelen <jjelen@redhat.com>", "target": 0, "dataset": "other", "idx": 424886}
  811. {"func": "static int changedline (const Proto *p, int oldpc, int newpc) {\n while (oldpc++ < newpc) {\n if (p->lineinfo[oldpc] != 0)\n return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));\n }\n return 0; /* no line changes in the way */\n}", "project": "lua", "hash": 103380299185166225191075529446543003471, "size": 7, "commit_id": "ae5b5ba529753c7a653901ffc29b5ea24c3fdf3a", "message": "Fixed bug: line hooks in stripped functions\n\nLine-hook handling was accessing debug info. without checking whether\nit was present.", "target": 1, "dataset": "other", "idx": 210098}
  812. {"func": "static int changedline (const Proto *p, int oldpc, int newpc) {\n if (p->lineinfo == NULL) /* no debug information? */\n return 0;\n while (oldpc++ < newpc) {\n if (p->lineinfo[oldpc] != 0)\n return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));\n }\n return 0; /* no line changes between positions */\n}", "project": "lua", "hash": 219668759070622296330128934071627053940, "size": 9, "commit_id": "ae5b5ba529753c7a653901ffc29b5ea24c3fdf3a", "message": "Fixed bug: line hooks in stripped functions\n\nLine-hook handling was accessing debug info. without checking whether\nit was present.", "target": 0, "dataset": "other", "idx": 427930}
  813. {"func": "int init_aliases(void)\n{\n FILE *fp;\n char alias[MAXALIASLEN + 1U];\n char dir[PATH_MAX + 1U];\n\n if ((fp = fopen(ALIASES_FILE, \"r\")) == NULL) {\n return 0;\n }\n while (fgets(alias, sizeof alias, fp) != NULL) {\n if (*alias == '#' || *alias == '\\n' || *alias == 0) {\n continue;\n }\n {\n char * const z = alias + strlen(alias) - 1U;\n\n if (*z != '\\n') {\n goto bad;\n }\n *z = 0;\n }\n do {\n if (fgets(dir, sizeof dir, fp) == NULL || *dir == 0) {\n goto bad;\n }\n {\n char * const z = dir + strlen(dir) - 1U;\n\n if (*z == '\\n') {\n *z = 0;\n }\n }\n } while (*dir == '#' || *dir == 0);\n if (head == NULL) {\n if ((head = tail = malloc(sizeof *head)) == NULL ||\n (tail->alias = strdup(alias)) == NULL ||\n (tail->dir = strdup(dir)) == NULL) {\n die_mem();\n }\n tail->next = NULL;\n } else {\n DirAlias *curr;\n\n if ((curr = malloc(sizeof *curr)) == NULL ||\n (curr->alias = strdup(alias)) == NULL ||\n (curr->dir = strdup(dir)) == NULL) {\n die_mem();\n }\n tail->next = curr;\n tail = curr;\n }\n }\n fclose(fp);\n aliases_up++;\n\n return 0;\n\n bad:\n fclose(fp);\n logfile(LOG_ERR, MSG_ALIASES_BROKEN_FILE \" [\" ALIASES_FILE \"]\");\n\n return -1;\n}", "project": "pure-ftpd", "hash": 117767822613476471687393411275640975670, "size": 63, "commit_id": "8d0d42542e2cb7a56d645fbe4d0ef436e38bcefa", "message": "diraliases: always set the tail of the list to NULL\n\nSpotted and reported by Antonio Norales from GitHub Security Labs.\nThanks!", "target": 1, "dataset": "other", "idx": 210109}
  814. {"func": "int init_aliases(void)\n{\n FILE *fp;\n char alias[MAXALIASLEN + 1U];\n char dir[PATH_MAX + 1U];\n\n if ((fp = fopen(ALIASES_FILE, \"r\")) == NULL) {\n return 0;\n }\n while (fgets(alias, sizeof alias, fp) != NULL) {\n if (*alias == '#' || *alias == '\\n' || *alias == 0) {\n continue;\n }\n {\n char * const z = alias + strlen(alias) - 1U;\n\n if (*z != '\\n') {\n goto bad;\n }\n *z = 0;\n }\n do {\n if (fgets(dir, sizeof dir, fp) == NULL || *dir == 0) {\n goto bad;\n }\n {\n char * const z = dir + strlen(dir) - 1U;\n\n if (*z == '\\n') {\n *z = 0;\n }\n }\n } while (*dir == '#' || *dir == 0);\n if (head == NULL) {\n if ((head = tail = malloc(sizeof *head)) == NULL ||\n (tail->alias = strdup(alias)) == NULL ||\n (tail->dir = strdup(dir)) == NULL) {\n die_mem();\n }\n } else {\n DirAlias *curr;\n\n if ((curr = malloc(sizeof *curr)) == NULL ||\n (curr->alias = strdup(alias)) == NULL ||\n (curr->dir = strdup(dir)) == NULL) {\n die_mem();\n }\n tail->next = curr;\n tail = curr;\n }\n tail->next = NULL;\n }\n fclose(fp);\n aliases_up++;\n\n return 0;\n\n bad:\n fclose(fp);\n logfile(LOG_ERR, MSG_ALIASES_BROKEN_FILE \" [\" ALIASES_FILE \"]\");\n\n return -1;\n}", "project": "pure-ftpd", "hash": 109088355298658185757450174813098275639, "size": 63, "commit_id": "8d0d42542e2cb7a56d645fbe4d0ef436e38bcefa", "message": "diraliases: always set the tail of the list to NULL\n\nSpotted and reported by Antonio Norales from GitHub Security Labs.\nThanks!", "target": 0, "dataset": "other", "idx": 428216}
  815. {"func": "read_and_discard_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n{\n JDIMENSION n;\n my_master_ptr master = (my_master_ptr)cinfo->master;\n JSAMPARRAY scanlines = NULL;\n void (*color_convert) (j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n JDIMENSION input_row, JSAMPARRAY output_buf,\n int num_rows) = NULL;\n void (*color_quantize) (j_decompress_ptr cinfo, JSAMPARRAY input_buf,\n JSAMPARRAY output_buf, int num_rows) = NULL;\n\n if (cinfo->cconvert && cinfo->cconvert->color_convert) {\n color_convert = cinfo->cconvert->color_convert;\n cinfo->cconvert->color_convert = noop_convert;\n }\n\n if (cinfo->cquantize && cinfo->cquantize->color_quantize) {\n color_quantize = cinfo->cquantize->color_quantize;\n cinfo->cquantize->color_quantize = noop_quantize;\n }\n\n if (master->using_merged_upsample && cinfo->max_v_samp_factor == 2) {\n my_merged_upsample_ptr upsample = (my_merged_upsample_ptr)cinfo->upsample;\n scanlines = &upsample->spare_row;\n }\n\n for (n = 0; n < num_lines; n++)\n jpeg_read_scanlines(cinfo, scanlines, 1);\n\n if (color_convert)\n cinfo->cconvert->color_convert = color_convert;\n\n if (color_quantize)\n cinfo->cquantize->color_quantize = color_quantize;\n}", "project": "libjpeg-turbo", "hash": 164487153551446965761993154553490265876, "size": 35, "commit_id": "6d2e8837b440ce4d8befd805a5abc0d351028d70", "message": "jpeg_skip_scanlines(): Avoid NULL + 0 UBSan error\n\nThis error occurs at the call to (*cinfo->cconvert->color_convert)() in\nsep_upsample() whenever cinfo->upsample->need_context_rows == TRUE\n(i.e. whenever h2v2 or h1v2 fancy upsampling is used.) The error is\ninnocuous, since (*cinfo->cconvert->color_convert)() points to a dummy\nfunction (noop_convert()) in that case.\n\nFixes #470", "target": 1, "dataset": "other", "idx": 210147}
  816. {"func": "read_and_discard_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n{\n JDIMENSION n;\n my_master_ptr master = (my_master_ptr)cinfo->master;\n JSAMPLE dummy_sample[1] = { 0 };\n JSAMPROW dummy_row = dummy_sample;\n JSAMPARRAY scanlines = NULL;\n void (*color_convert) (j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n JDIMENSION input_row, JSAMPARRAY output_buf,\n int num_rows) = NULL;\n void (*color_quantize) (j_decompress_ptr cinfo, JSAMPARRAY input_buf,\n JSAMPARRAY output_buf, int num_rows) = NULL;\n\n if (cinfo->cconvert && cinfo->cconvert->color_convert) {\n color_convert = cinfo->cconvert->color_convert;\n cinfo->cconvert->color_convert = noop_convert;\n /* This just prevents UBSan from complaining about adding 0 to a NULL\n * pointer. The pointer isn't actually used.\n */\n scanlines = &dummy_row;\n }\n\n if (cinfo->cquantize && cinfo->cquantize->color_quantize) {\n color_quantize = cinfo->cquantize->color_quantize;\n cinfo->cquantize->color_quantize = noop_quantize;\n }\n\n if (master->using_merged_upsample && cinfo->max_v_samp_factor == 2) {\n my_merged_upsample_ptr upsample = (my_merged_upsample_ptr)cinfo->upsample;\n scanlines = &upsample->spare_row;\n }\n\n for (n = 0; n < num_lines; n++)\n jpeg_read_scanlines(cinfo, scanlines, 1);\n\n if (color_convert)\n cinfo->cconvert->color_convert = color_convert;\n\n if (color_quantize)\n cinfo->cquantize->color_quantize = color_quantize;\n}", "project": "libjpeg-turbo", "hash": 83983514538588629499615690431545580587, "size": 41, "commit_id": "6d2e8837b440ce4d8befd805a5abc0d351028d70", "message": "jpeg_skip_scanlines(): Avoid NULL + 0 UBSan error\n\nThis error occurs at the call to (*cinfo->cconvert->color_convert)() in\nsep_upsample() whenever cinfo->upsample->need_context_rows == TRUE\n(i.e. whenever h2v2 or h1v2 fancy upsampling is used.) The error is\ninnocuous, since (*cinfo->cconvert->color_convert)() points to a dummy\nfunction (noop_convert()) in that case.\n\nFixes #470", "target": 0, "dataset": "other", "idx": 428737}
  817. {"func": "PHP_FUNCTION(enchant_broker_request_dict)\n{\n\tzval *broker;\n\tenchant_broker *pbroker;\n\tenchant_dict *dict;\n\tEnchantDict *d;\n\tchar *tag;\n\tint taglen;\n\tint pos;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rs\", &broker, &tag, &taglen) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tPHP_ENCHANT_GET_BROKER;\n\t\n\tif (taglen == 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Tag cannot be empty\");\n\t\tRETURN_FALSE;\n\t}\n\n\td = enchant_broker_request_dict(pbroker->pbroker, (const char *)tag);\n\tif (d) {\n\t\tif (pbroker->dictcnt) {\n\t\t\tpbroker->dict = (enchant_dict **)erealloc(pbroker->dict, sizeof(enchant_dict *) * pbroker->dictcnt);\n\t\t\tpos = pbroker->dictcnt++;\n\t\t} else {\n\t\t\tpbroker->dict = (enchant_dict **)emalloc(sizeof(enchant_dict *));\n\t\t\tpos = 0;\n\t\t\tpbroker->dictcnt++;\n\t\t}\n\n\t\tdict = pbroker->dict[pos] = (enchant_dict *)emalloc(sizeof(enchant_dict));\n\t\tdict->id = pos;\n\t\tdict->pbroker = pbroker;\n\t\tdict->pdict = d;\n\t\tdict->prev = pos ? pbroker->dict[pos-1] : NULL;\n\t\tdict->next = NULL;\n\t\tpbroker->dict[pos] = dict;\n\n\t\tif (pos) {\n\t\t\tpbroker->dict[pos-1]->next = dict;\n\t\t}\n\n\t\tdict->rsrc_id = ZEND_REGISTER_RESOURCE(return_value, dict, le_enchant_dict);\n\t\tzend_list_addref(pbroker->rsrc_id);\n\t} else {\n\t\tRETURN_FALSE;\n\t}\n}", "project": "php-src", "hash": 13727473563489801685086003443308994419, "size": 50, "commit_id": "bdfe457a2c1b47209e32783b3a6447e81baf179a", "message": "Port for for bug #68552", "target": 1, "dataset": "other", "idx": 210165}
  818. {"func": "PHP_FUNCTION(enchant_broker_request_dict)\n{\n\tzval *broker;\n\tenchant_broker *pbroker;\n\tenchant_dict *dict;\n\tEnchantDict *d;\n\tchar *tag;\n\tint taglen;\n\tint pos;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rs\", &broker, &tag, &taglen) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tPHP_ENCHANT_GET_BROKER;\n\t\n\tif (taglen == 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Tag cannot be empty\");\n\t\tRETURN_FALSE;\n\t}\n\n\td = enchant_broker_request_dict(pbroker->pbroker, (const char *)tag);\n\tif (d) {\n\t\tpos = pbroker->dictcnt++;\n\t\tif (pbroker->dictcnt) {\n\t\t\tpbroker->dict = (enchant_dict **)erealloc(pbroker->dict, sizeof(enchant_dict *) * pbroker->dictcnt);\n\t\t} else {\n\t\t\tpbroker->dict = (enchant_dict **)emalloc(sizeof(enchant_dict *));\n\t\t\tpos = 0;\n\t\t}\n\n\t\tdict = pbroker->dict[pos] = (enchant_dict *)emalloc(sizeof(enchant_dict));\n\t\tdict->id = pos;\n\t\tdict->pbroker = pbroker;\n\t\tdict->pdict = d;\n\t\tdict->prev = pos ? pbroker->dict[pos-1] : NULL;\n\t\tdict->next = NULL;\n\t\tpbroker->dict[pos] = dict;\n\n\t\tif (pos) {\n\t\t\tpbroker->dict[pos-1]->next = dict;\n\t\t}\n\n\t\tdict->rsrc_id = ZEND_REGISTER_RESOURCE(return_value, dict, le_enchant_dict);\n\t\tzend_list_addref(pbroker->rsrc_id);\n\t} else {\n\t\tRETURN_FALSE;\n\t}\n}", "project": "php-src", "hash": 290261600071308625104841727243059581538, "size": 49, "commit_id": "bdfe457a2c1b47209e32783b3a6447e81baf179a", "message": "Port for for bug #68552", "target": 0, "dataset": "other", "idx": 429189}
  819. {"func": "check_tty(const char *tty)\n{\n\t/* Check that we're not being set up to take a fall. */\n\tif ((tty == NULL) || (strlen(tty) == 0)) {\n\t\treturn NULL;\n\t}\n\t/* Pull out the meaningful part of the tty's name. */\n\tif (strchr(tty, '/') != NULL) {\n\t\tif (strncmp(tty, \"/dev/\", 5) != 0) {\n\t\t\t/* Make sure the device node is actually in /dev/,\n\t\t\t * noted by Michal Zalewski. */\n\t\t\treturn NULL;\n\t\t}\n\t\ttty = strrchr(tty, '/') + 1;\n\t}\n\t/* Make sure the tty wasn't actually a directory (no basename). */\n\tif (strlen(tty) == 0) {\n\t\treturn NULL;\n\t}\n\treturn tty;\n}", "project": "linux-pam", "hash": 336131573636879399421041172856936495490, "size": 21, "commit_id": "9dcead87e6d7f66d34e7a56d11a30daca367dffb", "message": "pam_timestamp: fix potential directory traversal issue (ticket #27)\n\npam_timestamp uses values of PAM_RUSER and PAM_TTY as components of\nthe timestamp pathname it creates, so extra care should be taken to\navoid potential directory traversal issues.\n\n* modules/pam_timestamp/pam_timestamp.c (check_tty): Treat\n\".\" and \"..\" tty values as invalid.\n(get_ruser): Treat \".\" and \"..\" ruser values, as well as any ruser\nvalue containing '/', as invalid.\n\nFixes CVE-2014-2583.\n\nReported-by: Sebastian Krahmer <krahmer@suse.de>", "target": 1, "dataset": "other", "idx": 210171}
  820. {"func": "check_tty(const char *tty)\n{\n\t/* Check that we're not being set up to take a fall. */\n\tif ((tty == NULL) || (strlen(tty) == 0)) {\n\t\treturn NULL;\n\t}\n\t/* Pull out the meaningful part of the tty's name. */\n\tif (strchr(tty, '/') != NULL) {\n\t\tif (strncmp(tty, \"/dev/\", 5) != 0) {\n\t\t\t/* Make sure the device node is actually in /dev/,\n\t\t\t * noted by Michal Zalewski. */\n\t\t\treturn NULL;\n\t\t}\n\t\ttty = strrchr(tty, '/') + 1;\n\t}\n\t/* Make sure the tty wasn't actually a directory (no basename). */\n\tif (!strlen(tty) || !strcmp(tty, \".\") || !strcmp(tty, \"..\")) {\n\t\treturn NULL;\n\t}\n\treturn tty;\n}", "project": "linux-pam", "hash": 1321413214506957733795541791949231362, "size": 21, "commit_id": "9dcead87e6d7f66d34e7a56d11a30daca367dffb", "message": "pam_timestamp: fix potential directory traversal issue (ticket #27)\n\npam_timestamp uses values of PAM_RUSER and PAM_TTY as components of\nthe timestamp pathname it creates, so extra care should be taken to\navoid potential directory traversal issues.\n\n* modules/pam_timestamp/pam_timestamp.c (check_tty): Treat\n\".\" and \"..\" tty values as invalid.\n(get_ruser): Treat \".\" and \"..\" ruser values, as well as any ruser\nvalue containing '/', as invalid.\n\nFixes CVE-2014-2583.\n\nReported-by: Sebastian Krahmer <krahmer@suse.de>", "target": 0, "dataset": "other", "idx": 429355}
  821. {"func": "get_ruser(pam_handle_t *pamh, char *ruserbuf, size_t ruserbuflen)\n{\n\tconst void *ruser;\n\tstruct passwd *pwd;\n\n\tif (ruserbuf == NULL || ruserbuflen < 1)\n\t\treturn -2;\n\t/* Get the name of the source user. */\n\tif (pam_get_item(pamh, PAM_RUSER, &ruser) != PAM_SUCCESS) {\n\t\truser = NULL;\n\t}\n\tif ((ruser == NULL) || (strlen(ruser) == 0)) {\n\t\t/* Barring that, use the current RUID. */\n\t\tpwd = pam_modutil_getpwuid(pamh, getuid());\n\t\tif (pwd != NULL) {\n\t\t\truser = pwd->pw_name;\n\t\t}\n\t}\n\tif (ruser == NULL || strlen(ruser) >= ruserbuflen) {\n\t\t*ruserbuf = '\\0';\n\t\treturn -1;\n\t}\n\tstrcpy(ruserbuf, ruser);\n\treturn 0;\n}", "project": "linux-pam", "hash": 227818384334126316111651650155998253999, "size": 25, "commit_id": "9dcead87e6d7f66d34e7a56d11a30daca367dffb", "message": "pam_timestamp: fix potential directory traversal issue (ticket #27)\n\npam_timestamp uses values of PAM_RUSER and PAM_TTY as components of\nthe timestamp pathname it creates, so extra care should be taken to\navoid potential directory traversal issues.\n\n* modules/pam_timestamp/pam_timestamp.c (check_tty): Treat\n\".\" and \"..\" tty values as invalid.\n(get_ruser): Treat \".\" and \"..\" ruser values, as well as any ruser\nvalue containing '/', as invalid.\n\nFixes CVE-2014-2583.\n\nReported-by: Sebastian Krahmer <krahmer@suse.de>", "target": 1, "dataset": "other", "idx": 210172}
  822. {"func": "get_ruser(pam_handle_t *pamh, char *ruserbuf, size_t ruserbuflen)\n{\n\tconst void *ruser;\n\tstruct passwd *pwd;\n\n\tif (ruserbuf == NULL || ruserbuflen < 1)\n\t\treturn -2;\n\t/* Get the name of the source user. */\n\tif (pam_get_item(pamh, PAM_RUSER, &ruser) != PAM_SUCCESS) {\n\t\truser = NULL;\n\t}\n\tif ((ruser == NULL) || (strlen(ruser) == 0)) {\n\t\t/* Barring that, use the current RUID. */\n\t\tpwd = pam_modutil_getpwuid(pamh, getuid());\n\t\tif (pwd != NULL) {\n\t\t\truser = pwd->pw_name;\n\t\t}\n\t} else {\n\t\t/*\n\t\t * This ruser is used by format_timestamp_name as a component\n\t\t * of constructed timestamp pathname, so \".\", \"..\", and '/'\n\t\t * are disallowed to avoid potential path traversal issues.\n\t\t */\n\t\tif (!strcmp(ruser, \".\") ||\n\t\t !strcmp(ruser, \"..\") ||\n\t\t strchr(ruser, '/')) {\n\t\t\truser = NULL;\n\t\t}\n\t}\n\tif (ruser == NULL || strlen(ruser) >= ruserbuflen) {\n\t\t*ruserbuf = '\\0';\n\t\treturn -1;\n\t}\n\tstrcpy(ruserbuf, ruser);\n\treturn 0;\n}", "project": "linux-pam", "hash": 113360647922111213131290475273018648503, "size": 36, "commit_id": "9dcead87e6d7f66d34e7a56d11a30daca367dffb", "message": "pam_timestamp: fix potential directory traversal issue (ticket #27)\n\npam_timestamp uses values of PAM_RUSER and PAM_TTY as components of\nthe timestamp pathname it creates, so extra care should be taken to\navoid potential directory traversal issues.\n\n* modules/pam_timestamp/pam_timestamp.c (check_tty): Treat\n\".\" and \"..\" tty values as invalid.\n(get_ruser): Treat \".\" and \"..\" ruser values, as well as any ruser\nvalue containing '/', as invalid.\n\nFixes CVE-2014-2583.\n\nReported-by: Sebastian Krahmer <krahmer@suse.de>", "target": 0, "dataset": "other", "idx": 429356}
  823. {"func": "int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n{\n size_t item_len;\n mysql->affected_rows= net_field_length_ll(&pos);\n mysql->insert_id=\t net_field_length_ll(&pos);\n mysql->server_status=uint2korr(pos);\n pos+=2;\n mysql->warning_count=uint2korr(pos);\n pos+=2;\n if (pos < mysql->net.read_pos+length)\n {\n if ((item_len= net_field_length(&pos)))\n mysql->info=(char*) pos;\n\n /* check if server supports session tracking */\n if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)\n {\n ma_clear_session_state(mysql);\n pos+= item_len;\n\n if (mysql->server_status & SERVER_SESSION_STATE_CHANGED)\n {\n int i;\n if (pos < mysql->net.read_pos + length)\n {\n LIST *session_item;\n MYSQL_LEX_STRING *str= NULL;\n enum enum_session_state_type si_type;\n uchar *old_pos= pos;\n size_t item_len= net_field_length(&pos); /* length for all items */\n\n /* length was already set, so make sure that info will be zero terminated */\n if (mysql->info)\n *old_pos= 0;\n\n while (item_len > 0)\n {\n size_t plen;\n char *data;\n old_pos= pos;\n si_type= (enum enum_session_state_type)net_field_length(&pos);\n switch(si_type) {\n case SESSION_TRACK_SCHEMA:\n case SESSION_TRACK_STATE_CHANGE:\n case SESSION_TRACK_TRANSACTION_CHARACTERISTICS:\n case SESSION_TRACK_SYSTEM_VARIABLES:\n if (si_type != SESSION_TRACK_STATE_CHANGE)\n net_field_length(&pos); /* ignore total length, item length will follow next */\n plen= net_field_length(&pos);\n if (!(session_item= ma_multi_malloc(0,\n &session_item, sizeof(LIST),\n &str, sizeof(MYSQL_LEX_STRING),\n &data, plen,\n NULL)))\n {\n ma_clear_session_state(mysql);\n SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n return -1;\n }\n str->length= plen;\n str->str= data;\n memcpy(str->str, (char *)pos, plen);\n pos+= plen;\n session_item->data= str;\n mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item);\n\n /* in case schema has changed, we have to update mysql->db */\n if (si_type == SESSION_TRACK_SCHEMA)\n {\n free(mysql->db);\n mysql->db= malloc(plen + 1);\n memcpy(mysql->db, str->str, plen);\n mysql->db[plen]= 0;\n }\n else if (si_type == SESSION_TRACK_SYSTEM_VARIABLES)\n {\n my_bool set_charset= 0;\n /* make sure that we update charset in case it has changed */\n if (!strncmp(str->str, \"character_set_client\", str->length))\n set_charset= 1;\n plen= net_field_length(&pos);\n if (!(session_item= ma_multi_malloc(0,\n &session_item, sizeof(LIST),\n &str, sizeof(MYSQL_LEX_STRING),\n &data, plen,\n NULL)))\n {\n ma_clear_session_state(mysql);\n SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n return -1;\n }\n str->length= plen;\n str->str= data;\n memcpy(str->str, (char *)pos, plen);\n pos+= plen;\n session_item->data= str;\n mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item);\n if (set_charset &&\n strncmp(mysql->charset->csname, str->str, str->length) != 0)\n {\n char cs_name[64];\n MARIADB_CHARSET_INFO *cs_info;\n memcpy(cs_name, str->str, str->length);\n cs_name[str->length]= 0;\n if ((cs_info = (MARIADB_CHARSET_INFO *)mysql_find_charset_name(cs_name)))\n mysql->charset= cs_info;\n }\n }\n break;\n default:\n /* not supported yet */\n plen= net_field_length(&pos);\n pos+= plen;\n break;\n }\n item_len-= (pos - old_pos);\n }\n }\n for (i= SESSION_TRACK_BEGIN; i <= SESSION_TRACK_END; i++)\n {\n mysql->extension->session_state[i].list= list_reverse(mysql->extension->session_state[i].list);\n mysql->extension->session_state[i].current= mysql->extension->session_state[i].list;\n }\n }\n }\n }\n /* CONC-351: clear session state information */\n else if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)\n ma_clear_session_state(mysql);\n return(0);\n}", "project": "mariadb-connector-c", "hash": 76318025094495661937304907006689356074, "size": 131, "commit_id": "2759b87d72926b7c9b5426437a7c8dd15ff57945", "message": "sanity checks for client-supplied OK packet content\n\nreported by Matthias Kaiser, Apple Information Security", "target": 1, "dataset": "other", "idx": 210193}
  824. {"func": "int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n{\n uchar *end= mysql->net.read_pos+length;\n size_t item_len;\n mysql->affected_rows= net_field_length_ll(&pos);\n mysql->insert_id=\t net_field_length_ll(&pos);\n mysql->server_status=uint2korr(pos);\n pos+=2;\n mysql->warning_count=uint2korr(pos);\n pos+=2;\n if (pos > end)\n goto corrupted;\n if (pos < end)\n {\n if ((item_len= net_field_length(&pos)))\n mysql->info=(char*) pos;\n if (pos + item_len > end)\n goto corrupted;\n\n /* check if server supports session tracking */\n if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)\n {\n ma_clear_session_state(mysql);\n pos+= item_len;\n\n if (mysql->server_status & SERVER_SESSION_STATE_CHANGED)\n {\n int i;\n if (pos < end)\n {\n LIST *session_item;\n MYSQL_LEX_STRING *str= NULL;\n enum enum_session_state_type si_type;\n uchar *old_pos= pos;\n\n item_len= net_field_length(&pos); /* length for all items */\n if (pos + item_len > end)\n goto corrupted;\n end= pos + item_len;\n\n /* length was already set, so make sure that info will be zero terminated */\n if (mysql->info)\n *old_pos= 0;\n\n while (pos < end)\n {\n size_t plen;\n char *data;\n si_type= (enum enum_session_state_type)net_field_length(&pos);\n switch(si_type) {\n case SESSION_TRACK_SCHEMA:\n case SESSION_TRACK_STATE_CHANGE:\n case SESSION_TRACK_TRANSACTION_CHARACTERISTICS:\n case SESSION_TRACK_SYSTEM_VARIABLES:\n if (si_type != SESSION_TRACK_STATE_CHANGE)\n net_field_length(&pos); /* ignore total length, item length will follow next */\n plen= net_field_length(&pos);\n if (pos + plen > end)\n goto corrupted;\n if (!(session_item= ma_multi_malloc(0,\n &session_item, sizeof(LIST),\n &str, sizeof(MYSQL_LEX_STRING),\n &data, plen,\n NULL)))\n goto oom;\n str->length= plen;\n str->str= data;\n memcpy(str->str, (char *)pos, plen);\n pos+= plen;\n session_item->data= str;\n mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item);\n\n /* in case schema has changed, we have to update mysql->db */\n if (si_type == SESSION_TRACK_SCHEMA)\n {\n free(mysql->db);\n mysql->db= malloc(plen + 1);\n memcpy(mysql->db, str->str, plen);\n mysql->db[plen]= 0;\n }\n else if (si_type == SESSION_TRACK_SYSTEM_VARIABLES)\n {\n my_bool set_charset= 0;\n /* make sure that we update charset in case it has changed */\n if (!strncmp(str->str, \"character_set_client\", str->length))\n set_charset= 1;\n plen= net_field_length(&pos);\n if (pos + plen > end)\n goto corrupted;\n if (!(session_item= ma_multi_malloc(0,\n &session_item, sizeof(LIST),\n &str, sizeof(MYSQL_LEX_STRING),\n &data, plen,\n NULL)))\n goto oom;\n str->length= plen;\n str->str= data;\n memcpy(str->str, (char *)pos, plen);\n pos+= plen;\n session_item->data= str;\n mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item);\n if (set_charset && str->length < CHARSET_NAME_LEN &&\n strncmp(mysql->charset->csname, str->str, str->length) != 0)\n {\n char cs_name[CHARSET_NAME_LEN];\n const MARIADB_CHARSET_INFO *cs_info;\n memcpy(cs_name, str->str, str->length);\n cs_name[str->length]= 0;\n if ((cs_info = mysql_find_charset_name(cs_name)))\n mysql->charset= cs_info;\n }\n }\n break;\n default:\n /* not supported yet */\n plen= net_field_length(&pos);\n if (pos + plen > end)\n goto corrupted;\n pos+= plen;\n break;\n }\n }\n }\n for (i= SESSION_TRACK_BEGIN; i <= SESSION_TRACK_END; i++)\n {\n mysql->extension->session_state[i].list= list_reverse(mysql->extension->session_state[i].list);\n mysql->extension->session_state[i].current= mysql->extension->session_state[i].list;\n }\n }\n }\n }\n /* CONC-351: clear session state information */\n else if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)\n ma_clear_session_state(mysql);\n return(0);\n\noom:\n ma_clear_session_state(mysql);\n SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n return -1;\n\ncorrupted:\n ma_clear_session_state(mysql);\n SET_CLIENT_ERROR(mysql, CR_MALFORMED_PACKET, SQLSTATE_UNKNOWN, 0);\n return -1;\n}", "project": "mariadb-connector-c", "hash": 291866632911754157865017334546963738553, "size": 146, "commit_id": "2759b87d72926b7c9b5426437a7c8dd15ff57945", "message": "sanity checks for client-supplied OK packet content\n\nreported by Matthias Kaiser, Apple Information Security", "target": 0, "dataset": "other", "idx": 429686}
  825. {"func": "virSecuritySELinuxMCSFind(virSecurityManager *mgr,\n const char *sens,\n int catMin,\n int catMax)\n{\n virSecuritySELinuxData *data = virSecurityManagerGetPrivateData(mgr);\n int catRange;\n char *mcs = NULL;\n\n /* +1 since virRandomInt range is exclusive of the upper bound */\n catRange = (catMax - catMin) + 1;\n\n if (catRange < 8) {\n virReportError(VIR_ERR_INTERNAL_ERROR,\n _(\"Category range c%d-c%d too small\"),\n catMin, catMax);\n return NULL;\n }\n\n VIR_DEBUG(\"Using sensitivity level '%s' cat min %d max %d range %d\",\n sens, catMin, catMax, catRange);\n\n for (;;) {\n int c1 = virRandomInt(catRange);\n int c2 = virRandomInt(catRange);\n\n VIR_DEBUG(\"Try cat %s:c%d,c%d\", sens, c1 + catMin, c2 + catMin);\n\n if (c1 == c2) {\n mcs = g_strdup_printf(\"%s:c%d\", sens, catMin + c1);\n } else {\n if (c1 > c2) {\n int t = c1;\n c1 = c2;\n c2 = t;\n }\n mcs = g_strdup_printf(\"%s:c%d,c%d\", sens, catMin + c1, catMin + c2);\n }\n\n if (virHashLookup(data->mcs, mcs) == NULL)\n break;\n\n VIR_FREE(mcs);\n }\n\n return mcs;\n}", "project": "libvirt", "hash": 268703927834014537463145149594703911908, "size": 47, "commit_id": "15073504dbb624d3f6c911e85557019d3620fdb2", "message": "security: fix SELinux label generation logic\n\nA process can access a file if the set of MCS categories\nfor the file is equal-to *or* a subset-of, the set of\nMCS categories for the process.\n\nIf there are two VMs:\n\n a) svirt_t:s0:c117\n b) svirt_t:s0:c117,c720\n\nThen VM (b) is able to access files labelled for VM (a).\n\nIOW, we must discard case where the categories are equal\nbecause that is a subset of many other valid category pairs.\n\nFixes: https://gitlab.com/libvirt/libvirt/-/issues/153\nCVE-2021-3631\nReviewed-by: Peter Krempa <pkrempa@redhat.com>\nSigned-off-by: Daniel P. Berrang\u00e9 <berrange@redhat.com>", "target": 1, "dataset": "other", "idx": 210201}
  826. {"func": "virSecuritySELinuxMCSFind(virSecurityManager *mgr,\n const char *sens,\n int catMin,\n int catMax)\n{\n virSecuritySELinuxData *data = virSecurityManagerGetPrivateData(mgr);\n int catRange;\n char *mcs = NULL;\n\n /* +1 since virRandomInt range is exclusive of the upper bound */\n catRange = (catMax - catMin) + 1;\n\n if (catRange < 8) {\n virReportError(VIR_ERR_INTERNAL_ERROR,\n _(\"Category range c%d-c%d too small\"),\n catMin, catMax);\n return NULL;\n }\n\n VIR_DEBUG(\"Using sensitivity level '%s' cat min %d max %d range %d\",\n sens, catMin, catMax, catRange);\n\n for (;;) {\n int c1 = virRandomInt(catRange);\n int c2 = virRandomInt(catRange);\n\n VIR_DEBUG(\"Try cat %s:c%d,c%d\", sens, c1 + catMin, c2 + catMin);\n\n if (c1 == c2) {\n /*\n * A process can access a file if the set of MCS categories\n * for the file is equal-to *or* a subset-of, the set of\n * MCS categories for the process.\n *\n * IOW, we must discard case where the categories are equal\n * because that is a subset of other category pairs.\n */\n continue;\n } else {\n if (c1 > c2) {\n int t = c1;\n c1 = c2;\n c2 = t;\n }\n mcs = g_strdup_printf(\"%s:c%d,c%d\", sens, catMin + c1, catMin + c2);\n }\n\n if (virHashLookup(data->mcs, mcs) == NULL)\n break;\n\n VIR_FREE(mcs);\n }\n\n return mcs;\n}", "project": "libvirt", "hash": 143827953277160340656527682050918218776, "size": 55, "commit_id": "15073504dbb624d3f6c911e85557019d3620fdb2", "message": "security: fix SELinux label generation logic\n\nA process can access a file if the set of MCS categories\nfor the file is equal-to *or* a subset-of, the set of\nMCS categories for the process.\n\nIf there are two VMs:\n\n a) svirt_t:s0:c117\n b) svirt_t:s0:c117,c720\n\nThen VM (b) is able to access files labelled for VM (a).\n\nIOW, we must discard case where the categories are equal\nbecause that is a subset of many other valid category pairs.\n\nFixes: https://gitlab.com/libvirt/libvirt/-/issues/153\nCVE-2021-3631\nReviewed-by: Peter Krempa <pkrempa@redhat.com>\nSigned-off-by: Daniel P. Berrang\u00e9 <berrange@redhat.com>", "target": 0, "dataset": "other", "idx": 430309}
  827. {"func": "UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) {\n if(!isWritable() || srcLength == 0 || srcChars == NULL) {\n return *this;\n }\n\n // Perform all remaining operations relative to srcChars + srcStart.\n // From this point forward, do not use srcStart.\n srcChars += srcStart;\n\n if(srcLength < 0) {\n // get the srcLength if necessary\n if((srcLength = u_strlen(srcChars)) == 0) {\n return *this;\n }\n }\n\n int32_t oldLength = length();\n int32_t newLength = oldLength + srcLength;\n\n // Check for append onto ourself\n const UChar* oldArray = getArrayStart();\n if (isBufferWritable() &&\n oldArray < srcChars + srcLength &&\n srcChars < oldArray + oldLength) {\n // Copy into a new UnicodeString and start over\n UnicodeString copy(srcChars, srcLength);\n if (copy.isBogus()) {\n setToBogus();\n return *this;\n }\n return doAppend(copy.getArrayStart(), 0, srcLength);\n }\n\n // optimize append() onto a large-enough, owned string\n if((newLength <= getCapacity() && isBufferWritable()) ||\n cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {\n UChar *newArray = getArrayStart();\n // Do not copy characters when\n // UChar *buffer=str.getAppendBuffer(...);\n // is followed by\n // str.append(buffer, length);\n // or\n // str.appendString(buffer, length)\n // or similar.\n if(srcChars != newArray + oldLength) {\n us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength);\n }\n setLength(newLength);\n }\n return *this;\n}", "project": "icu", "hash": 78872655036842327692103499513475894622, "size": 51, "commit_id": "b7d08bc04a4296982fcef8b6b8a354a9e4e7afca", "message": "ICU-20958 Prevent SEGV_MAPERR in append\n\nSee #971", "target": 1, "dataset": "other", "idx": 210237}
  828. {"func": "UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) {\n if(!isWritable() || srcLength == 0 || srcChars == NULL) {\n return *this;\n }\n\n // Perform all remaining operations relative to srcChars + srcStart.\n // From this point forward, do not use srcStart.\n srcChars += srcStart;\n\n if(srcLength < 0) {\n // get the srcLength if necessary\n if((srcLength = u_strlen(srcChars)) == 0) {\n return *this;\n }\n }\n\n int32_t oldLength = length();\n int32_t newLength;\n if (uprv_add32_overflow(oldLength, srcLength, &newLength)) {\n setToBogus();\n return *this;\n }\n\n // Check for append onto ourself\n const UChar* oldArray = getArrayStart();\n if (isBufferWritable() &&\n oldArray < srcChars + srcLength &&\n srcChars < oldArray + oldLength) {\n // Copy into a new UnicodeString and start over\n UnicodeString copy(srcChars, srcLength);\n if (copy.isBogus()) {\n setToBogus();\n return *this;\n }\n return doAppend(copy.getArrayStart(), 0, srcLength);\n }\n\n // optimize append() onto a large-enough, owned string\n if((newLength <= getCapacity() && isBufferWritable()) ||\n cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {\n UChar *newArray = getArrayStart();\n // Do not copy characters when\n // UChar *buffer=str.getAppendBuffer(...);\n // is followed by\n // str.append(buffer, length);\n // or\n // str.appendString(buffer, length)\n // or similar.\n if(srcChars != newArray + oldLength) {\n us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength);\n }\n setLength(newLength);\n }\n return *this;\n}", "project": "icu", "hash": 202583290338277335296873764122279909646, "size": 55, "commit_id": "b7d08bc04a4296982fcef8b6b8a354a9e4e7afca", "message": "ICU-20958 Prevent SEGV_MAPERR in append\n\nSee #971", "target": 0, "dataset": "other", "idx": 430797}
  829. {"func": "HeaderLookupTable_t::lookup (const char *buf, const std::size_t len) const {\n const HeaderTableRecord *r = HttpHeaderHashTable::lookup(buf, len);\n if (!r)\n return BadHdr;\n return *r;\n}", "project": "squid", "hash": 2837537094058907697257649187599047333, "size": 6, "commit_id": "d09b34de2575af3bab4b34c775f93acb7270b4c3", "message": "Limit HeaderLookupTable_t::lookup() to BadHdr and specific IDs", "target": 1, "dataset": "other", "idx": 210242}
  830. {"func": "HeaderLookupTable_t::lookup (const char *buf, const std::size_t len) const {\n const HeaderTableRecord *r = HttpHeaderHashTable::lookup(buf, len);\n if (!r || r->id == Http::HdrType::OTHER)\n return BadHdr;\n return *r;\n}", "project": "squid", "hash": 43860048861657268208848208606759751881, "size": 6, "commit_id": "d09b34de2575af3bab4b34c775f93acb7270b4c3", "message": "Limit HeaderLookupTable_t::lookup() to BadHdr and specific IDs", "target": 0, "dataset": "other", "idx": 430901}
  831. {"func": "static int decode_attr_security_label(struct xdr_stream *xdr, uint32_t *bitmap,\n\t\t\t\t\tstruct nfs4_label *label)\n{\n\tuint32_t pi = 0;\n\tuint32_t lfs = 0;\n\t__u32 len;\n\t__be32 *p;\n\tint status = 0;\n\n\tif (unlikely(bitmap[2] & (FATTR4_WORD2_SECURITY_LABEL - 1U)))\n\t\treturn -EIO;\n\tif (likely(bitmap[2] & FATTR4_WORD2_SECURITY_LABEL)) {\n\t\tp = xdr_inline_decode(xdr, 4);\n\t\tif (unlikely(!p))\n\t\t\treturn -EIO;\n\t\tlfs = be32_to_cpup(p++);\n\t\tp = xdr_inline_decode(xdr, 4);\n\t\tif (unlikely(!p))\n\t\t\treturn -EIO;\n\t\tpi = be32_to_cpup(p++);\n\t\tp = xdr_inline_decode(xdr, 4);\n\t\tif (unlikely(!p))\n\t\t\treturn -EIO;\n\t\tlen = be32_to_cpup(p++);\n\t\tp = xdr_inline_decode(xdr, len);\n\t\tif (unlikely(!p))\n\t\t\treturn -EIO;\n\t\tif (len < NFS4_MAXLABELLEN) {\n\t\t\tif (label) {\n\t\t\t\tmemcpy(label->label, p, len);\n\t\t\t\tlabel->len = len;\n\t\t\t\tlabel->pi = pi;\n\t\t\t\tlabel->lfs = lfs;\n\t\t\t\tstatus = NFS_ATTR_FATTR_V4_SECURITY_LABEL;\n\t\t\t}\n\t\t\tbitmap[2] &= ~FATTR4_WORD2_SECURITY_LABEL;\n\t\t} else\n\t\t\tprintk(KERN_WARNING \"%s: label too long (%u)!\\n\",\n\t\t\t\t\t__func__, len);\n\t}\n\tif (label && label->label)\n\t\tdprintk(\"%s: label=%s, len=%d, PI=%d, LFS=%d\\n\", __func__,\n\t\t\t(char *)label->label, label->len, label->pi, label->lfs);\n\treturn status;\n}", "project": "linux", "hash": 293774740721234251683748491997728460674, "size": 45, "commit_id": "b4487b93545214a9db8cbf32e86411677b0cca21", "message": "nfs: Fix getxattr kernel panic and memory overflow\n\nMove the buffer size check to decode_attr_security_label() before memcpy()\nOnly call memcpy() if the buffer is large enough\n\nFixes: aa9c2669626c (\"NFS: Client implementation of Labeled-NFS\")\nSigned-off-by: Jeffrey Mitchell <jeffrey.mitchell@starlab.io>\n[Trond: clean up duplicate test of label->len != 0]\nSigned-off-by: Trond Myklebust <trond.myklebust@hammerspace.com>", "target": 1, "dataset": "other", "idx": 210250}
  832. {"func": "static int decode_attr_security_label(struct xdr_stream *xdr, uint32_t *bitmap,\n\t\t\t\t\tstruct nfs4_label *label)\n{\n\tuint32_t pi = 0;\n\tuint32_t lfs = 0;\n\t__u32 len;\n\t__be32 *p;\n\tint status = 0;\n\n\tif (unlikely(bitmap[2] & (FATTR4_WORD2_SECURITY_LABEL - 1U)))\n\t\treturn -EIO;\n\tif (likely(bitmap[2] & FATTR4_WORD2_SECURITY_LABEL)) {\n\t\tp = xdr_inline_decode(xdr, 4);\n\t\tif (unlikely(!p))\n\t\t\treturn -EIO;\n\t\tlfs = be32_to_cpup(p++);\n\t\tp = xdr_inline_decode(xdr, 4);\n\t\tif (unlikely(!p))\n\t\t\treturn -EIO;\n\t\tpi = be32_to_cpup(p++);\n\t\tp = xdr_inline_decode(xdr, 4);\n\t\tif (unlikely(!p))\n\t\t\treturn -EIO;\n\t\tlen = be32_to_cpup(p++);\n\t\tp = xdr_inline_decode(xdr, len);\n\t\tif (unlikely(!p))\n\t\t\treturn -EIO;\n\t\tif (len < NFS4_MAXLABELLEN) {\n\t\t\tif (label) {\n\t\t\t\tif (label->len) {\n\t\t\t\t\tif (label->len < len)\n\t\t\t\t\t\treturn -ERANGE;\n\t\t\t\t\tmemcpy(label->label, p, len);\n\t\t\t\t}\n\t\t\t\tlabel->len = len;\n\t\t\t\tlabel->pi = pi;\n\t\t\t\tlabel->lfs = lfs;\n\t\t\t\tstatus = NFS_ATTR_FATTR_V4_SECURITY_LABEL;\n\t\t\t}\n\t\t\tbitmap[2] &= ~FATTR4_WORD2_SECURITY_LABEL;\n\t\t} else\n\t\t\tprintk(KERN_WARNING \"%s: label too long (%u)!\\n\",\n\t\t\t\t\t__func__, len);\n\t}\n\tif (label && label->label)\n\t\tdprintk(\"%s: label=%s, len=%d, PI=%d, LFS=%d\\n\", __func__,\n\t\t\t(char *)label->label, label->len, label->pi, label->lfs);\n\treturn status;\n}", "project": "linux", "hash": 57059966302914892646918225923262002221, "size": 49, "commit_id": "b4487b93545214a9db8cbf32e86411677b0cca21", "message": "nfs: Fix getxattr kernel panic and memory overflow\n\nMove the buffer size check to decode_attr_security_label() before memcpy()\nOnly call memcpy() if the buffer is large enough\n\nFixes: aa9c2669626c (\"NFS: Client implementation of Labeled-NFS\")\nSigned-off-by: Jeffrey Mitchell <jeffrey.mitchell@starlab.io>\n[Trond: clean up duplicate test of label->len != 0]\nSigned-off-by: Trond Myklebust <trond.myklebust@hammerspace.com>", "target": 0, "dataset": "other", "idx": 431495}
  833. {"func": "static void hci_extended_inquiry_result_evt(struct hci_dev *hdev,\n\t\t\t\t\t struct sk_buff *skb)\n{\n\tstruct inquiry_data data;\n\tstruct extended_inquiry_info *info = (void *) (skb->data + 1);\n\tint num_rsp = *((__u8 *) skb->data);\n\tsize_t eir_len;\n\n\tBT_DBG(\"%s num_rsp %d\", hdev->name, num_rsp);\n\n\tif (!num_rsp)\n\t\treturn;\n\n\tif (hci_dev_test_flag(hdev, HCI_PERIODIC_INQ))\n\t\treturn;\n\n\thci_dev_lock(hdev);\n\n\tfor (; num_rsp; num_rsp--, info++) {\n\t\tu32 flags;\n\t\tbool name_known;\n\n\t\tbacpy(&data.bdaddr, &info->bdaddr);\n\t\tdata.pscan_rep_mode\t= info->pscan_rep_mode;\n\t\tdata.pscan_period_mode\t= info->pscan_period_mode;\n\t\tdata.pscan_mode\t\t= 0x00;\n\t\tmemcpy(data.dev_class, info->dev_class, 3);\n\t\tdata.clock_offset\t= info->clock_offset;\n\t\tdata.rssi\t\t= info->rssi;\n\t\tdata.ssp_mode\t\t= 0x01;\n\n\t\tif (hci_dev_test_flag(hdev, HCI_MGMT))\n\t\t\tname_known = eir_get_data(info->data,\n\t\t\t\t\t\t sizeof(info->data),\n\t\t\t\t\t\t EIR_NAME_COMPLETE, NULL);\n\t\telse\n\t\t\tname_known = true;\n\n\t\tflags = hci_inquiry_cache_update(hdev, &data, name_known);\n\n\t\teir_len = eir_get_length(info->data, sizeof(info->data));\n\n\t\tmgmt_device_found(hdev, &info->bdaddr, ACL_LINK, 0x00,\n\t\t\t\t info->dev_class, info->rssi,\n\t\t\t\t flags, info->data, eir_len, NULL, 0);\n\t}\n\n\thci_dev_unlock(hdev);\n}", "project": "linux", "hash": 246597494627569744149252198466981823503, "size": 49, "commit_id": "51c19bf3d5cfaa66571e4b88ba2a6f6295311101", "message": "Bluetooth: Fix slab-out-of-bounds read in hci_extended_inquiry_result_evt()\n\nCheck upon `num_rsp` is insufficient. A malformed event packet with a\nlarge `num_rsp` number makes hci_extended_inquiry_result_evt() go out\nof bounds. Fix it.\n\nThis patch fixes the following syzbot bug:\n\n https://syzkaller.appspot.com/bug?id=4bf11aa05c4ca51ce0df86e500fce486552dc8d2\n\nReported-by: syzbot+d8489a79b781849b9c46@syzkaller.appspotmail.com\nCc: stable@vger.kernel.org\nSigned-off-by: Peilin Ye <yepeilin.cs@gmail.com>\nAcked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>\nSigned-off-by: Marcel Holtmann <marcel@holtmann.org>", "target": 1, "dataset": "other", "idx": 210268}
  834. {"func": "static void hci_extended_inquiry_result_evt(struct hci_dev *hdev,\n\t\t\t\t\t struct sk_buff *skb)\n{\n\tstruct inquiry_data data;\n\tstruct extended_inquiry_info *info = (void *) (skb->data + 1);\n\tint num_rsp = *((__u8 *) skb->data);\n\tsize_t eir_len;\n\n\tBT_DBG(\"%s num_rsp %d\", hdev->name, num_rsp);\n\n\tif (!num_rsp || skb->len < num_rsp * sizeof(*info) + 1)\n\t\treturn;\n\n\tif (hci_dev_test_flag(hdev, HCI_PERIODIC_INQ))\n\t\treturn;\n\n\thci_dev_lock(hdev);\n\n\tfor (; num_rsp; num_rsp--, info++) {\n\t\tu32 flags;\n\t\tbool name_known;\n\n\t\tbacpy(&data.bdaddr, &info->bdaddr);\n\t\tdata.pscan_rep_mode\t= info->pscan_rep_mode;\n\t\tdata.pscan_period_mode\t= info->pscan_period_mode;\n\t\tdata.pscan_mode\t\t= 0x00;\n\t\tmemcpy(data.dev_class, info->dev_class, 3);\n\t\tdata.clock_offset\t= info->clock_offset;\n\t\tdata.rssi\t\t= info->rssi;\n\t\tdata.ssp_mode\t\t= 0x01;\n\n\t\tif (hci_dev_test_flag(hdev, HCI_MGMT))\n\t\t\tname_known = eir_get_data(info->data,\n\t\t\t\t\t\t sizeof(info->data),\n\t\t\t\t\t\t EIR_NAME_COMPLETE, NULL);\n\t\telse\n\t\t\tname_known = true;\n\n\t\tflags = hci_inquiry_cache_update(hdev, &data, name_known);\n\n\t\teir_len = eir_get_length(info->data, sizeof(info->data));\n\n\t\tmgmt_device_found(hdev, &info->bdaddr, ACL_LINK, 0x00,\n\t\t\t\t info->dev_class, info->rssi,\n\t\t\t\t flags, info->data, eir_len, NULL, 0);\n\t}\n\n\thci_dev_unlock(hdev);\n}", "project": "linux", "hash": 330631060070038770247000748836217689829, "size": 49, "commit_id": "51c19bf3d5cfaa66571e4b88ba2a6f6295311101", "message": "Bluetooth: Fix slab-out-of-bounds read in hci_extended_inquiry_result_evt()\n\nCheck upon `num_rsp` is insufficient. A malformed event packet with a\nlarge `num_rsp` number makes hci_extended_inquiry_result_evt() go out\nof bounds. Fix it.\n\nThis patch fixes the following syzbot bug:\n\n https://syzkaller.appspot.com/bug?id=4bf11aa05c4ca51ce0df86e500fce486552dc8d2\n\nReported-by: syzbot+d8489a79b781849b9c46@syzkaller.appspotmail.com\nCc: stable@vger.kernel.org\nSigned-off-by: Peilin Ye <yepeilin.cs@gmail.com>\nAcked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>\nSigned-off-by: Marcel Holtmann <marcel@holtmann.org>", "target": 0, "dataset": "other", "idx": 431954}
  835. {"func": "static int svm_cpu_init(int cpu)\n{\n\tstruct svm_cpu_data *sd;\n\tint r;\n\n\tsd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);\n\tif (!sd)\n\t\treturn -ENOMEM;\n\tsd->cpu = cpu;\n\tr = -ENOMEM;\n\tsd->save_area = alloc_page(GFP_KERNEL);\n\tif (!sd->save_area)\n\t\tgoto err_1;\n\n\tif (svm_sev_enabled()) {\n\t\tr = -ENOMEM;\n\t\tsd->sev_vmcbs = kmalloc_array(max_sev_asid + 1,\n\t\t\t\t\t sizeof(void *),\n\t\t\t\t\t GFP_KERNEL);\n\t\tif (!sd->sev_vmcbs)\n\t\t\tgoto err_1;\n\t}\n\n\tper_cpu(svm_data, cpu) = sd;\n\n\treturn 0;\n\nerr_1:\n\tkfree(sd);\n\treturn r;\n\n}", "project": "linux", "hash": 19969613992103226668284025200331411815, "size": 32, "commit_id": "d80b64ff297e40c2b6f7d7abc1b3eba70d22a068", "message": "KVM: SVM: Fix potential memory leak in svm_cpu_init()\n\nWhen kmalloc memory for sd->sev_vmcbs failed, we forget to free the page\nheld by sd->save_area. Also get rid of the var r as '-ENOMEM' is actually\nthe only possible outcome here.\n\nReviewed-by: Liran Alon <liran.alon@oracle.com>\nReviewed-by: Vitaly Kuznetsov <vkuznets@redhat.com>\nSigned-off-by: Miaohe Lin <linmiaohe@huawei.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 1, "dataset": "other", "idx": 210296}
  836. {"func": "static int svm_cpu_init(int cpu)\n{\n\tstruct svm_cpu_data *sd;\n\n\tsd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);\n\tif (!sd)\n\t\treturn -ENOMEM;\n\tsd->cpu = cpu;\n\tsd->save_area = alloc_page(GFP_KERNEL);\n\tif (!sd->save_area)\n\t\tgoto free_cpu_data;\n\n\tif (svm_sev_enabled()) {\n\t\tsd->sev_vmcbs = kmalloc_array(max_sev_asid + 1,\n\t\t\t\t\t sizeof(void *),\n\t\t\t\t\t GFP_KERNEL);\n\t\tif (!sd->sev_vmcbs)\n\t\t\tgoto free_save_area;\n\t}\n\n\tper_cpu(svm_data, cpu) = sd;\n\n\treturn 0;\n\nfree_save_area:\n\t__free_page(sd->save_area);\nfree_cpu_data:\n\tkfree(sd);\n\treturn -ENOMEM;\n\n}", "project": "linux", "hash": 183067082748724995934254062159834476787, "size": 31, "commit_id": "d80b64ff297e40c2b6f7d7abc1b3eba70d22a068", "message": "KVM: SVM: Fix potential memory leak in svm_cpu_init()\n\nWhen kmalloc memory for sd->sev_vmcbs failed, we forget to free the page\nheld by sd->save_area. Also get rid of the var r as '-ENOMEM' is actually\nthe only possible outcome here.\n\nReviewed-by: Liran Alon <liran.alon@oracle.com>\nReviewed-by: Vitaly Kuznetsov <vkuznets@redhat.com>\nSigned-off-by: Miaohe Lin <linmiaohe@huawei.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 0, "dataset": "other", "idx": 432423}
  837. {"func": "BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)\n{\n\trdpGlyph* prevGlyph;\n\n\tif (id > 9)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache id: %\" PRIu32 \"\", id);\n\t\treturn FALSE;\n\t}\n\n\tif (index > glyphCache->glyphCache[id].number)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache index: %\" PRIu32 \" in cache id: %\" PRIu32 \"\", index, id);\n\t\treturn FALSE;\n\t}\n\n\tWLog_Print(glyphCache->log, WLOG_DEBUG, \"GlyphCachePut: id: %\" PRIu32 \" index: %\" PRIu32 \"\", id,\n\t index);\n\tprevGlyph = glyphCache->glyphCache[id].entries[index];\n\n\tif (prevGlyph)\n\t\tprevGlyph->Free(glyphCache->context, prevGlyph);\n\n\tglyphCache->glyphCache[id].entries[index] = glyph;\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 73282285903996096925940375434935798209, "size": 26, "commit_id": "c0fd449ec0870b050d350d6d844b1ea6dad4bc7d", "message": "Fixed Out-of-bound read in glyph_cache_put\n\nCVE-2020-11098 thanks to @antonio-morales for finding this.", "target": 1, "dataset": "other", "idx": 210325}
  838. {"func": "BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)\n{\n\trdpGlyph* prevGlyph;\n\n\tif (id > 9)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache id: %\" PRIu32 \"\", id);\n\t\treturn FALSE;\n\t}\n\n\tif (index >= glyphCache->glyphCache[id].number)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache index: %\" PRIu32 \" in cache id: %\" PRIu32 \"\", index, id);\n\t\treturn FALSE;\n\t}\n\n\tWLog_Print(glyphCache->log, WLOG_DEBUG, \"GlyphCachePut: id: %\" PRIu32 \" index: %\" PRIu32 \"\", id,\n\t index);\n\tprevGlyph = glyphCache->glyphCache[id].entries[index];\n\n\tif (prevGlyph)\n\t\tprevGlyph->Free(glyphCache->context, prevGlyph);\n\n\tglyphCache->glyphCache[id].entries[index] = glyph;\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 206456276622603553888667254120967264481, "size": 26, "commit_id": "c0fd449ec0870b050d350d6d844b1ea6dad4bc7d", "message": "Fixed Out-of-bound read in glyph_cache_put\n\nCVE-2020-11098 thanks to @antonio-morales for finding this.", "target": 0, "dataset": "other", "idx": 432859}
  839. {"func": "static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,\n AUTODETECT_RSP_PDU* autodetectRspPdu)\n{\n\tBOOL success = TRUE;\n\n\tif (autodetectRspPdu->headerLength != 0x0E)\n\t\treturn FALSE;\n\n\tWLog_VRB(AUTODETECT_TAG, \"received Bandwidth Measure Results PDU\");\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */\n\n\tif (rdp->autodetect->bandwidthMeasureTimeDelta > 0)\n\t\trdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /\n\t\t rdp->autodetect->bandwidthMeasureTimeDelta;\n\telse\n\t\trdp->autodetect->netCharBandwidth = 0;\n\n\tIFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,\n\t autodetectRspPdu->sequenceNumber);\n\treturn success;\n}", "project": "FreeRDP", "hash": 216691492795313936043673492828130509835, "size": 22, "commit_id": "f5e73cc7c9cd973b516a618da877c87b80950b65", "message": "Fixed #6009: Bounds checks in autodetect_recv_bandwidth_measure_results", "target": 1, "dataset": "other", "idx": 210399}
  840. {"func": "static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,\n AUTODETECT_RSP_PDU* autodetectRspPdu)\n{\n\tBOOL success = TRUE;\n\n\tif (autodetectRspPdu->headerLength != 0x0E)\n\t\treturn FALSE;\n\n\tWLog_VRB(AUTODETECT_TAG, \"received Bandwidth Measure Results PDU\");\n\tif (Stream_GetRemainingLength(s) < 8)\n\t\treturn -1;\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */\n\n\tif (rdp->autodetect->bandwidthMeasureTimeDelta > 0)\n\t\trdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /\n\t\t rdp->autodetect->bandwidthMeasureTimeDelta;\n\telse\n\t\trdp->autodetect->netCharBandwidth = 0;\n\n\tIFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,\n\t autodetectRspPdu->sequenceNumber);\n\treturn success;\n}", "project": "FreeRDP", "hash": 251258706899851186161828557200980478981, "size": 24, "commit_id": "f5e73cc7c9cd973b516a618da877c87b80950b65", "message": "Fixed #6009: Bounds checks in autodetect_recv_bandwidth_measure_results", "target": 0, "dataset": "other", "idx": 434145}
  841. {"func": "static PCRE2_SPTR SLJIT_FUNC do_extuni_no_utf(jit_arguments *args, PCRE2_SPTR cc)\n{\nPCRE2_SPTR start_subject = args->begin;\nPCRE2_SPTR end_subject = args->end;\nint lgb, rgb, ricount;\nPCRE2_SPTR bptr;\nuint32_t c;\n\nGETCHARINC(c, cc);\nlgb = UCD_GRAPHBREAK(c);\n\nwhile (cc < end_subject)\n {\n c = *cc;\n rgb = UCD_GRAPHBREAK(c);\n\n if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;\n\n /* Not breaking between Regional Indicators is allowed only if there\n are an even number of preceding RIs. */\n\n if (lgb == ucp_gbRegionalIndicator && rgb == ucp_gbRegionalIndicator)\n {\n ricount = 0;\n bptr = cc - 1;\n\n /* bptr is pointing to the left-hand character */\n while (bptr > start_subject)\n {\n bptr--;\n c = *bptr;\n\n if (UCD_GRAPHBREAK(c) != ucp_gbRegionalIndicator) break;\n\n ricount++;\n }\n\n if ((ricount & 1) != 0) break; /* Grapheme break required */\n }\n\n /* If Extend or ZWJ follows Extended_Pictographic, do not update lgb; this\n allows any number of them before a following Extended_Pictographic. */\n\n if ((rgb != ucp_gbExtend && rgb != ucp_gbZWJ) ||\n lgb != ucp_gbExtended_Pictographic)\n lgb = rgb;\n\n cc++;\n }\n\nreturn cc;\n}", "project": "php-src", "hash": 23685102313507176772328800273051474560, "size": 52, "commit_id": "8947fd9e9fdce87cd6c59817b1db58e789538fe9", "message": "Fix #78338: Array cross-border reading in PCRE\n\nWe backport r1092 from pcre2.", "target": 1, "dataset": "other", "idx": 210402}
  842. {"func": "static PCRE2_SPTR SLJIT_FUNC do_extuni_no_utf(jit_arguments *args, PCRE2_SPTR cc)\n{\nPCRE2_SPTR start_subject = args->begin;\nPCRE2_SPTR end_subject = args->end;\nint lgb, rgb, ricount;\nPCRE2_SPTR bptr;\nuint32_t c;\n\nc = *cc++;\nlgb = UCD_GRAPHBREAK(c);\n\nwhile (cc < end_subject)\n {\n c = *cc;\n rgb = UCD_GRAPHBREAK(c);\n\n if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;\n\n /* Not breaking between Regional Indicators is allowed only if there\n are an even number of preceding RIs. */\n\n if (lgb == ucp_gbRegionalIndicator && rgb == ucp_gbRegionalIndicator)\n {\n ricount = 0;\n bptr = cc - 1;\n\n /* bptr is pointing to the left-hand character */\n while (bptr > start_subject)\n {\n bptr--;\n c = *bptr;\n\n if (UCD_GRAPHBREAK(c) != ucp_gbRegionalIndicator) break;\n\n ricount++;\n }\n\n if ((ricount & 1) != 0) break; /* Grapheme break required */\n }\n\n /* If Extend or ZWJ follows Extended_Pictographic, do not update lgb; this\n allows any number of them before a following Extended_Pictographic. */\n\n if ((rgb != ucp_gbExtend && rgb != ucp_gbZWJ) ||\n lgb != ucp_gbExtended_Pictographic)\n lgb = rgb;\n\n cc++;\n }\n\nreturn cc;\n}", "project": "php-src", "hash": 53992940305778057865824736494755359235, "size": 52, "commit_id": "8947fd9e9fdce87cd6c59817b1db58e789538fe9", "message": "Fix #78338: Array cross-border reading in PCRE\n\nWe backport r1092 from pcre2.", "target": 0, "dataset": "other", "idx": 434186}
  843. {"func": "static Image *ReadVIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define VFF_CM_genericRGB 15\n#define VFF_CM_ntscRGB 1\n#define VFF_CM_NONE 0\n#define VFF_DEP_DECORDER 0x4\n#define VFF_DEP_NSORDER 0x8\n#define VFF_DES_RAW 0\n#define VFF_LOC_IMPLICIT 1\n#define VFF_MAPTYP_NONE 0\n#define VFF_MAPTYP_1_BYTE 1\n#define VFF_MAPTYP_2_BYTE 2\n#define VFF_MAPTYP_4_BYTE 4\n#define VFF_MAPTYP_FLOAT 5\n#define VFF_MAPTYP_DOUBLE 7\n#define VFF_MS_NONE 0\n#define VFF_MS_ONEPERBAND 1\n#define VFF_MS_SHARED 3\n#define VFF_TYP_BIT 0\n#define VFF_TYP_1_BYTE 1\n#define VFF_TYP_2_BYTE 2\n#define VFF_TYP_4_BYTE 4\n#define VFF_TYP_FLOAT 5\n#define VFF_TYP_DOUBLE 9\n\n typedef struct _ViffInfo\n {\n unsigned char\n identifier,\n file_type,\n release,\n version,\n machine_dependency,\n reserve[3];\n\n char\n comment[512];\n\n unsigned int\n rows,\n columns,\n subrows;\n\n int\n x_offset,\n y_offset;\n\n float\n x_bits_per_pixel,\n y_bits_per_pixel;\n\n unsigned int\n location_type,\n location_dimension,\n number_of_images,\n number_data_bands,\n data_storage_type,\n data_encode_scheme,\n map_scheme,\n map_storage_type,\n map_rows,\n map_columns,\n map_subrows,\n map_enable,\n maps_per_cycle,\n color_space_model;\n } ViffInfo;\n\n double\n min_value,\n scale_factor,\n value;\n\n Image\n *image;\n\n int\n bit;\n\n MagickBooleanType\n status;\n\n MagickSizeType\n number_pixels;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n x;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i;\n\n register unsigned char\n *p;\n\n size_t\n bytes_per_pixel,\n max_packets,\n quantum;\n\n ssize_t\n count,\n y;\n\n unsigned char\n *pixels;\n\n unsigned long\n lsb_first;\n\n ViffInfo\n viff_info;\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 {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read VIFF header (1024 bytes).\n */\n count=ReadBlob(image,1,&viff_info.identifier);\n do\n {\n /*\n Verify VIFF identifier.\n */\n if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))\n ThrowReaderException(CorruptImageError,\"NotAVIFFImage\");\n /*\n Initialize VIFF image.\n */\n (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);\n (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);\n (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);\n (void) ReadBlob(image,sizeof(viff_info.machine_dependency),\n &viff_info.machine_dependency);\n (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);\n count=ReadBlob(image,512,(unsigned char *) viff_info.comment);\n if (count != 512)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n viff_info.comment[511]='\\0';\n if (strlen(viff_info.comment) > 4)\n (void) SetImageProperty(image,\"comment\",viff_info.comment);\n if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||\n (viff_info.machine_dependency == VFF_DEP_NSORDER))\n image->endian=LSBEndian;\n else\n image->endian=MSBEndian;\n viff_info.rows=ReadBlobLong(image);\n viff_info.columns=ReadBlobLong(image);\n viff_info.subrows=ReadBlobLong(image);\n viff_info.x_offset=ReadBlobSignedLong(image);\n viff_info.y_offset=ReadBlobSignedLong(image);\n viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);\n viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);\n viff_info.location_type=ReadBlobLong(image);\n viff_info.location_dimension=ReadBlobLong(image);\n viff_info.number_of_images=ReadBlobLong(image);\n viff_info.number_data_bands=ReadBlobLong(image);\n viff_info.data_storage_type=ReadBlobLong(image);\n viff_info.data_encode_scheme=ReadBlobLong(image);\n viff_info.map_scheme=ReadBlobLong(image);\n viff_info.map_storage_type=ReadBlobLong(image);\n viff_info.map_rows=ReadBlobLong(image);\n viff_info.map_columns=ReadBlobLong(image);\n viff_info.map_subrows=ReadBlobLong(image);\n viff_info.map_enable=ReadBlobLong(image);\n viff_info.maps_per_cycle=ReadBlobLong(image);\n viff_info.color_space_model=ReadBlobLong(image);\n for (i=0; i < 420; i++)\n (void) ReadBlobByte(image);\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n image->columns=viff_info.rows;\n image->rows=viff_info.columns;\n image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :\n MAGICKCORE_QUANTUM_DEPTH;\n image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n (void) SetImageBackgroundColor(image);\n /*\n Verify that we can read this VIFF image.\n */\n number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;\n if (number_pixels != (size_t) number_pixels)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (number_pixels == 0)\n ThrowReaderException(CoderError,\"ImageColumnOrRowSizeIsNotSupported\");\n if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((viff_info.data_storage_type != VFF_TYP_BIT) &&\n (viff_info.data_storage_type != VFF_TYP_1_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_2_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_4_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_FLOAT) &&\n (viff_info.data_storage_type != VFF_TYP_DOUBLE))\n ThrowReaderException(CoderError,\"DataStorageTypeIsNotSupported\");\n if (viff_info.data_encode_scheme != VFF_DES_RAW)\n ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\");\n if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&\n (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))\n ThrowReaderException(CoderError,\"MapStorageTypeIsNotSupported\");\n if ((viff_info.color_space_model != VFF_CM_NONE) &&\n (viff_info.color_space_model != VFF_CM_ntscRGB) &&\n (viff_info.color_space_model != VFF_CM_genericRGB))\n ThrowReaderException(CoderError,\"ColorspaceModelIsNotSupported\");\n if (viff_info.location_type != VFF_LOC_IMPLICIT)\n ThrowReaderException(CoderError,\"LocationTypeIsNotSupported\");\n if (viff_info.number_of_images != 1)\n ThrowReaderException(CoderError,\"NumberOfImagesIsNotSupported\");\n if (viff_info.map_rows == 0)\n viff_info.map_scheme=VFF_MS_NONE;\n switch ((int) viff_info.map_scheme)\n {\n case VFF_MS_NONE:\n {\n if (viff_info.number_data_bands < 3)\n {\n /*\n Create linear color ramp.\n */\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n image->colors=2;\n else\n if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)\n image->colors=256UL;\n else\n image->colors=image->depth <= 8 ? 256UL : 65536UL;\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n break;\n }\n case VFF_MS_ONEPERBAND:\n case VFF_MS_SHARED:\n {\n unsigned char\n *viff_colormap;\n\n /*\n Allocate VIFF colormap.\n */\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;\n case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;\n case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;\n case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;\n case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;\n default: bytes_per_pixel=1; break;\n }\n image->colors=viff_info.map_columns;\n if ((MagickSizeType) (viff_info.map_rows*image->colors) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((MagickSizeType) viff_info.map_rows > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if ((MagickSizeType) viff_info.map_rows >\n (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));\n if (viff_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Read VIFF raster colormap.\n */\n (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,\n viff_colormap);\n lsb_first=1;\n if (*(char *) &lsb_first &&\n ((viff_info.machine_dependency != VFF_DEP_DECORDER) &&\n (viff_info.machine_dependency != VFF_DEP_NSORDER)))\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_2_BYTE:\n {\n MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*\n viff_info.map_rows));\n break;\n }\n case VFF_MAPTYP_4_BYTE:\n case VFF_MAPTYP_FLOAT:\n {\n MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*\n viff_info.map_rows));\n break;\n }\n default: break;\n }\n for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)\n {\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;\n case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;\n case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;\n case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;\n default: value=1.0*viff_colormap[i]; break;\n }\n if (i < (ssize_t) image->colors)\n {\n image->colormap[i].red=ScaleCharToQuantum((unsigned char) value);\n image->colormap[i].green=ScaleCharToQuantum((unsigned char)\n value);\n image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value);\n }\n else\n if (i < (ssize_t) (2*image->colors))\n image->colormap[i % image->colors].green=ScaleCharToQuantum(\n (unsigned char) value);\n else\n if (i < (ssize_t) (3*image->colors))\n image->colormap[i % image->colors].blue=ScaleCharToQuantum(\n (unsigned char) value);\n }\n viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);\n break;\n }\n default:\n ThrowReaderException(CoderError,\"ColormapTypeNotSupported\");\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n /*\n Create bi-level colormap.\n */\n image->colors=2;\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n image->colorspace=GRAYColorspace;\n }\n /*\n Allocate VIFF pixels.\n */\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;\n case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;\n case VFF_TYP_FLOAT: bytes_per_pixel=4; break;\n case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;\n default: bytes_per_pixel=1; break;\n }\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n if (HeapOverflowSanityCheck((image->columns+7UL) >> 3UL,image->rows) != MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n max_packets=((image->columns+7UL) >> 3UL)*image->rows;\n }\n else\n {\n if (HeapOverflowSanityCheck((size_t) number_pixels,viff_info.number_data_bands) != MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n max_packets=(size_t) (number_pixels*viff_info.number_data_bands);\n }\n if ((MagickSizeType) (bytes_per_pixel*max_packets) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n pixels=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(\n number_pixels,max_packets),bytes_per_pixel*sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(pixels,0,MagickMax(number_pixels,max_packets)*\n bytes_per_pixel*sizeof(*pixels));\n (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels);\n lsb_first=1;\n if (*(char *) &lsb_first &&\n ((viff_info.machine_dependency != VFF_DEP_DECORDER) &&\n (viff_info.machine_dependency != VFF_DEP_NSORDER)))\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE:\n {\n MSBOrderShort(pixels,bytes_per_pixel*max_packets);\n break;\n }\n case VFF_TYP_4_BYTE:\n case VFF_TYP_FLOAT:\n {\n MSBOrderLong(pixels,bytes_per_pixel*max_packets);\n break;\n }\n default: break;\n }\n min_value=0.0;\n scale_factor=1.0;\n if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&\n (viff_info.map_scheme == VFF_MS_NONE))\n {\n double\n max_value;\n\n /*\n Determine scale factor.\n */\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;\n default: value=1.0*pixels[0]; break;\n }\n max_value=value;\n min_value=value;\n for (i=0; i < (ssize_t) max_packets; i++)\n {\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;\n default: value=1.0*pixels[i]; break;\n }\n if (value > max_value)\n max_value=value;\n else\n if (value < min_value)\n min_value=value;\n }\n if ((min_value == 0) && (max_value == 0))\n scale_factor=0;\n else\n if (min_value == max_value)\n {\n scale_factor=(MagickRealType) QuantumRange/min_value;\n min_value=0;\n }\n else\n scale_factor=(MagickRealType) QuantumRange/(max_value-min_value);\n }\n /*\n Convert pixels to Quantum size.\n */\n p=(unsigned char *) pixels;\n for (i=0; i < (ssize_t) max_packets; i++)\n {\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;\n default: value=1.0*pixels[i]; break;\n }\n if (viff_info.map_scheme == VFF_MS_NONE)\n {\n value=(value-min_value)*scale_factor;\n if (value > QuantumRange)\n value=QuantumRange;\n else\n if (value < 0)\n value=0;\n }\n *p=(unsigned char) ((Quantum) value);\n p++;\n }\n /*\n Convert VIFF raster image to pixel packets.\n */\n p=(unsigned char *) pixels;\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n /*\n Convert bitmap scanline.\n */\n if (image->storage_class != PseudoClass)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\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-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);\n SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);\n SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);\n SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(indexes+x+bit,quantum);\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (int) (image->columns % 8); bit++)\n {\n quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);\n SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);\n SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);\n SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(indexes+x+bit,quantum);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n if (image->storage_class == PseudoClass)\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,*p++);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n else\n {\n /*\n Convert DirectColor scanline.\n */\n number_pixels=(MagickSizeType) image->columns*image->rows;\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 SetPixelRed(q,ScaleCharToQuantum(*p));\n SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels)));\n SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels)));\n if (image->colors != 0)\n {\n ssize_t\n index;\n\n index=(ssize_t) GetPixelRed(q);\n SetPixelRed(q,image->colormap[(ssize_t)\n ConstrainColormapIndex(image,(ssize_t) index)].red);\n index=(ssize_t) GetPixelGreen(q);\n SetPixelGreen(q,image->colormap[(ssize_t)\n ConstrainColormapIndex(image,(ssize_t) index)].green);\n index=(ssize_t) GetPixelRed(q);\n SetPixelBlue(q,image->colormap[(ssize_t)\n ConstrainColormapIndex(image,(ssize_t) index)].blue);\n }\n SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange-\n ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity);\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n count=ReadBlob(image,1,&viff_info.identifier);\n if ((count == 1) && (viff_info.identifier == 0xab))\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while ((count != 0) && (viff_info.identifier == 0xab));\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick6", "hash": 69229050309440507101939339857355577375, "size": 649, "commit_id": "d5e7c2b5ba384e7d0d8ddac6c9ae2319cb74b9c5", "message": "https://github.com/ImageMagick/ImageMagick/issues/1286", "target": 1, "dataset": "other", "idx": 210554}
  844. {"func": "static Image *ReadVIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define VFF_CM_genericRGB 15\n#define VFF_CM_ntscRGB 1\n#define VFF_CM_NONE 0\n#define VFF_DEP_DECORDER 0x4\n#define VFF_DEP_NSORDER 0x8\n#define VFF_DES_RAW 0\n#define VFF_LOC_IMPLICIT 1\n#define VFF_MAPTYP_NONE 0\n#define VFF_MAPTYP_1_BYTE 1\n#define VFF_MAPTYP_2_BYTE 2\n#define VFF_MAPTYP_4_BYTE 4\n#define VFF_MAPTYP_FLOAT 5\n#define VFF_MAPTYP_DOUBLE 7\n#define VFF_MS_NONE 0\n#define VFF_MS_ONEPERBAND 1\n#define VFF_MS_SHARED 3\n#define VFF_TYP_BIT 0\n#define VFF_TYP_1_BYTE 1\n#define VFF_TYP_2_BYTE 2\n#define VFF_TYP_4_BYTE 4\n#define VFF_TYP_FLOAT 5\n#define VFF_TYP_DOUBLE 9\n\n typedef struct _ViffInfo\n {\n unsigned char\n identifier,\n file_type,\n release,\n version,\n machine_dependency,\n reserve[3];\n\n char\n comment[512];\n\n unsigned int\n rows,\n columns,\n subrows;\n\n int\n x_offset,\n y_offset;\n\n float\n x_bits_per_pixel,\n y_bits_per_pixel;\n\n unsigned int\n location_type,\n location_dimension,\n number_of_images,\n number_data_bands,\n data_storage_type,\n data_encode_scheme,\n map_scheme,\n map_storage_type,\n map_rows,\n map_columns,\n map_subrows,\n map_enable,\n maps_per_cycle,\n color_space_model;\n } ViffInfo;\n\n double\n min_value,\n scale_factor,\n value;\n\n Image\n *image;\n\n int\n bit;\n\n MagickBooleanType\n status;\n\n MagickSizeType\n number_pixels;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n x;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i;\n\n register unsigned char\n *p;\n\n size_t\n bytes_per_pixel,\n max_packets,\n quantum;\n\n ssize_t\n count,\n y;\n\n unsigned char\n *pixels;\n\n unsigned long\n lsb_first;\n\n ViffInfo\n viff_info;\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 {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read VIFF header (1024 bytes).\n */\n count=ReadBlob(image,1,&viff_info.identifier);\n do\n {\n /*\n Verify VIFF identifier.\n */\n if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))\n ThrowReaderException(CorruptImageError,\"NotAVIFFImage\");\n /*\n Initialize VIFF image.\n */\n (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);\n (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);\n (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);\n (void) ReadBlob(image,sizeof(viff_info.machine_dependency),\n &viff_info.machine_dependency);\n (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);\n count=ReadBlob(image,512,(unsigned char *) viff_info.comment);\n if (count != 512)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n viff_info.comment[511]='\\0';\n if (strlen(viff_info.comment) > 4)\n (void) SetImageProperty(image,\"comment\",viff_info.comment);\n if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||\n (viff_info.machine_dependency == VFF_DEP_NSORDER))\n image->endian=LSBEndian;\n else\n image->endian=MSBEndian;\n viff_info.rows=ReadBlobLong(image);\n viff_info.columns=ReadBlobLong(image);\n viff_info.subrows=ReadBlobLong(image);\n viff_info.x_offset=ReadBlobSignedLong(image);\n viff_info.y_offset=ReadBlobSignedLong(image);\n viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);\n viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);\n viff_info.location_type=ReadBlobLong(image);\n viff_info.location_dimension=ReadBlobLong(image);\n viff_info.number_of_images=ReadBlobLong(image);\n viff_info.number_data_bands=ReadBlobLong(image);\n viff_info.data_storage_type=ReadBlobLong(image);\n viff_info.data_encode_scheme=ReadBlobLong(image);\n viff_info.map_scheme=ReadBlobLong(image);\n viff_info.map_storage_type=ReadBlobLong(image);\n viff_info.map_rows=ReadBlobLong(image);\n viff_info.map_columns=ReadBlobLong(image);\n viff_info.map_subrows=ReadBlobLong(image);\n viff_info.map_enable=ReadBlobLong(image);\n viff_info.maps_per_cycle=ReadBlobLong(image);\n viff_info.color_space_model=ReadBlobLong(image);\n for (i=0; i < 420; i++)\n (void) ReadBlobByte(image);\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;\n if (number_pixels != (size_t) number_pixels)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (number_pixels > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if (number_pixels == 0)\n ThrowReaderException(CoderError,\"ImageColumnOrRowSizeIsNotSupported\");\n image->columns=viff_info.rows;\n image->rows=viff_info.columns;\n image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :\n MAGICKCORE_QUANTUM_DEPTH;\n image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n (void) SetImageBackgroundColor(image);\n /*\n Verify that we can read this VIFF image.\n */\n if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((viff_info.data_storage_type != VFF_TYP_BIT) &&\n (viff_info.data_storage_type != VFF_TYP_1_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_2_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_4_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_FLOAT) &&\n (viff_info.data_storage_type != VFF_TYP_DOUBLE))\n ThrowReaderException(CoderError,\"DataStorageTypeIsNotSupported\");\n if (viff_info.data_encode_scheme != VFF_DES_RAW)\n ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\");\n if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&\n (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))\n ThrowReaderException(CoderError,\"MapStorageTypeIsNotSupported\");\n if ((viff_info.color_space_model != VFF_CM_NONE) &&\n (viff_info.color_space_model != VFF_CM_ntscRGB) &&\n (viff_info.color_space_model != VFF_CM_genericRGB))\n ThrowReaderException(CoderError,\"ColorspaceModelIsNotSupported\");\n if (viff_info.location_type != VFF_LOC_IMPLICIT)\n ThrowReaderException(CoderError,\"LocationTypeIsNotSupported\");\n if (viff_info.number_of_images != 1)\n ThrowReaderException(CoderError,\"NumberOfImagesIsNotSupported\");\n if (viff_info.map_rows == 0)\n viff_info.map_scheme=VFF_MS_NONE;\n switch ((int) viff_info.map_scheme)\n {\n case VFF_MS_NONE:\n {\n if (viff_info.number_data_bands < 3)\n {\n /*\n Create linear color ramp.\n */\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n image->colors=2;\n else\n if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)\n image->colors=256UL;\n else\n image->colors=image->depth <= 8 ? 256UL : 65536UL;\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n break;\n }\n case VFF_MS_ONEPERBAND:\n case VFF_MS_SHARED:\n {\n unsigned char\n *viff_colormap;\n\n /*\n Allocate VIFF colormap.\n */\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;\n case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;\n case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;\n case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;\n case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;\n default: bytes_per_pixel=1; break;\n }\n image->colors=viff_info.map_columns;\n if ((MagickSizeType) (viff_info.map_rows*image->colors) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((MagickSizeType) viff_info.map_rows > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if ((MagickSizeType) viff_info.map_rows >\n (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));\n if (viff_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Read VIFF raster colormap.\n */\n (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,\n viff_colormap);\n lsb_first=1;\n if (*(char *) &lsb_first &&\n ((viff_info.machine_dependency != VFF_DEP_DECORDER) &&\n (viff_info.machine_dependency != VFF_DEP_NSORDER)))\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_2_BYTE:\n {\n MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*\n viff_info.map_rows));\n break;\n }\n case VFF_MAPTYP_4_BYTE:\n case VFF_MAPTYP_FLOAT:\n {\n MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*\n viff_info.map_rows));\n break;\n }\n default: break;\n }\n for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)\n {\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;\n case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;\n case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;\n case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;\n default: value=1.0*viff_colormap[i]; break;\n }\n if (i < (ssize_t) image->colors)\n {\n image->colormap[i].red=ScaleCharToQuantum((unsigned char) value);\n image->colormap[i].green=ScaleCharToQuantum((unsigned char)\n value);\n image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value);\n }\n else\n if (i < (ssize_t) (2*image->colors))\n image->colormap[i % image->colors].green=ScaleCharToQuantum(\n (unsigned char) value);\n else\n if (i < (ssize_t) (3*image->colors))\n image->colormap[i % image->colors].blue=ScaleCharToQuantum(\n (unsigned char) value);\n }\n viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);\n break;\n }\n default:\n ThrowReaderException(CoderError,\"ColormapTypeNotSupported\");\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n /*\n Create bi-level colormap.\n */\n image->colors=2;\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n image->colorspace=GRAYColorspace;\n }\n /*\n Allocate VIFF pixels.\n */\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;\n case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;\n case VFF_TYP_FLOAT: bytes_per_pixel=4; break;\n case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;\n default: bytes_per_pixel=1; break;\n }\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n if (HeapOverflowSanityCheck((image->columns+7UL) >> 3UL,image->rows) != MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n max_packets=((image->columns+7UL) >> 3UL)*image->rows;\n }\n else\n {\n if (HeapOverflowSanityCheck((size_t) number_pixels,viff_info.number_data_bands) != MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n max_packets=(size_t) (number_pixels*viff_info.number_data_bands);\n }\n if ((MagickSizeType) (bytes_per_pixel*max_packets) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n pixels=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(\n number_pixels,max_packets),bytes_per_pixel*sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(pixels,0,MagickMax(number_pixels,max_packets)*\n bytes_per_pixel*sizeof(*pixels));\n (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels);\n lsb_first=1;\n if (*(char *) &lsb_first &&\n ((viff_info.machine_dependency != VFF_DEP_DECORDER) &&\n (viff_info.machine_dependency != VFF_DEP_NSORDER)))\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE:\n {\n MSBOrderShort(pixels,bytes_per_pixel*max_packets);\n break;\n }\n case VFF_TYP_4_BYTE:\n case VFF_TYP_FLOAT:\n {\n MSBOrderLong(pixels,bytes_per_pixel*max_packets);\n break;\n }\n default: break;\n }\n min_value=0.0;\n scale_factor=1.0;\n if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&\n (viff_info.map_scheme == VFF_MS_NONE))\n {\n double\n max_value;\n\n /*\n Determine scale factor.\n */\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;\n default: value=1.0*pixels[0]; break;\n }\n max_value=value;\n min_value=value;\n for (i=0; i < (ssize_t) max_packets; i++)\n {\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;\n default: value=1.0*pixels[i]; break;\n }\n if (value > max_value)\n max_value=value;\n else\n if (value < min_value)\n min_value=value;\n }\n if ((min_value == 0) && (max_value == 0))\n scale_factor=0;\n else\n if (min_value == max_value)\n {\n scale_factor=(MagickRealType) QuantumRange/min_value;\n min_value=0;\n }\n else\n scale_factor=(MagickRealType) QuantumRange/(max_value-min_value);\n }\n /*\n Convert pixels to Quantum size.\n */\n p=(unsigned char *) pixels;\n for (i=0; i < (ssize_t) max_packets; i++)\n {\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;\n default: value=1.0*pixels[i]; break;\n }\n if (viff_info.map_scheme == VFF_MS_NONE)\n {\n value=(value-min_value)*scale_factor;\n if (value > QuantumRange)\n value=QuantumRange;\n else\n if (value < 0)\n value=0;\n }\n *p=(unsigned char) ((Quantum) value);\n p++;\n }\n /*\n Convert VIFF raster image to pixel packets.\n */\n p=(unsigned char *) pixels;\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n /*\n Convert bitmap scanline.\n */\n if (image->storage_class != PseudoClass)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\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-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);\n SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);\n SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);\n SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(indexes+x+bit,quantum);\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (int) (image->columns % 8); bit++)\n {\n quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);\n SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);\n SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);\n SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(indexes+x+bit,quantum);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n if (image->storage_class == PseudoClass)\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,*p++);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n else\n {\n /*\n Convert DirectColor scanline.\n */\n number_pixels=(MagickSizeType) image->columns*image->rows;\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 SetPixelRed(q,ScaleCharToQuantum(*p));\n SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels)));\n SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels)));\n if (image->colors != 0)\n {\n ssize_t\n index;\n\n index=(ssize_t) GetPixelRed(q);\n SetPixelRed(q,image->colormap[(ssize_t)\n ConstrainColormapIndex(image,(ssize_t) index)].red);\n index=(ssize_t) GetPixelGreen(q);\n SetPixelGreen(q,image->colormap[(ssize_t)\n ConstrainColormapIndex(image,(ssize_t) index)].green);\n index=(ssize_t) GetPixelRed(q);\n SetPixelBlue(q,image->colormap[(ssize_t)\n ConstrainColormapIndex(image,(ssize_t) index)].blue);\n }\n SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange-\n ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity);\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n count=ReadBlob(image,1,&viff_info.identifier);\n if ((count == 1) && (viff_info.identifier == 0xab))\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while ((count != 0) && (viff_info.identifier == 0xab));\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick6", "hash": 228274360687575937756915751337592850337, "size": 651, "commit_id": "d5e7c2b5ba384e7d0d8ddac6c9ae2319cb74b9c5", "message": "https://github.com/ImageMagick/ImageMagick/issues/1286", "target": 0, "dataset": "other", "idx": 437401}
  845. {"func": "MagickExport Image *AcquireImage(const ImageInfo *image_info)\n{\n const char\n *option;\n\n Image\n *image;\n\n MagickStatusType\n flags;\n\n /*\n Allocate image structure.\n */\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n image=(Image *) AcquireCriticalMemory(sizeof(*image));\n (void) memset(image,0,sizeof(*image));\n /*\n Initialize Image structure.\n */\n (void) CopyMagickString(image->magick,\"MIFF\",MaxTextExtent);\n image->storage_class=DirectClass;\n image->depth=MAGICKCORE_QUANTUM_DEPTH;\n image->colorspace=sRGBColorspace;\n image->rendering_intent=PerceptualIntent;\n image->gamma=1.000f/2.200f;\n image->chromaticity.red_primary.x=0.6400f;\n image->chromaticity.red_primary.y=0.3300f;\n image->chromaticity.red_primary.z=0.0300f;\n image->chromaticity.green_primary.x=0.3000f;\n image->chromaticity.green_primary.y=0.6000f;\n image->chromaticity.green_primary.z=0.1000f;\n image->chromaticity.blue_primary.x=0.1500f;\n image->chromaticity.blue_primary.y=0.0600f;\n image->chromaticity.blue_primary.z=0.7900f;\n image->chromaticity.white_point.x=0.3127f;\n image->chromaticity.white_point.y=0.3290f;\n image->chromaticity.white_point.z=0.3583f;\n image->interlace=NoInterlace;\n image->ticks_per_second=UndefinedTicksPerSecond;\n image->compose=OverCompositeOp;\n image->blur=1.0;\n InitializeExceptionInfo(&image->exception);\n (void) QueryColorDatabase(BackgroundColor,&image->background_color,\n &image->exception);\n (void) QueryColorDatabase(BorderColor,&image->border_color,&image->exception);\n (void) QueryColorDatabase(MatteColor,&image->matte_color,&image->exception);\n (void) QueryColorDatabase(TransparentColor,&image->transparent_color,\n &image->exception);\n GetTimerInfo(&image->timer);\n image->ping=MagickFalse;\n image->cache=AcquirePixelCache(0);\n image->blob=CloneBlobInfo((BlobInfo *) NULL);\n image->timestamp=time((time_t *) NULL);\n image->debug=IsEventLogging();\n image->reference_count=1;\n image->semaphore=AllocateSemaphoreInfo();\n image->signature=MagickCoreSignature;\n if (image_info == (ImageInfo *) NULL)\n return(image);\n /*\n Transfer image info.\n */\n SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue :\n MagickFalse);\n (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);\n (void) CopyMagickString(image->magick_filename,image_info->filename,\n MaxTextExtent);\n (void) CopyMagickString(image->magick,image_info->magick,MaxTextExtent);\n if (image_info->size != (char *) NULL)\n {\n (void) ParseAbsoluteGeometry(image_info->size,&image->extract_info);\n image->columns=image->extract_info.width;\n image->rows=image->extract_info.height;\n image->offset=image->extract_info.x;\n image->extract_info.x=0;\n image->extract_info.y=0;\n }\n if (image_info->extract != (char *) NULL)\n {\n RectangleInfo\n geometry;\n\n (void) memset(&geometry,0,sizeof(geometry));\n flags=ParseAbsoluteGeometry(image_info->extract,&geometry);\n if (((flags & XValue) != 0) || ((flags & YValue) != 0))\n {\n image->extract_info=geometry;\n Swap(image->columns,image->extract_info.width);\n Swap(image->rows,image->extract_info.height);\n }\n }\n image->compression=image_info->compression;\n image->quality=image_info->quality;\n image->endian=image_info->endian;\n image->interlace=image_info->interlace;\n image->units=image_info->units;\n if (image_info->density != (char *) NULL)\n {\n GeometryInfo\n geometry_info;\n\n flags=ParseGeometry(image_info->density,&geometry_info);\n image->x_resolution=geometry_info.rho;\n image->y_resolution=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->y_resolution=image->x_resolution;\n }\n if (image_info->page != (char *) NULL)\n {\n char\n *geometry;\n\n image->page=image->extract_info;\n geometry=GetPageGeometry(image_info->page);\n (void) ParseAbsoluteGeometry(geometry,&image->page);\n geometry=DestroyString(geometry);\n }\n if (image_info->depth != 0)\n image->depth=image_info->depth;\n image->dither=image_info->dither;\n image->background_color=image_info->background_color;\n image->border_color=image_info->border_color;\n image->matte_color=image_info->matte_color;\n image->transparent_color=image_info->transparent_color;\n image->ping=image_info->ping;\n image->progress_monitor=image_info->progress_monitor;\n image->client_data=image_info->client_data;\n if (image_info->cache != (void *) NULL)\n ClonePixelCacheMethods(image->cache,image_info->cache);\n (void) SyncImageSettings(image_info,image);\n option=GetImageOption(image_info,\"delay\");\n if (option != (const char *) NULL)\n {\n GeometryInfo\n geometry_info;\n\n flags=ParseGeometry(option,&geometry_info);\n if ((flags & GreaterValue) != 0)\n {\n if (image->delay > (size_t) floor(geometry_info.rho+0.5))\n image->delay=(size_t) floor(geometry_info.rho+0.5);\n }\n else\n if ((flags & LessValue) != 0)\n {\n if (image->delay < (size_t) floor(geometry_info.rho+0.5))\n image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);\n }\n else\n image->delay=(size_t) floor(geometry_info.rho+0.5);\n if ((flags & SigmaValue) != 0)\n image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);\n }\n option=GetImageOption(image_info,\"dispose\");\n if (option != (const char *) NULL)\n image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions,\n MagickFalse,option);\n return(image);\n}", "project": "ImageMagick6", "hash": 172244786076976468574270858869555969333, "size": 160, "commit_id": "27b1c74979ac473a430e266ff6c4b645664bc805", "message": "https://github.com/ImageMagick/ImageMagick/issues/1522", "target": 1, "dataset": "other", "idx": 210612}
  846. {"func": "MagickExport Image *AcquireImage(const ImageInfo *image_info)\n{\n const char\n *option;\n\n Image\n *image;\n\n MagickStatusType\n flags;\n\n /*\n Allocate image structure.\n */\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n image=(Image *) AcquireCriticalMemory(sizeof(*image));\n (void) memset(image,0,sizeof(*image));\n /*\n Initialize Image structure.\n */\n (void) CopyMagickString(image->magick,\"MIFF\",MaxTextExtent);\n image->storage_class=DirectClass;\n image->depth=MAGICKCORE_QUANTUM_DEPTH;\n image->colorspace=sRGBColorspace;\n image->rendering_intent=PerceptualIntent;\n image->gamma=1.000f/2.200f;\n image->chromaticity.red_primary.x=0.6400f;\n image->chromaticity.red_primary.y=0.3300f;\n image->chromaticity.red_primary.z=0.0300f;\n image->chromaticity.green_primary.x=0.3000f;\n image->chromaticity.green_primary.y=0.6000f;\n image->chromaticity.green_primary.z=0.1000f;\n image->chromaticity.blue_primary.x=0.1500f;\n image->chromaticity.blue_primary.y=0.0600f;\n image->chromaticity.blue_primary.z=0.7900f;\n image->chromaticity.white_point.x=0.3127f;\n image->chromaticity.white_point.y=0.3290f;\n image->chromaticity.white_point.z=0.3583f;\n image->interlace=NoInterlace;\n image->ticks_per_second=UndefinedTicksPerSecond;\n image->compose=OverCompositeOp;\n image->blur=1.0;\n InitializeExceptionInfo(&image->exception);\n (void) QueryColorDatabase(BackgroundColor,&image->background_color,\n &image->exception);\n (void) QueryColorDatabase(BorderColor,&image->border_color,&image->exception);\n (void) QueryColorDatabase(MatteColor,&image->matte_color,&image->exception);\n (void) QueryColorDatabase(TransparentColor,&image->transparent_color,\n &image->exception);\n GetTimerInfo(&image->timer);\n image->ping=MagickFalse;\n image->cache=AcquirePixelCache(0);\n image->blob=CloneBlobInfo((BlobInfo *) NULL);\n image->timestamp=time((time_t *) NULL);\n image->debug=IsEventLogging();\n image->reference_count=1;\n image->semaphore=AllocateSemaphoreInfo();\n image->signature=MagickCoreSignature;\n if (image_info == (ImageInfo *) NULL)\n return(image);\n /*\n Transfer image info.\n */\n SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue :\n MagickFalse);\n (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);\n (void) CopyMagickString(image->magick_filename,image_info->filename,\n MaxTextExtent);\n (void) CopyMagickString(image->magick,image_info->magick,MaxTextExtent);\n if (image_info->size != (char *) NULL)\n {\n (void) ParseAbsoluteGeometry(image_info->size,&image->extract_info);\n image->columns=image->extract_info.width;\n image->rows=image->extract_info.height;\n image->offset=image->extract_info.x;\n image->extract_info.x=0;\n image->extract_info.y=0;\n }\n if (image_info->extract != (char *) NULL)\n {\n RectangleInfo\n geometry;\n\n (void) memset(&geometry,0,sizeof(geometry));\n flags=ParseAbsoluteGeometry(image_info->extract,&geometry);\n if (((flags & XValue) != 0) || ((flags & YValue) != 0))\n {\n image->extract_info=geometry;\n Swap(image->columns,image->extract_info.width);\n Swap(image->rows,image->extract_info.height);\n }\n }\n image->compression=image_info->compression;\n image->quality=image_info->quality;\n image->endian=image_info->endian;\n image->interlace=image_info->interlace;\n image->units=image_info->units;\n if (image_info->density != (char *) NULL)\n {\n GeometryInfo\n geometry_info;\n\n flags=ParseGeometry(image_info->density,&geometry_info);\n if ((flags & RhoValue) != 0)\n image->x_resolution=geometry_info.rho;\n image->y_resolution=image->x_resolution;\n if ((flags & SigmaValue) != 0)\n image->y_resolution=geometry_info.sigma;\n }\n if (image_info->page != (char *) NULL)\n {\n char\n *geometry;\n\n image->page=image->extract_info;\n geometry=GetPageGeometry(image_info->page);\n (void) ParseAbsoluteGeometry(geometry,&image->page);\n geometry=DestroyString(geometry);\n }\n if (image_info->depth != 0)\n image->depth=image_info->depth;\n image->dither=image_info->dither;\n image->background_color=image_info->background_color;\n image->border_color=image_info->border_color;\n image->matte_color=image_info->matte_color;\n image->transparent_color=image_info->transparent_color;\n image->ping=image_info->ping;\n image->progress_monitor=image_info->progress_monitor;\n image->client_data=image_info->client_data;\n if (image_info->cache != (void *) NULL)\n ClonePixelCacheMethods(image->cache,image_info->cache);\n (void) SyncImageSettings(image_info,image);\n option=GetImageOption(image_info,\"delay\");\n if (option != (const char *) NULL)\n {\n GeometryInfo\n geometry_info;\n\n flags=ParseGeometry(option,&geometry_info);\n if ((flags & GreaterValue) != 0)\n {\n if (image->delay > (size_t) floor(geometry_info.rho+0.5))\n image->delay=(size_t) floor(geometry_info.rho+0.5);\n }\n else\n if ((flags & LessValue) != 0)\n {\n if (image->delay < (size_t) floor(geometry_info.rho+0.5))\n image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);\n }\n else\n image->delay=(size_t) floor(geometry_info.rho+0.5);\n if ((flags & SigmaValue) != 0)\n image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);\n }\n option=GetImageOption(image_info,\"dispose\");\n if (option != (const char *) NULL)\n image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions,\n MagickFalse,option);\n return(image);\n}", "project": "ImageMagick6", "hash": 10506252874396520598024428032753043560, "size": 161, "commit_id": "27b1c74979ac473a430e266ff6c4b645664bc805", "message": "https://github.com/ImageMagick/ImageMagick/issues/1522", "target": 0, "dataset": "other", "idx": 438548}
  847. {"func": "bfad_im_get_stats(struct Scsi_Host *shost)\n{\n\tstruct bfad_im_port_s *im_port =\n\t\t\t(struct bfad_im_port_s *) shost->hostdata[0];\n\tstruct bfad_s *bfad = im_port->bfad;\n\tstruct bfad_hal_comp fcomp;\n\tunion bfa_port_stats_u *fcstats;\n\tstruct fc_host_statistics *hstats;\n\tbfa_status_t rc;\n\tunsigned long flags;\n\n\tfcstats = kzalloc(sizeof(union bfa_port_stats_u), GFP_KERNEL);\n\tif (fcstats == NULL)\n\t\treturn NULL;\n\n\thstats = &bfad->link_stats;\n\tinit_completion(&fcomp.comp);\n\tspin_lock_irqsave(&bfad->bfad_lock, flags);\n\tmemset(hstats, 0, sizeof(struct fc_host_statistics));\n\trc = bfa_port_get_stats(BFA_FCPORT(&bfad->bfa),\n\t\t\t\tfcstats, bfad_hcb_comp, &fcomp);\n\tspin_unlock_irqrestore(&bfad->bfad_lock, flags);\n\tif (rc != BFA_STATUS_OK)\n\t\treturn NULL;\n\n\twait_for_completion(&fcomp.comp);\n\n\t/* Fill the fc_host_statistics structure */\n\thstats->seconds_since_last_reset = fcstats->fc.secs_reset;\n\thstats->tx_frames = fcstats->fc.tx_frames;\n\thstats->tx_words = fcstats->fc.tx_words;\n\thstats->rx_frames = fcstats->fc.rx_frames;\n\thstats->rx_words = fcstats->fc.rx_words;\n\thstats->lip_count = fcstats->fc.lip_count;\n\thstats->nos_count = fcstats->fc.nos_count;\n\thstats->error_frames = fcstats->fc.error_frames;\n\thstats->dumped_frames = fcstats->fc.dropped_frames;\n\thstats->link_failure_count = fcstats->fc.link_failures;\n\thstats->loss_of_sync_count = fcstats->fc.loss_of_syncs;\n\thstats->loss_of_signal_count = fcstats->fc.loss_of_signals;\n\thstats->prim_seq_protocol_err_count = fcstats->fc.primseq_errs;\n\thstats->invalid_crc_count = fcstats->fc.invalid_crcs;\n\n\tkfree(fcstats);\n\treturn hstats;\n}", "project": "linux", "hash": 276831105069953521205119097095926483692, "size": 46, "commit_id": "0e62395da2bd5166d7c9e14cbc7503b256a34cb0", "message": "scsi: bfa: release allocated memory in case of error\n\nIn bfad_im_get_stats if bfa_port_get_stats fails, allocated memory needs to\nbe released.\n\nLink: https://lore.kernel.org/r/20190910234417.22151-1-navid.emamdoost@gmail.com\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Martin K. Petersen <martin.petersen@oracle.com>", "target": 1, "dataset": "other", "idx": 210708}
  848. {"func": "bfad_im_get_stats(struct Scsi_Host *shost)\n{\n\tstruct bfad_im_port_s *im_port =\n\t\t\t(struct bfad_im_port_s *) shost->hostdata[0];\n\tstruct bfad_s *bfad = im_port->bfad;\n\tstruct bfad_hal_comp fcomp;\n\tunion bfa_port_stats_u *fcstats;\n\tstruct fc_host_statistics *hstats;\n\tbfa_status_t rc;\n\tunsigned long flags;\n\n\tfcstats = kzalloc(sizeof(union bfa_port_stats_u), GFP_KERNEL);\n\tif (fcstats == NULL)\n\t\treturn NULL;\n\n\thstats = &bfad->link_stats;\n\tinit_completion(&fcomp.comp);\n\tspin_lock_irqsave(&bfad->bfad_lock, flags);\n\tmemset(hstats, 0, sizeof(struct fc_host_statistics));\n\trc = bfa_port_get_stats(BFA_FCPORT(&bfad->bfa),\n\t\t\t\tfcstats, bfad_hcb_comp, &fcomp);\n\tspin_unlock_irqrestore(&bfad->bfad_lock, flags);\n\tif (rc != BFA_STATUS_OK) {\n\t\tkfree(fcstats);\n\t\treturn NULL;\n\t}\n\n\twait_for_completion(&fcomp.comp);\n\n\t/* Fill the fc_host_statistics structure */\n\thstats->seconds_since_last_reset = fcstats->fc.secs_reset;\n\thstats->tx_frames = fcstats->fc.tx_frames;\n\thstats->tx_words = fcstats->fc.tx_words;\n\thstats->rx_frames = fcstats->fc.rx_frames;\n\thstats->rx_words = fcstats->fc.rx_words;\n\thstats->lip_count = fcstats->fc.lip_count;\n\thstats->nos_count = fcstats->fc.nos_count;\n\thstats->error_frames = fcstats->fc.error_frames;\n\thstats->dumped_frames = fcstats->fc.dropped_frames;\n\thstats->link_failure_count = fcstats->fc.link_failures;\n\thstats->loss_of_sync_count = fcstats->fc.loss_of_syncs;\n\thstats->loss_of_signal_count = fcstats->fc.loss_of_signals;\n\thstats->prim_seq_protocol_err_count = fcstats->fc.primseq_errs;\n\thstats->invalid_crc_count = fcstats->fc.invalid_crcs;\n\n\tkfree(fcstats);\n\treturn hstats;\n}", "project": "linux", "hash": 16138988951117577206220013462963868888, "size": 48, "commit_id": "0e62395da2bd5166d7c9e14cbc7503b256a34cb0", "message": "scsi: bfa: release allocated memory in case of error\n\nIn bfad_im_get_stats if bfa_port_get_stats fails, allocated memory needs to\nbe released.\n\nLink: https://lore.kernel.org/r/20190910234417.22151-1-navid.emamdoost@gmail.com\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Martin K. Petersen <martin.petersen@oracle.com>", "target": 0, "dataset": "other", "idx": 439536}
  849. {"func": "ldns_rr_new_frm_str_internal(ldns_rr **newrr, const char *str,\n\t\t\t\t\t\t\t uint32_t default_ttl, const ldns_rdf *origin,\n\t\t\t\t\t\t\t ldns_rdf **prev, bool question)\n{\n\tldns_rr *new;\n\tconst ldns_rr_descriptor *desc;\n\tldns_rr_type rr_type;\n\tldns_buffer *rr_buf = NULL;\n\tldns_buffer *rd_buf = NULL;\n\tuint32_t ttl_val;\n\tchar *owner = NULL;\n\tchar *ttl = NULL;\n\tldns_rr_class clas_val;\n\tchar *clas = NULL;\n\tchar *type = NULL;\n\tsize_t type_sz;\n\tchar *rdata = NULL;\n\tchar *rd = NULL;\n\tchar *xtok = NULL; /* For RDF types with spaces (i.e. extra tokens) */\n\tsize_t rd_strlen;\n\tconst char *delimiters;\n\tssize_t c;\n\tldns_rdf *owner_dname;\n const char* endptr;\n int was_unknown_rr_format = 0;\n\tldns_status status = LDNS_STATUS_OK;\n\n\t/* used for types with unknown number of rdatas */\n\tbool done;\n\tbool quoted;\n\n\tldns_rdf *r = NULL;\n\tuint16_t r_cnt;\n\tuint16_t r_min;\n\tuint16_t r_max;\n size_t pre_data_pos;\n\n\tuint16_t hex_data_size;\n\tchar *hex_data_str = NULL;\n\tuint16_t cur_hex_data_size;\n\tsize_t hex_pos = 0;\n\tuint8_t *hex_data = NULL;\n\n\tnew = ldns_rr_new();\n\n\towner = LDNS_XMALLOC(char, LDNS_MAX_DOMAINLEN + 1);\n\tttl = LDNS_XMALLOC(char, LDNS_TTL_DATALEN);\n\tclas = LDNS_XMALLOC(char, LDNS_SYNTAX_DATALEN);\n\trdata = LDNS_XMALLOC(char, LDNS_MAX_PACKETLEN + 1);\n\trr_buf = LDNS_MALLOC(ldns_buffer);\n\trd_buf = LDNS_MALLOC(ldns_buffer);\n\trd = LDNS_XMALLOC(char, LDNS_MAX_RDFLEN);\n\txtok = LDNS_XMALLOC(char, LDNS_MAX_RDFLEN);\n\tif (rr_buf) {\n\t\trr_buf->_data = NULL;\n\t}\n\tif (rd_buf) {\n\t\trd_buf->_data = NULL;\n\t}\n\tif (!new || !owner || !ttl || !clas || !rdata ||\n\t\t\t!rr_buf || !rd_buf || !rd || !xtok) {\n\n\t\tgoto memerror;\n\t}\n\n\tldns_buffer_new_frm_data(rr_buf, (char*)str, strlen(str));\n\n\t/* split the rr in its parts -1 signals trouble */\n\tif (ldns_bget_token(rr_buf, owner, \"\\t\\n \", LDNS_MAX_DOMAINLEN) == -1){\n\n\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\tgoto error;\n\t}\n\n\tif (ldns_bget_token(rr_buf, ttl, \"\\t\\n \", LDNS_TTL_DATALEN) == -1) {\n\n\t\tstatus = LDNS_STATUS_SYNTAX_TTL_ERR;\n\t\tgoto error;\n\t}\n\tttl_val = (uint32_t) ldns_str2period(ttl, &endptr);\n\n\tif (strlen(ttl) > 0 && !isdigit((int) ttl[0])) {\n\t\t/* ah, it's not there or something */\n\t\tif (default_ttl == 0) {\n\t\t\tttl_val = LDNS_DEFAULT_TTL;\n\t\t} else {\n\t\t\tttl_val = default_ttl;\n\t\t}\n\t\t/* we not ASSUMING the TTL is missing and that\n\t\t * the rest of the RR is still there. That is\n\t\t * CLASS TYPE RDATA\n\t\t * so ttl value we read is actually the class\n\t\t */\n\t\tclas_val = ldns_get_rr_class_by_name(ttl);\n\t\t/* class can be left out too, assume IN, current\n\t\t * token must be type\n\t\t */\n\t\tif (clas_val == 0) {\n\t\t\tclas_val = LDNS_RR_CLASS_IN;\n\t\t\ttype_sz = strlen(ttl) + 1;\n\t\t\ttype = LDNS_XMALLOC(char, type_sz);\n\t\t\tif (!type) {\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t\tstrlcpy(type, ttl, type_sz);\n\t\t}\n\t} else {\n\t\tif (-1 == ldns_bget_token(\n\t\t\t\trr_buf, clas, \"\\t\\n \", LDNS_SYNTAX_DATALEN)) {\n\n\t\t\tstatus = LDNS_STATUS_SYNTAX_CLASS_ERR;\n\t\t\tgoto error;\n\t\t}\n\t\tclas_val = ldns_get_rr_class_by_name(clas);\n\t\t/* class can be left out too, assume IN, current\n\t\t * token must be type\n\t\t */\n\t\tif (clas_val == 0) {\n\t\t\tclas_val = LDNS_RR_CLASS_IN;\n\t\t\ttype_sz = strlen(clas) + 1;\n\t\t\ttype = LDNS_XMALLOC(char, type_sz);\n\t\t\tif (!type) {\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t\tstrlcpy(type, clas, type_sz);\n\t\t}\n\t}\n\t/* the rest should still be waiting for us */\n\n\tif (!type) {\n\t\ttype = LDNS_XMALLOC(char, LDNS_SYNTAX_DATALEN);\n\t\tif (!type) {\n\t\t\tgoto memerror;\n\t\t}\n\t\tif (-1 == ldns_bget_token(\n\t\t\t\trr_buf, type, \"\\t\\n \", LDNS_SYNTAX_DATALEN)) {\n\n\t\t\tstatus = LDNS_STATUS_SYNTAX_TYPE_ERR;\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tif (ldns_bget_token(rr_buf, rdata, \"\\0\", LDNS_MAX_PACKETLEN) == -1) {\n\t\t/* apparently we are done, and it's only a question RR\n\t\t * so do not set status and go to ldnserror here\n\t\t */\n\t}\n\tldns_buffer_new_frm_data(rd_buf, rdata, strlen(rdata));\n\n\tif (strlen(owner) <= 1 && strncmp(owner, \"@\", 1) == 0) {\n\t\tif (origin) {\n\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(origin));\n\t\t} else if (prev && *prev) {\n\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(*prev));\n\t\t} else {\n\t\t\t/* default to root */\n\t\t\tldns_rr_set_owner(new, ldns_dname_new_frm_str(\".\"));\n\t\t}\n\n\t\t/* @ also overrides prev */\n\t\tif (prev) {\n\t\t\tldns_rdf_deep_free(*prev);\n\t\t\t*prev = ldns_rdf_clone(ldns_rr_owner(new));\n\t\t\tif (!*prev) {\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (strlen(owner) == 0) {\n\t\t\t/* no ownername was given, try prev, if that fails\n\t\t\t * origin, else default to root */\n\t\t\tif (prev && *prev) {\n\t\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(*prev));\n\t\t\t} else if (origin) {\n\t\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(origin));\n\t\t\t} else {\n\t\t\t\tldns_rr_set_owner(new,\n\t\t\t\t\t\tldns_dname_new_frm_str(\".\"));\n\t\t\t}\n\t\t\tif(!ldns_rr_owner(new)) {\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t} else {\n\t\t\towner_dname = ldns_dname_new_frm_str(owner);\n\t\t\tif (!owner_dname) {\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\t\t\tgoto error;\n\t\t\t}\n\n\t\t\tldns_rr_set_owner(new, owner_dname);\n\t\t\tif (!ldns_dname_str_absolute(owner) && origin) {\n\t\t\t\tif(ldns_dname_cat(ldns_rr_owner(new), origin)\n\t\t\t\t\t\t!= LDNS_STATUS_OK) {\n\n\t\t\t\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (prev) {\n\t\t\t\tldns_rdf_deep_free(*prev);\n\t\t\t\t*prev = ldns_rdf_clone(ldns_rr_owner(new));\n\t\t\t\tif (!*prev) {\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tLDNS_FREE(owner);\n\n\tldns_rr_set_question(new, question);\n\n\tldns_rr_set_ttl(new, ttl_val);\n\tLDNS_FREE(ttl);\n\n\tldns_rr_set_class(new, clas_val);\n\tLDNS_FREE(clas);\n\n\trr_type = ldns_get_rr_type_by_name(type);\n\tLDNS_FREE(type);\n\n\tdesc = ldns_rr_descript((uint16_t)rr_type);\n\tldns_rr_set_type(new, rr_type);\n\tif (desc) {\n\t\t/* only the rdata remains */\n\t\tr_max = ldns_rr_descriptor_maximum(desc);\n\t\tr_min = ldns_rr_descriptor_minimum(desc);\n\t} else {\n\t\tr_min = 0;\n\t\tr_max = 1;\n\t}\n\n\tfor (done = false, r_cnt = 0; !done && r_cnt < r_max; r_cnt++) {\n\t\tquoted = false;\n\n\t\tswitch (ldns_rr_descriptor_field_type(desc, r_cnt)) {\n\t\tcase LDNS_RDF_TYPE_B64 :\n\t\tcase LDNS_RDF_TYPE_HEX : /* These rdf types may con- */\n\t\tcase LDNS_RDF_TYPE_LOC : /* tain whitespace, only if */\n\t\tcase LDNS_RDF_TYPE_WKS : /* it is the last rd field. */\n\t\tcase LDNS_RDF_TYPE_IPSECKEY :\n\t\tcase LDNS_RDF_TYPE_AMTRELAY :\n\t\tcase LDNS_RDF_TYPE_NSEC :\tif (r_cnt == r_max - 1) {\n\t\t\t\t\t\t\tdelimiters = \"\\n\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* fallthrough */\n\t\tdefault :\tdelimiters = \"\\n\\t \"; \n\t\t}\n\n\t\tif (ldns_rdf_type_maybe_quoted(\n\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\tdesc, r_cnt)) &&\n\t\t\t\tldns_buffer_remaining(rd_buf) > 0){\n\n\t\t\t/* skip spaces */\n\t\t\twhile (*(ldns_buffer_current(rd_buf)) == ' ') {\n\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t}\n\n\t\t\tif (*(ldns_buffer_current(rd_buf)) == '\\\"') {\n\t\t\t\tdelimiters = \"\\\"\\0\";\n\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t\tquoted = true;\n\t\t\t} else if (ldns_rr_descriptor_field_type(desc, r_cnt)\n\t\t\t\t\t== LDNS_RDF_TYPE_LONG_STR) {\n\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\n\t\t/* because number of fields can be variable, we can't rely on\n\t\t * _maximum() only\n\t\t */\n\n\t\t/* skip spaces */\n\t\twhile (ldns_buffer_position(rd_buf) < ldns_buffer_limit(rd_buf)\n\t\t\t\t&& *(ldns_buffer_current(rd_buf)) == ' '\n\t\t\t\t&& !quoted) {\n\n\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t}\n\n\t\tpre_data_pos = ldns_buffer_position(rd_buf);\n\t\tif (-1 == (c = ldns_bget_token(\n\t\t\t\trd_buf, rd, delimiters, LDNS_MAX_RDFLEN))) {\n\n\t\t\tdone = true;\n\t\t\t(void)done; /* we're breaking, so done not read anymore */\n\t\t\tbreak;\n\t\t}\n\t\t/* hmmz, rfc3597 specifies that any type can be represented \n\t\t * with \\# method, which can contain spaces...\n\t\t * it does specify size though...\n\t\t */\n\t\trd_strlen = strlen(rd);\n\n\t\t/* unknown RR data */\n\t\tif (strncmp(rd, \"\\\\#\", 2) == 0 && !quoted &&\n\t\t\t\t(rd_strlen == 2 || rd[2]==' ')) {\n\n\t\t\twas_unknown_rr_format = 1;\n\t\t\t/* go back to before \\#\n\t\t\t * and skip it while setting delimiters better\n\t\t\t */\n\t\t\tldns_buffer_set_position(rd_buf, pre_data_pos);\n\t\t\tdelimiters = \"\\n\\t \";\n\t\t\t(void)ldns_bget_token(rd_buf, rd,\n\t\t\t\t\tdelimiters, LDNS_MAX_RDFLEN);\n\t\t\t/* read rdata octet length */\n\t\t\tc = ldns_bget_token(rd_buf, rd,\n\t\t\t\t\tdelimiters, LDNS_MAX_RDFLEN);\n\t\t\tif (c == -1) {\n\t\t\t\t/* something goes very wrong here */\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\thex_data_size = (uint16_t) atoi(rd);\n\t\t\t/* copy hex chars into hex str (2 chars per byte) */\n\t\t\thex_data_str = LDNS_XMALLOC(char, 2*hex_data_size + 1);\n\t\t\tif (!hex_data_str) {\n\t\t\t\t/* malloc error */\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t\tcur_hex_data_size = 0;\n\t\t\twhile(cur_hex_data_size < 2 * hex_data_size) {\n\t\t\t\tc = ldns_bget_token(rd_buf, rd,\n\t\t\t\t\t\tdelimiters, LDNS_MAX_RDFLEN);\n\t\t\t\tif (c == -1) {\n\t\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\trd_strlen = strlen(rd);\n\t\t\t\tif ((size_t)cur_hex_data_size + rd_strlen >\n\t\t\t\t 2 * (size_t)hex_data_size) {\n\t\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tstrlcpy(hex_data_str + cur_hex_data_size, rd,\n\t\t\t\t\t\trd_strlen + 1);\n\n\t\t\t\tcur_hex_data_size += rd_strlen;\n\t\t\t}\n\t\t\thex_data_str[cur_hex_data_size] = '\\0';\n\n\t\t\t/* correct the rdf type */\n\t\t\t/* if *we* know the type, interpret it as wireformat */\n\t\t\tif (desc) {\n\t\t\t\thex_pos = 0;\n\t\t\t\thex_data =\n\t\t\t\t\tLDNS_XMALLOC(uint8_t, hex_data_size+2);\n\n\t\t\t\tif (!hex_data) {\n\t\t\t\t\tgoto memerror;\n\t\t\t\t}\n\t\t\t\tldns_write_uint16(hex_data, hex_data_size);\n\t\t\t\tldns_hexstring_to_data(\n\t\t\t\t\t\thex_data + 2, hex_data_str);\n\t\t\t\tstatus = ldns_wire2rdf(new, hex_data,\n\t\t\t\t\t\thex_data_size + 2, &hex_pos);\n\t\t\t\tif (status != LDNS_STATUS_OK) {\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tLDNS_FREE(hex_data);\n\t\t\t} else {\n\t\t\t\tr = ldns_rdf_new_frm_str(LDNS_RDF_TYPE_HEX,\n\t\t\t\t\t\thex_data_str);\n\t\t\t\tif (!r) {\n\t\t\t\t\tgoto memerror;\n\t\t\t\t}\n\t\t\t\tldns_rdf_set_type(r, LDNS_RDF_TYPE_UNKNOWN);\n\t\t\t\tif (!ldns_rr_push_rdf(new, r)) {\n\t\t\t\t\tgoto memerror;\n\t\t\t\t}\n\t\t\t}\n\t\t\tLDNS_FREE(hex_data_str);\n\n\t\t} else if(rd_strlen > 0 || quoted) {\n\t\t\t/* Normal RR */\n\t\t\tswitch(ldns_rr_descriptor_field_type(desc, r_cnt)) {\n\n\t\t\tcase LDNS_RDF_TYPE_HEX:\n\t\t\tcase LDNS_RDF_TYPE_B64:\n\t\t\t\t/* When this is the last rdata field, then the\n\t\t\t\t * rest should be read in (cause then these\n\t\t\t\t * rdf types may contain spaces).\n\t\t\t\t */\n\t\t\t\tif (r_cnt == r_max - 1) {\n\t\t\t\t\tc = ldns_bget_token(rd_buf, xtok,\n\t\t\t\t\t\t\t\"\\n\", LDNS_MAX_RDFLEN);\n\t\t\t\t\tif (c != -1) {\n\t\t\t\t\t\t(void) strncat(rd, xtok,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\t\t\t\tdesc, r_cnt), rd);\n\t\t\t\tbreak;\n\n\t\t\tcase LDNS_RDF_TYPE_HIP:\n\t\t\t\t/*\n\t\t\t\t * In presentation format this RDATA type has\n\t\t\t\t * three tokens: An algorithm byte, then a\n\t\t\t\t * variable length HIT (in hexbytes) and then\n\t\t\t\t * a variable length Public Key (in base64).\n\t\t\t\t *\n\t\t\t\t * We have just read the algorithm, so we need\n\t\t\t\t * two more tokens: HIT and Public Key.\n\t\t\t\t */\n\t\t\t\tdo {\n\t\t\t\t\t/* Read and append HIT */\n\t\t\t\t\tif (ldns_bget_token(rd_buf,\n\t\t\t\t\t\t\txtok, delimiters,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN) == -1)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t(void) strncat(rd, \" \",\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\t\t\t\t\t(void) strncat(rd, xtok,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\n\t\t\t\t\t/* Read and append Public Key*/\n\t\t\t\t\tif (ldns_bget_token(rd_buf,\n\t\t\t\t\t\t\txtok, delimiters,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN) == -1)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t(void) strncat(rd, \" \",\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\t\t\t\t\t(void) strncat(rd, xtok,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\t\t\t\t} while (false);\n\n\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\t\t\t\tdesc, r_cnt), rd);\n\t\t\t\tbreak;\n\n\t\t\tcase LDNS_RDF_TYPE_DNAME:\n\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\t\t\t\tdesc, r_cnt), rd);\n\n\t\t\t\t/* check if the origin should be used\n\t\t\t\t * or concatenated\n\t\t\t\t */\n\t\t\t\tif (r && ldns_rdf_size(r) > 1 &&\n\t\t\t\t\t\tldns_rdf_data(r)[0] == 1 &&\n\t\t\t\t\t\tldns_rdf_data(r)[1] == '@') {\n\n\t\t\t\t\tldns_rdf_deep_free(r);\n\n\t\t\t\t\tr = origin ? ldns_rdf_clone(origin)\n\n\t\t\t\t\t : ( rr_type == LDNS_RR_TYPE_SOA ?\n\n\t\t\t\t\t ldns_rdf_clone(\n\t\t\t\t\t\t ldns_rr_owner(new))\n\n\t\t\t\t\t : ldns_rdf_new_frm_str(\n\t\t\t\t\t\t LDNS_RDF_TYPE_DNAME, \".\")\n\t\t\t\t\t );\n\n\t\t\t\t} else if (r && rd_strlen >= 1 && origin &&\n\t\t\t\t\t\t!ldns_dname_str_absolute(rd)) {\n\n\t\t\t\t\tstatus = ldns_dname_cat(r, origin);\n\t\t\t\t\tif (status != LDNS_STATUS_OK) {\n\t\t\t\t\t\tgoto error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\t\t\t\tdesc, r_cnt), rd);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!r) {\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tldns_rr_push_rdf(new, r);\n\t\t}\n\t\tif (quoted) {\n\t\t\tif (ldns_buffer_available(rd_buf, 1)) {\n\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t} else {\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t}\n\n\t} /* for (done = false, r_cnt = 0; !done && r_cnt < r_max; r_cnt++) */\n\tLDNS_FREE(rd);\n\tLDNS_FREE(xtok);\n\tldns_buffer_free(rr_buf);\n\tLDNS_FREE(rdata);\n\tif (ldns_buffer_remaining(rd_buf) > 0) {\n\t\tldns_buffer_free(rd_buf);\n\t\tldns_rr_free(new);\n\t\treturn LDNS_STATUS_SYNTAX_SUPERFLUOUS_TEXT_ERR;\n\t}\n\tldns_buffer_free(rd_buf);\n\n\tif (!question && desc && !was_unknown_rr_format &&\n\t\t\tldns_rr_rd_count(new) < r_min) {\n\n\t\tldns_rr_free(new);\n\t\treturn LDNS_STATUS_SYNTAX_MISSING_VALUE_ERR;\n\t}\n\n\tif (newrr) {\n\t\t*newrr = new;\n\t} else {\n\t\t/* Maybe the caller just wanted to see if it would parse? */\n\t\tldns_rr_free(new);\n\t}\n\treturn LDNS_STATUS_OK;\n\nmemerror:\n\tstatus = LDNS_STATUS_MEM_ERR;\nerror:\n\tif (rd_buf && rd_buf->_data) {\n\t\tldns_buffer_free(rd_buf);\n\t} else {\n\t\tLDNS_FREE(rd_buf);\n\t}\n\tif (rr_buf && rr_buf->_data) {\n\t\tldns_buffer_free(rr_buf);\n\t} else {\n\t\tLDNS_FREE(rr_buf);\n\t}\n\tLDNS_FREE(type);\n\tLDNS_FREE(owner);\n\tLDNS_FREE(ttl);\n\tLDNS_FREE(clas);\n\tLDNS_FREE(hex_data);\n\tLDNS_FREE(hex_data_str);\n\tLDNS_FREE(xtok);\n\tLDNS_FREE(rd);\n\tLDNS_FREE(rdata);\n\tldns_rr_free(new);\n\treturn status;\n}", "project": "ldns", "hash": 275591331531328108995815488932308997000, "size": 550, "commit_id": "15d96206996bea969fbc918eb0a4a346f514b9f3", "message": "* bugfix #70: heap Out-of-bound Read vulnerability in\n rr_frm_str_internal reported by pokerfacett.", "target": 1, "dataset": "other", "idx": 210738}
  850. {"func": "ldns_rr_new_frm_str_internal(ldns_rr **newrr, const char *str,\n\t\t\t\t\t\t\t uint32_t default_ttl, const ldns_rdf *origin,\n\t\t\t\t\t\t\t ldns_rdf **prev, bool question)\n{\n\tldns_rr *new;\n\tconst ldns_rr_descriptor *desc;\n\tldns_rr_type rr_type;\n\tldns_buffer *rr_buf = NULL;\n\tldns_buffer *rd_buf = NULL;\n\tuint32_t ttl_val;\n\tchar *owner = NULL;\n\tchar *ttl = NULL;\n\tldns_rr_class clas_val;\n\tchar *clas = NULL;\n\tchar *type = NULL;\n\tsize_t type_sz;\n\tchar *rdata = NULL;\n\tchar *rd = NULL;\n\tchar *xtok = NULL; /* For RDF types with spaces (i.e. extra tokens) */\n\tsize_t rd_strlen;\n\tconst char *delimiters;\n\tssize_t c;\n\tldns_rdf *owner_dname;\n const char* endptr;\n int was_unknown_rr_format = 0;\n\tldns_status status = LDNS_STATUS_OK;\n\n\t/* used for types with unknown number of rdatas */\n\tbool done;\n\tbool quoted;\n\n\tldns_rdf *r = NULL;\n\tuint16_t r_cnt;\n\tuint16_t r_min;\n\tuint16_t r_max;\n size_t pre_data_pos;\n\n\tuint16_t hex_data_size;\n\tchar *hex_data_str = NULL;\n\tuint16_t cur_hex_data_size;\n\tsize_t hex_pos = 0;\n\tuint8_t *hex_data = NULL;\n\n\tnew = ldns_rr_new();\n\n\towner = LDNS_XMALLOC(char, LDNS_MAX_DOMAINLEN + 1);\n\tttl = LDNS_XMALLOC(char, LDNS_TTL_DATALEN);\n\tclas = LDNS_XMALLOC(char, LDNS_SYNTAX_DATALEN);\n\trdata = LDNS_XMALLOC(char, LDNS_MAX_PACKETLEN + 1);\n\trr_buf = LDNS_MALLOC(ldns_buffer);\n\trd_buf = LDNS_MALLOC(ldns_buffer);\n\trd = LDNS_XMALLOC(char, LDNS_MAX_RDFLEN);\n\txtok = LDNS_XMALLOC(char, LDNS_MAX_RDFLEN);\n\tif (rr_buf) {\n\t\trr_buf->_data = NULL;\n\t}\n\tif (rd_buf) {\n\t\trd_buf->_data = NULL;\n\t}\n\tif (!new || !owner || !ttl || !clas || !rdata ||\n\t\t\t!rr_buf || !rd_buf || !rd || !xtok) {\n\n\t\tgoto memerror;\n\t}\n\n\tldns_buffer_new_frm_data(rr_buf, (char*)str, strlen(str));\n\n\t/* split the rr in its parts -1 signals trouble */\n\tif (ldns_bget_token(rr_buf, owner, \"\\t\\n \", LDNS_MAX_DOMAINLEN) == -1){\n\n\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\tgoto error;\n\t}\n\n\tif (ldns_bget_token(rr_buf, ttl, \"\\t\\n \", LDNS_TTL_DATALEN) == -1) {\n\n\t\tstatus = LDNS_STATUS_SYNTAX_TTL_ERR;\n\t\tgoto error;\n\t}\n\tttl_val = (uint32_t) ldns_str2period(ttl, &endptr);\n\n\tif (strlen(ttl) > 0 && !isdigit((int) ttl[0])) {\n\t\t/* ah, it's not there or something */\n\t\tif (default_ttl == 0) {\n\t\t\tttl_val = LDNS_DEFAULT_TTL;\n\t\t} else {\n\t\t\tttl_val = default_ttl;\n\t\t}\n\t\t/* we not ASSUMING the TTL is missing and that\n\t\t * the rest of the RR is still there. That is\n\t\t * CLASS TYPE RDATA\n\t\t * so ttl value we read is actually the class\n\t\t */\n\t\tclas_val = ldns_get_rr_class_by_name(ttl);\n\t\t/* class can be left out too, assume IN, current\n\t\t * token must be type\n\t\t */\n\t\tif (clas_val == 0) {\n\t\t\tclas_val = LDNS_RR_CLASS_IN;\n\t\t\ttype_sz = strlen(ttl) + 1;\n\t\t\ttype = LDNS_XMALLOC(char, type_sz);\n\t\t\tif (!type) {\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t\tstrlcpy(type, ttl, type_sz);\n\t\t}\n\t} else {\n\t\tif (-1 == ldns_bget_token(\n\t\t\t\trr_buf, clas, \"\\t\\n \", LDNS_SYNTAX_DATALEN)) {\n\n\t\t\tstatus = LDNS_STATUS_SYNTAX_CLASS_ERR;\n\t\t\tgoto error;\n\t\t}\n\t\tclas_val = ldns_get_rr_class_by_name(clas);\n\t\t/* class can be left out too, assume IN, current\n\t\t * token must be type\n\t\t */\n\t\tif (clas_val == 0) {\n\t\t\tclas_val = LDNS_RR_CLASS_IN;\n\t\t\ttype_sz = strlen(clas) + 1;\n\t\t\ttype = LDNS_XMALLOC(char, type_sz);\n\t\t\tif (!type) {\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t\tstrlcpy(type, clas, type_sz);\n\t\t}\n\t}\n\t/* the rest should still be waiting for us */\n\n\tif (!type) {\n\t\ttype = LDNS_XMALLOC(char, LDNS_SYNTAX_DATALEN);\n\t\tif (!type) {\n\t\t\tgoto memerror;\n\t\t}\n\t\tif (-1 == ldns_bget_token(\n\t\t\t\trr_buf, type, \"\\t\\n \", LDNS_SYNTAX_DATALEN)) {\n\n\t\t\tstatus = LDNS_STATUS_SYNTAX_TYPE_ERR;\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tif (ldns_bget_token(rr_buf, rdata, \"\\0\", LDNS_MAX_PACKETLEN) == -1) {\n\t\t/* apparently we are done, and it's only a question RR\n\t\t * so do not set status and go to ldnserror here\n\t\t */\n\t}\n\tldns_buffer_new_frm_data(rd_buf, rdata, strlen(rdata));\n\n\tif (strlen(owner) <= 1 && strncmp(owner, \"@\", 1) == 0) {\n\t\tif (origin) {\n\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(origin));\n\t\t} else if (prev && *prev) {\n\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(*prev));\n\t\t} else {\n\t\t\t/* default to root */\n\t\t\tldns_rr_set_owner(new, ldns_dname_new_frm_str(\".\"));\n\t\t}\n\n\t\t/* @ also overrides prev */\n\t\tif (prev) {\n\t\t\tldns_rdf_deep_free(*prev);\n\t\t\t*prev = ldns_rdf_clone(ldns_rr_owner(new));\n\t\t\tif (!*prev) {\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (strlen(owner) == 0) {\n\t\t\t/* no ownername was given, try prev, if that fails\n\t\t\t * origin, else default to root */\n\t\t\tif (prev && *prev) {\n\t\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(*prev));\n\t\t\t} else if (origin) {\n\t\t\t\tldns_rr_set_owner(new, ldns_rdf_clone(origin));\n\t\t\t} else {\n\t\t\t\tldns_rr_set_owner(new,\n\t\t\t\t\t\tldns_dname_new_frm_str(\".\"));\n\t\t\t}\n\t\t\tif(!ldns_rr_owner(new)) {\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t} else {\n\t\t\towner_dname = ldns_dname_new_frm_str(owner);\n\t\t\tif (!owner_dname) {\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\t\t\tgoto error;\n\t\t\t}\n\n\t\t\tldns_rr_set_owner(new, owner_dname);\n\t\t\tif (!ldns_dname_str_absolute(owner) && origin) {\n\t\t\t\tif(ldns_dname_cat(ldns_rr_owner(new), origin)\n\t\t\t\t\t\t!= LDNS_STATUS_OK) {\n\n\t\t\t\t\tstatus = LDNS_STATUS_SYNTAX_ERR;\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (prev) {\n\t\t\t\tldns_rdf_deep_free(*prev);\n\t\t\t\t*prev = ldns_rdf_clone(ldns_rr_owner(new));\n\t\t\t\tif (!*prev) {\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tLDNS_FREE(owner);\n\n\tldns_rr_set_question(new, question);\n\n\tldns_rr_set_ttl(new, ttl_val);\n\tLDNS_FREE(ttl);\n\n\tldns_rr_set_class(new, clas_val);\n\tLDNS_FREE(clas);\n\n\trr_type = ldns_get_rr_type_by_name(type);\n\tLDNS_FREE(type);\n\n\tdesc = ldns_rr_descript((uint16_t)rr_type);\n\tldns_rr_set_type(new, rr_type);\n\tif (desc) {\n\t\t/* only the rdata remains */\n\t\tr_max = ldns_rr_descriptor_maximum(desc);\n\t\tr_min = ldns_rr_descriptor_minimum(desc);\n\t} else {\n\t\tr_min = 0;\n\t\tr_max = 1;\n\t}\n\n\tfor (done = false, r_cnt = 0; !done && r_cnt < r_max; r_cnt++) {\n\t\tquoted = false;\n\n\t\tswitch (ldns_rr_descriptor_field_type(desc, r_cnt)) {\n\t\tcase LDNS_RDF_TYPE_B64 :\n\t\tcase LDNS_RDF_TYPE_HEX : /* These rdf types may con- */\n\t\tcase LDNS_RDF_TYPE_LOC : /* tain whitespace, only if */\n\t\tcase LDNS_RDF_TYPE_WKS : /* it is the last rd field. */\n\t\tcase LDNS_RDF_TYPE_IPSECKEY :\n\t\tcase LDNS_RDF_TYPE_AMTRELAY :\n\t\tcase LDNS_RDF_TYPE_NSEC :\tif (r_cnt == r_max - 1) {\n\t\t\t\t\t\t\tdelimiters = \"\\n\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* fallthrough */\n\t\tdefault :\tdelimiters = \"\\n\\t \"; \n\t\t}\n\n\t\tif (ldns_rdf_type_maybe_quoted(\n\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\tdesc, r_cnt)) &&\n\t\t\t\tldns_buffer_remaining(rd_buf) > 0){\n\n\t\t\t/* skip spaces */\n\t\t\twhile (sldns_buffer_remaining(strbuf) > 0 &&\n\t\t\t\t*(ldns_buffer_current(rd_buf)) == ' ') {\n\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t}\n\n\t\t\tif (sldns_buffer_remaining(strbuf) > 0 &&\n\t\t\t\t*(ldns_buffer_current(rd_buf)) == '\\\"') {\n\t\t\t\tdelimiters = \"\\\"\\0\";\n\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t\tquoted = true;\n\t\t\t}\n\t\t\tif (!quoted && ldns_rr_descriptor_field_type(desc, r_cnt)\n\t\t\t\t\t== LDNS_RDF_TYPE_LONG_STR) {\n\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\n\t\t/* because number of fields can be variable, we can't rely on\n\t\t * _maximum() only\n\t\t */\n\n\t\t/* skip spaces */\n\t\twhile (ldns_buffer_position(rd_buf) < ldns_buffer_limit(rd_buf)\n\t\t\t\t&& *(ldns_buffer_current(rd_buf)) == ' '\n\t\t\t\t&& !quoted) {\n\n\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t}\n\n\t\tpre_data_pos = ldns_buffer_position(rd_buf);\n\t\tif (-1 == (c = ldns_bget_token(\n\t\t\t\trd_buf, rd, delimiters, LDNS_MAX_RDFLEN))) {\n\n\t\t\tdone = true;\n\t\t\t(void)done; /* we're breaking, so done not read anymore */\n\t\t\tbreak;\n\t\t}\n\t\t/* hmmz, rfc3597 specifies that any type can be represented \n\t\t * with \\# method, which can contain spaces...\n\t\t * it does specify size though...\n\t\t */\n\t\trd_strlen = strlen(rd);\n\n\t\t/* unknown RR data */\n\t\tif (strncmp(rd, \"\\\\#\", 2) == 0 && !quoted &&\n\t\t\t\t(rd_strlen == 2 || rd[2]==' ')) {\n\n\t\t\twas_unknown_rr_format = 1;\n\t\t\t/* go back to before \\#\n\t\t\t * and skip it while setting delimiters better\n\t\t\t */\n\t\t\tldns_buffer_set_position(rd_buf, pre_data_pos);\n\t\t\tdelimiters = \"\\n\\t \";\n\t\t\t(void)ldns_bget_token(rd_buf, rd,\n\t\t\t\t\tdelimiters, LDNS_MAX_RDFLEN);\n\t\t\t/* read rdata octet length */\n\t\t\tc = ldns_bget_token(rd_buf, rd,\n\t\t\t\t\tdelimiters, LDNS_MAX_RDFLEN);\n\t\t\tif (c == -1) {\n\t\t\t\t/* something goes very wrong here */\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\thex_data_size = (uint16_t) atoi(rd);\n\t\t\t/* copy hex chars into hex str (2 chars per byte) */\n\t\t\thex_data_str = LDNS_XMALLOC(char, 2*hex_data_size + 1);\n\t\t\tif (!hex_data_str) {\n\t\t\t\t/* malloc error */\n\t\t\t\tgoto memerror;\n\t\t\t}\n\t\t\tcur_hex_data_size = 0;\n\t\t\twhile(cur_hex_data_size < 2 * hex_data_size) {\n\t\t\t\tc = ldns_bget_token(rd_buf, rd,\n\t\t\t\t\t\tdelimiters, LDNS_MAX_RDFLEN);\n\t\t\t\tif (c == -1) {\n\t\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\trd_strlen = strlen(rd);\n\t\t\t\tif ((size_t)cur_hex_data_size + rd_strlen >\n\t\t\t\t 2 * (size_t)hex_data_size) {\n\t\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tstrlcpy(hex_data_str + cur_hex_data_size, rd,\n\t\t\t\t\t\trd_strlen + 1);\n\n\t\t\t\tcur_hex_data_size += rd_strlen;\n\t\t\t}\n\t\t\thex_data_str[cur_hex_data_size] = '\\0';\n\n\t\t\t/* correct the rdf type */\n\t\t\t/* if *we* know the type, interpret it as wireformat */\n\t\t\tif (desc) {\n\t\t\t\thex_pos = 0;\n\t\t\t\thex_data =\n\t\t\t\t\tLDNS_XMALLOC(uint8_t, hex_data_size+2);\n\n\t\t\t\tif (!hex_data) {\n\t\t\t\t\tgoto memerror;\n\t\t\t\t}\n\t\t\t\tldns_write_uint16(hex_data, hex_data_size);\n\t\t\t\tldns_hexstring_to_data(\n\t\t\t\t\t\thex_data + 2, hex_data_str);\n\t\t\t\tstatus = ldns_wire2rdf(new, hex_data,\n\t\t\t\t\t\thex_data_size + 2, &hex_pos);\n\t\t\t\tif (status != LDNS_STATUS_OK) {\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tLDNS_FREE(hex_data);\n\t\t\t} else {\n\t\t\t\tr = ldns_rdf_new_frm_str(LDNS_RDF_TYPE_HEX,\n\t\t\t\t\t\thex_data_str);\n\t\t\t\tif (!r) {\n\t\t\t\t\tgoto memerror;\n\t\t\t\t}\n\t\t\t\tldns_rdf_set_type(r, LDNS_RDF_TYPE_UNKNOWN);\n\t\t\t\tif (!ldns_rr_push_rdf(new, r)) {\n\t\t\t\t\tgoto memerror;\n\t\t\t\t}\n\t\t\t}\n\t\t\tLDNS_FREE(hex_data_str);\n\n\t\t} else if(rd_strlen > 0 || quoted) {\n\t\t\t/* Normal RR */\n\t\t\tswitch(ldns_rr_descriptor_field_type(desc, r_cnt)) {\n\n\t\t\tcase LDNS_RDF_TYPE_HEX:\n\t\t\tcase LDNS_RDF_TYPE_B64:\n\t\t\t\t/* When this is the last rdata field, then the\n\t\t\t\t * rest should be read in (cause then these\n\t\t\t\t * rdf types may contain spaces).\n\t\t\t\t */\n\t\t\t\tif (r_cnt == r_max - 1) {\n\t\t\t\t\tc = ldns_bget_token(rd_buf, xtok,\n\t\t\t\t\t\t\t\"\\n\", LDNS_MAX_RDFLEN);\n\t\t\t\t\tif (c != -1) {\n\t\t\t\t\t\t(void) strncat(rd, xtok,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\t\t\t\tdesc, r_cnt), rd);\n\t\t\t\tbreak;\n\n\t\t\tcase LDNS_RDF_TYPE_HIP:\n\t\t\t\t/*\n\t\t\t\t * In presentation format this RDATA type has\n\t\t\t\t * three tokens: An algorithm byte, then a\n\t\t\t\t * variable length HIT (in hexbytes) and then\n\t\t\t\t * a variable length Public Key (in base64).\n\t\t\t\t *\n\t\t\t\t * We have just read the algorithm, so we need\n\t\t\t\t * two more tokens: HIT and Public Key.\n\t\t\t\t */\n\t\t\t\tdo {\n\t\t\t\t\t/* Read and append HIT */\n\t\t\t\t\tif (ldns_bget_token(rd_buf,\n\t\t\t\t\t\t\txtok, delimiters,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN) == -1)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t(void) strncat(rd, \" \",\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\t\t\t\t\t(void) strncat(rd, xtok,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\n\t\t\t\t\t/* Read and append Public Key*/\n\t\t\t\t\tif (ldns_bget_token(rd_buf,\n\t\t\t\t\t\t\txtok, delimiters,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN) == -1)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t(void) strncat(rd, \" \",\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\t\t\t\t\t(void) strncat(rd, xtok,\n\t\t\t\t\t\t\tLDNS_MAX_RDFLEN -\n\t\t\t\t\t\t\tstrlen(rd) - 1);\n\t\t\t\t} while (false);\n\n\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\t\t\t\tdesc, r_cnt), rd);\n\t\t\t\tbreak;\n\n\t\t\tcase LDNS_RDF_TYPE_DNAME:\n\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\t\t\t\tdesc, r_cnt), rd);\n\n\t\t\t\t/* check if the origin should be used\n\t\t\t\t * or concatenated\n\t\t\t\t */\n\t\t\t\tif (r && ldns_rdf_size(r) > 1 &&\n\t\t\t\t\t\tldns_rdf_data(r)[0] == 1 &&\n\t\t\t\t\t\tldns_rdf_data(r)[1] == '@') {\n\n\t\t\t\t\tldns_rdf_deep_free(r);\n\n\t\t\t\t\tr = origin ? ldns_rdf_clone(origin)\n\n\t\t\t\t\t : ( rr_type == LDNS_RR_TYPE_SOA ?\n\n\t\t\t\t\t ldns_rdf_clone(\n\t\t\t\t\t\t ldns_rr_owner(new))\n\n\t\t\t\t\t : ldns_rdf_new_frm_str(\n\t\t\t\t\t\t LDNS_RDF_TYPE_DNAME, \".\")\n\t\t\t\t\t );\n\n\t\t\t\t} else if (r && rd_strlen >= 1 && origin &&\n\t\t\t\t\t\t!ldns_dname_str_absolute(rd)) {\n\n\t\t\t\t\tstatus = ldns_dname_cat(r, origin);\n\t\t\t\t\tif (status != LDNS_STATUS_OK) {\n\t\t\t\t\t\tgoto error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tr = ldns_rdf_new_frm_str(\n\t\t\t\t\t\tldns_rr_descriptor_field_type(\n\t\t\t\t\t\t\tdesc, r_cnt), rd);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!r) {\n\t\t\t\tstatus = LDNS_STATUS_SYNTAX_RDATA_ERR;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tldns_rr_push_rdf(new, r);\n\t\t}\n\t\tif (quoted) {\n\t\t\tif (ldns_buffer_available(rd_buf, 1)) {\n\t\t\t\tldns_buffer_skip(rd_buf, 1);\n\t\t\t} else {\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t}\n\n\t} /* for (done = false, r_cnt = 0; !done && r_cnt < r_max; r_cnt++) */\n\tLDNS_FREE(rd);\n\tLDNS_FREE(xtok);\n\tldns_buffer_free(rr_buf);\n\tLDNS_FREE(rdata);\n\tif (ldns_buffer_remaining(rd_buf) > 0) {\n\t\tldns_buffer_free(rd_buf);\n\t\tldns_rr_free(new);\n\t\treturn LDNS_STATUS_SYNTAX_SUPERFLUOUS_TEXT_ERR;\n\t}\n\tldns_buffer_free(rd_buf);\n\n\tif (!question && desc && !was_unknown_rr_format &&\n\t\t\tldns_rr_rd_count(new) < r_min) {\n\n\t\tldns_rr_free(new);\n\t\treturn LDNS_STATUS_SYNTAX_MISSING_VALUE_ERR;\n\t}\n\n\tif (newrr) {\n\t\t*newrr = new;\n\t} else {\n\t\t/* Maybe the caller just wanted to see if it would parse? */\n\t\tldns_rr_free(new);\n\t}\n\treturn LDNS_STATUS_OK;\n\nmemerror:\n\tstatus = LDNS_STATUS_MEM_ERR;\nerror:\n\tif (rd_buf && rd_buf->_data) {\n\t\tldns_buffer_free(rd_buf);\n\t} else {\n\t\tLDNS_FREE(rd_buf);\n\t}\n\tif (rr_buf && rr_buf->_data) {\n\t\tldns_buffer_free(rr_buf);\n\t} else {\n\t\tLDNS_FREE(rr_buf);\n\t}\n\tLDNS_FREE(type);\n\tLDNS_FREE(owner);\n\tLDNS_FREE(ttl);\n\tLDNS_FREE(clas);\n\tLDNS_FREE(hex_data);\n\tLDNS_FREE(hex_data_str);\n\tLDNS_FREE(xtok);\n\tLDNS_FREE(rd);\n\tLDNS_FREE(rdata);\n\tldns_rr_free(new);\n\treturn status;\n}", "project": "ldns", "hash": 35425557283156952799065220793970367868, "size": 553, "commit_id": "15d96206996bea969fbc918eb0a4a346f514b9f3", "message": "* bugfix #70: heap Out-of-bound Read vulnerability in\n rr_frm_str_internal reported by pokerfacett.", "target": 0, "dataset": "other", "idx": 439914}
  851. {"func": " Classifier (const char *&ptr, int size)\n {\n if (size <= 0) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (truncated rule).\");\n \n {\n char suffix[Name::SIZE];\n memset (suffix, 0, Name::SIZE);\n Xdr::read<CharPtrIO> (ptr, std::min(size, Name::SIZE-1), suffix);\n _suffix = std::string(suffix);\n }\n\n if (static_cast<size_t>(size) < _suffix.length() + 1 + 2*Xdr::size<char>()) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (truncated rule).\");\n\n char value;\n Xdr::read<CharPtrIO> (ptr, value);\n\n _cscIdx = (int)(value >> 4) - 1;\n if (_cscIdx < -1 || _cscIdx >= 3) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt cscIdx rule).\");\n\n _scheme = (CompressorScheme)((value >> 2) & 3);\n if (_scheme < 0 || _scheme >= NUM_COMPRESSOR_SCHEMES) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt scheme rule).\");\n\n _caseInsensitive = (value & 1 ? true : false);\n\n Xdr::read<CharPtrIO> (ptr, value);\n if (value < 0 || value >= NUM_PIXELTYPES) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt rule).\");\n _type = (PixelType)value;\n }", "project": "openexr", "hash": 286477158467248343403232113020885568232, "size": 38, "commit_id": "3eda5d70aba127bae9bd6bae9956fcf024b64031", "message": "fixes for DWA uncompress: sanity check unknown data reading, off-by-one error on max suffix string length\n\nSigned-off-by: Peter Hillman <peterh@wetafx.co.nz>", "target": 1, "dataset": "other", "idx": 210760}
  852. {"func": " Classifier (const char *&ptr, int size)\n {\n if (size <= 0) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (truncated rule).\");\n \n {\n // maximum length of string plus one byte for terminating NULL\n char suffix[Name::SIZE+1];\n memset (suffix, 0, Name::SIZE+1);\n Xdr::read<CharPtrIO> (ptr, std::min(size, Name::SIZE-1), suffix);\n _suffix = std::string(suffix);\n }\n\n if (static_cast<size_t>(size) < _suffix.length() + 1 + 2*Xdr::size<char>()) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (truncated rule).\");\n\n char value;\n Xdr::read<CharPtrIO> (ptr, value);\n\n _cscIdx = (int)(value >> 4) - 1;\n if (_cscIdx < -1 || _cscIdx >= 3) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt cscIdx rule).\");\n\n _scheme = (CompressorScheme)((value >> 2) & 3);\n if (_scheme < 0 || _scheme >= NUM_COMPRESSOR_SCHEMES) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt scheme rule).\");\n\n _caseInsensitive = (value & 1 ? true : false);\n\n Xdr::read<CharPtrIO> (ptr, value);\n if (value < 0 || value >= NUM_PIXELTYPES) \n throw IEX_NAMESPACE::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt rule).\");\n _type = (PixelType)value;\n }", "project": "openexr", "hash": 259403700882642134149486624904642429148, "size": 39, "commit_id": "3eda5d70aba127bae9bd6bae9956fcf024b64031", "message": "fixes for DWA uncompress: sanity check unknown data reading, off-by-one error on max suffix string length\n\nSigned-off-by: Peter Hillman <peterh@wetafx.co.nz>", "target": 0, "dataset": "other", "idx": 440093}
  853. {"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 if( dest.eDest!=priorOp ){\n int iCont, iBreak, iStart;\n assert( p->pEList );\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 \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; i<nCol; i++, apColl++){\n *apColl = multiSelectCollSeq(pParse, p, i);\n if( 0==*apColl ){\n *apColl = db->pDfltColl;\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": 129135244890151070904216177945464072400, "size": 342, "commit_id": "8428b3b437569338a9d1e10c4cd8154acbe33089", "message": "Continuation of [e2bddcd4c55ba3cb]: Add another spot where it is necessary\nto abort early due to prior errors in sqlite3WindowRewrite().\n\nFossilOrigin-Name: cba2a2a44cdf138a629109bb0ad088ed4ef67fc66bed3e0373554681a39615d2", "target": 1, "dataset": "other", "idx": 210816}
  854. {"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 if( dest.eDest!=priorOp ){\n int iCont, iBreak, iStart;\n assert( p->pEList );\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; i<nCol; i++, apColl++){\n *apColl = multiSelectCollSeq(pParse, p, i);\n if( 0==*apColl ){\n *apColl = db->pDfltColl;\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": 142655477716831857820189871529105126571, "size": 343, "commit_id": "8428b3b437569338a9d1e10c4cd8154acbe33089", "message": "Continuation of [e2bddcd4c55ba3cb]: Add another spot where it is necessary\nto abort early due to prior errors in sqlite3WindowRewrite().\n\nFossilOrigin-Name: cba2a2a44cdf138a629109bb0ad088ed4ef67fc66bed3e0373554681a39615d2", "target": 0, "dataset": "other", "idx": 440749}
  855. {"func": "static ssize_t usbip_sockfd_store(struct device *dev, struct device_attribute *attr,\n\t\t\t const char *buf, size_t count)\n{\n\tstruct stub_device *sdev = dev_get_drvdata(dev);\n\tint sockfd = 0;\n\tstruct socket *socket;\n\tint rv;\n\n\tif (!sdev) {\n\t\tdev_err(dev, \"sdev is null\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\trv = sscanf(buf, \"%d\", &sockfd);\n\tif (rv != 1)\n\t\treturn -EINVAL;\n\n\tif (sockfd != -1) {\n\t\tint err;\n\n\t\tdev_info(dev, \"stub up\\n\");\n\n\t\tspin_lock_irq(&sdev->ud.lock);\n\n\t\tif (sdev->ud.status != SDEV_ST_AVAILABLE) {\n\t\t\tdev_err(dev, \"not ready\\n\");\n\t\t\tgoto err;\n\t\t}\n\n\t\tsocket = sockfd_lookup(sockfd, &err);\n\t\tif (!socket) {\n\t\t\tdev_err(dev, \"failed to lookup sock\");\n\t\t\tgoto err;\n\t\t}\n\n\t\tif (socket->type != SOCK_STREAM) {\n\t\t\tdev_err(dev, \"Expecting SOCK_STREAM - found %d\",\n\t\t\t\tsocket->type);\n\t\t\tgoto sock_err;\n\t\t}\n\n\t\tsdev->ud.tcp_socket = socket;\n\t\tsdev->ud.sockfd = sockfd;\n\n\t\tspin_unlock_irq(&sdev->ud.lock);\n\n\t\tsdev->ud.tcp_rx = kthread_get_run(stub_rx_loop, &sdev->ud,\n\t\t\t\t\t\t \"stub_rx\");\n\t\tsdev->ud.tcp_tx = kthread_get_run(stub_tx_loop, &sdev->ud,\n\t\t\t\t\t\t \"stub_tx\");\n\n\t\tspin_lock_irq(&sdev->ud.lock);\n\t\tsdev->ud.status = SDEV_ST_USED;\n\t\tspin_unlock_irq(&sdev->ud.lock);\n\n\t} else {\n\t\tdev_info(dev, \"stub down\\n\");\n\n\t\tspin_lock_irq(&sdev->ud.lock);\n\t\tif (sdev->ud.status != SDEV_ST_USED)\n\t\t\tgoto err;\n\n\t\tspin_unlock_irq(&sdev->ud.lock);\n\n\t\tusbip_event_add(&sdev->ud, SDEV_EVENT_DOWN);\n\t}\n\n\treturn count;\n\nsock_err:\n\tsockfd_put(socket);\nerr:\n\tspin_unlock_irq(&sdev->ud.lock);\n\treturn -EINVAL;\n}", "project": "linux", "hash": 78418534195062063945792345058960368186, "size": 75, "commit_id": "9380afd6df70e24eacbdbde33afc6a3950965d22", "message": "usbip: fix stub_dev usbip_sockfd_store() races leading to gpf\n\nusbip_sockfd_store() is invoked when user requests attach (import)\ndetach (unimport) usb device from usbip host. vhci_hcd sends import\nrequest and usbip_sockfd_store() exports the device if it is free\nfor export.\n\nExport and unexport are governed by local state and shared state\n- Shared state (usbip device status, sockfd) - sockfd and Device\n status are used to determine if stub should be brought up or shut\n down.\n- Local state (tcp_socket, rx and tx thread task_struct ptrs)\n A valid tcp_socket controls rx and tx thread operations while the\n device is in exported state.\n- While the device is exported, device status is marked used and socket,\n sockfd, and thread pointers are valid.\n\nExport sequence (stub-up) includes validating the socket and creating\nreceive (rx) and transmit (tx) threads to talk to the client to provide\naccess to the exported device. rx and tx threads depends on local and\nshared state to be correct and in sync.\n\nUnexport (stub-down) sequence shuts the socket down and stops the rx and\ntx threads. Stub-down sequence relies on local and shared states to be\nin sync.\n\nThere are races in updating the local and shared status in the current\nstub-up sequence resulting in crashes. These stem from starting rx and\ntx threads before local and global state is updated correctly to be in\nsync.\n\n1. Doesn't handle kthread_create() error and saves invalid ptr in local\n state that drives rx and tx threads.\n2. Updates tcp_socket and sockfd, starts stub_rx and stub_tx threads\n before updating usbip_device status to SDEV_ST_USED. This opens up a\n race condition between the threads and usbip_sockfd_store() stub up\n and down handling.\n\nFix the above problems:\n- Stop using kthread_get_run() macro to create/start threads.\n- Create threads and get task struct reference.\n- Add kthread_create() failure handling and bail out.\n- Hold usbip_device lock to update local and shared states after\n creating rx and tx threads.\n- Update usbip_device status to SDEV_ST_USED.\n- Update usbip_device tcp_socket, sockfd, tcp_rx, and tcp_tx\n- Start threads after usbip_device (tcp_socket, sockfd, tcp_rx, tcp_tx,\n and status) is complete.\n\nCredit goes to syzbot and Tetsuo Handa for finding and root-causing the\nkthread_get_run() improper error handling problem and others. This is a\nhard problem to find and debug since the races aren't seen in a normal\ncase. Fuzzing forces the race window to be small enough for the\nkthread_get_run() error path bug and starting threads before updating the\nlocal and shared state bug in the stub-up sequence.\n\nTested with syzbot reproducer:\n- https://syzkaller.appspot.com/text?tag=ReproC&x=14801034d00000\n\nFixes: 9720b4bc76a83807 (\"staging/usbip: convert to kthread\")\nCc: stable@vger.kernel.org\nReported-by: syzbot <syzbot+a93fba6d384346a761e3@syzkaller.appspotmail.com>\nReported-by: syzbot <syzbot+bf1a360e305ee719e364@syzkaller.appspotmail.com>\nReported-by: syzbot <syzbot+95ce4b142579611ef0a9@syzkaller.appspotmail.com>\nReported-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>\nSigned-off-by: Shuah Khan <skhan@linuxfoundation.org>\nLink: https://lore.kernel.org/r/268a0668144d5ff36ec7d87fdfa90faf583b7ccc.1615171203.git.skhan@linuxfoundation.org\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 1, "dataset": "other", "idx": 210838}
  856. {"func": "static ssize_t usbip_sockfd_store(struct device *dev, struct device_attribute *attr,\n\t\t\t const char *buf, size_t count)\n{\n\tstruct stub_device *sdev = dev_get_drvdata(dev);\n\tint sockfd = 0;\n\tstruct socket *socket;\n\tint rv;\n\tstruct task_struct *tcp_rx = NULL;\n\tstruct task_struct *tcp_tx = NULL;\n\n\tif (!sdev) {\n\t\tdev_err(dev, \"sdev is null\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\trv = sscanf(buf, \"%d\", &sockfd);\n\tif (rv != 1)\n\t\treturn -EINVAL;\n\n\tif (sockfd != -1) {\n\t\tint err;\n\n\t\tdev_info(dev, \"stub up\\n\");\n\n\t\tspin_lock_irq(&sdev->ud.lock);\n\n\t\tif (sdev->ud.status != SDEV_ST_AVAILABLE) {\n\t\t\tdev_err(dev, \"not ready\\n\");\n\t\t\tgoto err;\n\t\t}\n\n\t\tsocket = sockfd_lookup(sockfd, &err);\n\t\tif (!socket) {\n\t\t\tdev_err(dev, \"failed to lookup sock\");\n\t\t\tgoto err;\n\t\t}\n\n\t\tif (socket->type != SOCK_STREAM) {\n\t\t\tdev_err(dev, \"Expecting SOCK_STREAM - found %d\",\n\t\t\t\tsocket->type);\n\t\t\tgoto sock_err;\n\t\t}\n\n\t\t/* unlock and create threads and get tasks */\n\t\tspin_unlock_irq(&sdev->ud.lock);\n\t\ttcp_rx = kthread_create(stub_rx_loop, &sdev->ud, \"stub_rx\");\n\t\tif (IS_ERR(tcp_rx)) {\n\t\t\tsockfd_put(socket);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\ttcp_tx = kthread_create(stub_tx_loop, &sdev->ud, \"stub_tx\");\n\t\tif (IS_ERR(tcp_tx)) {\n\t\t\tkthread_stop(tcp_rx);\n\t\t\tsockfd_put(socket);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\t/* get task structs now */\n\t\tget_task_struct(tcp_rx);\n\t\tget_task_struct(tcp_tx);\n\n\t\t/* lock and update sdev->ud state */\n\t\tspin_lock_irq(&sdev->ud.lock);\n\t\tsdev->ud.tcp_socket = socket;\n\t\tsdev->ud.sockfd = sockfd;\n\t\tsdev->ud.tcp_rx = tcp_rx;\n\t\tsdev->ud.tcp_tx = tcp_tx;\n\t\tsdev->ud.status = SDEV_ST_USED;\n\t\tspin_unlock_irq(&sdev->ud.lock);\n\n\t\twake_up_process(sdev->ud.tcp_rx);\n\t\twake_up_process(sdev->ud.tcp_tx);\n\n\t} else {\n\t\tdev_info(dev, \"stub down\\n\");\n\n\t\tspin_lock_irq(&sdev->ud.lock);\n\t\tif (sdev->ud.status != SDEV_ST_USED)\n\t\t\tgoto err;\n\n\t\tspin_unlock_irq(&sdev->ud.lock);\n\n\t\tusbip_event_add(&sdev->ud, SDEV_EVENT_DOWN);\n\t}\n\n\treturn count;\n\nsock_err:\n\tsockfd_put(socket);\nerr:\n\tspin_unlock_irq(&sdev->ud.lock);\n\treturn -EINVAL;\n}", "project": "linux", "hash": 151624572692064030266631166703937205385, "size": 93, "commit_id": "9380afd6df70e24eacbdbde33afc6a3950965d22", "message": "usbip: fix stub_dev usbip_sockfd_store() races leading to gpf\n\nusbip_sockfd_store() is invoked when user requests attach (import)\ndetach (unimport) usb device from usbip host. vhci_hcd sends import\nrequest and usbip_sockfd_store() exports the device if it is free\nfor export.\n\nExport and unexport are governed by local state and shared state\n- Shared state (usbip device status, sockfd) - sockfd and Device\n status are used to determine if stub should be brought up or shut\n down.\n- Local state (tcp_socket, rx and tx thread task_struct ptrs)\n A valid tcp_socket controls rx and tx thread operations while the\n device is in exported state.\n- While the device is exported, device status is marked used and socket,\n sockfd, and thread pointers are valid.\n\nExport sequence (stub-up) includes validating the socket and creating\nreceive (rx) and transmit (tx) threads to talk to the client to provide\naccess to the exported device. rx and tx threads depends on local and\nshared state to be correct and in sync.\n\nUnexport (stub-down) sequence shuts the socket down and stops the rx and\ntx threads. Stub-down sequence relies on local and shared states to be\nin sync.\n\nThere are races in updating the local and shared status in the current\nstub-up sequence resulting in crashes. These stem from starting rx and\ntx threads before local and global state is updated correctly to be in\nsync.\n\n1. Doesn't handle kthread_create() error and saves invalid ptr in local\n state that drives rx and tx threads.\n2. Updates tcp_socket and sockfd, starts stub_rx and stub_tx threads\n before updating usbip_device status to SDEV_ST_USED. This opens up a\n race condition between the threads and usbip_sockfd_store() stub up\n and down handling.\n\nFix the above problems:\n- Stop using kthread_get_run() macro to create/start threads.\n- Create threads and get task struct reference.\n- Add kthread_create() failure handling and bail out.\n- Hold usbip_device lock to update local and shared states after\n creating rx and tx threads.\n- Update usbip_device status to SDEV_ST_USED.\n- Update usbip_device tcp_socket, sockfd, tcp_rx, and tcp_tx\n- Start threads after usbip_device (tcp_socket, sockfd, tcp_rx, tcp_tx,\n and status) is complete.\n\nCredit goes to syzbot and Tetsuo Handa for finding and root-causing the\nkthread_get_run() improper error handling problem and others. This is a\nhard problem to find and debug since the races aren't seen in a normal\ncase. Fuzzing forces the race window to be small enough for the\nkthread_get_run() error path bug and starting threads before updating the\nlocal and shared state bug in the stub-up sequence.\n\nTested with syzbot reproducer:\n- https://syzkaller.appspot.com/text?tag=ReproC&x=14801034d00000\n\nFixes: 9720b4bc76a83807 (\"staging/usbip: convert to kthread\")\nCc: stable@vger.kernel.org\nReported-by: syzbot <syzbot+a93fba6d384346a761e3@syzkaller.appspotmail.com>\nReported-by: syzbot <syzbot+bf1a360e305ee719e364@syzkaller.appspotmail.com>\nReported-by: syzbot <syzbot+95ce4b142579611ef0a9@syzkaller.appspotmail.com>\nReported-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>\nSigned-off-by: Shuah Khan <skhan@linuxfoundation.org>\nLink: https://lore.kernel.org/r/268a0668144d5ff36ec7d87fdfa90faf583b7ccc.1615171203.git.skhan@linuxfoundation.org\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 0, "dataset": "other", "idx": 440929}
  857. {"func": "static struct socket *get_raw_socket(int fd)\n{\n\tstruct {\n\t\tstruct sockaddr_ll sa;\n\t\tchar buf[MAX_ADDR_LEN];\n\t} uaddr;\n\tint r;\n\tstruct socket *sock = sockfd_lookup(fd, &r);\n\n\tif (!sock)\n\t\treturn ERR_PTR(-ENOTSOCK);\n\n\t/* Parameter checking */\n\tif (sock->sk->sk_type != SOCK_RAW) {\n\t\tr = -ESOCKTNOSUPPORT;\n\t\tgoto err;\n\t}\n\n\tr = sock->ops->getname(sock, (struct sockaddr *)&uaddr.sa, 0);\n\tif (r < 0)\n\t\tgoto err;\n\n\tif (uaddr.sa.sll_family != AF_PACKET) {\n\t\tr = -EPFNOSUPPORT;\n\t\tgoto err;\n\t}\n\treturn sock;\nerr:\n\tsockfd_put(sock);\n\treturn ERR_PTR(r);\n}", "project": "linux", "hash": 238781874818479014817245249246228980971, "size": 31, "commit_id": "42d84c8490f9f0931786f1623191fcab397c3d64", "message": "vhost: Check docket sk_family instead of call getname\n\nDoing so, we save one call to get data we already have in the struct.\n\nAlso, since there is no guarantee that getname use sockaddr_ll\nparameter beyond its size, we add a little bit of security here.\nIt should do not do beyond MAX_ADDR_LEN, but syzbot found that\nax25_getname writes more (72 bytes, the size of full_sockaddr_ax25,\nversus 20 + 32 bytes of sockaddr_ll + MAX_ADDR_LEN in syzbot repro).\n\nFixes: 3a4d5c94e9593 (\"vhost_net: a kernel-level virtio server\")\nReported-by: syzbot+f2a62d07a5198c819c7b@syzkaller.appspotmail.com\nSigned-off-by: Eugenio P\u00e9rez <eperezma@redhat.com>\nAcked-by: Michael S. Tsirkin <mst@redhat.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 1, "dataset": "other", "idx": 210873}
  858. {"func": "static struct socket *get_raw_socket(int fd)\n{\n\tint r;\n\tstruct socket *sock = sockfd_lookup(fd, &r);\n\n\tif (!sock)\n\t\treturn ERR_PTR(-ENOTSOCK);\n\n\t/* Parameter checking */\n\tif (sock->sk->sk_type != SOCK_RAW) {\n\t\tr = -ESOCKTNOSUPPORT;\n\t\tgoto err;\n\t}\n\n\tif (sock->sk->sk_family != AF_PACKET) {\n\t\tr = -EPFNOSUPPORT;\n\t\tgoto err;\n\t}\n\treturn sock;\nerr:\n\tsockfd_put(sock);\n\treturn ERR_PTR(r);\n}", "project": "linux", "hash": 206714559947468791292926111562093878142, "size": 23, "commit_id": "42d84c8490f9f0931786f1623191fcab397c3d64", "message": "vhost: Check docket sk_family instead of call getname\n\nDoing so, we save one call to get data we already have in the struct.\n\nAlso, since there is no guarantee that getname use sockaddr_ll\nparameter beyond its size, we add a little bit of security here.\nIt should do not do beyond MAX_ADDR_LEN, but syzbot found that\nax25_getname writes more (72 bytes, the size of full_sockaddr_ax25,\nversus 20 + 32 bytes of sockaddr_ll + MAX_ADDR_LEN in syzbot repro).\n\nFixes: 3a4d5c94e9593 (\"vhost_net: a kernel-level virtio server\")\nReported-by: syzbot+f2a62d07a5198c819c7b@syzkaller.appspotmail.com\nSigned-off-by: Eugenio P\u00e9rez <eperezma@redhat.com>\nAcked-by: Michael S. Tsirkin <mst@redhat.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 0, "dataset": "other", "idx": 441966}
  859. {"func": "mwifiex_cmd_802_11_ad_hoc_start(struct mwifiex_private *priv,\n\t\t\t\tstruct host_cmd_ds_command *cmd,\n\t\t\t\tstruct cfg80211_ssid *req_ssid)\n{\n\tint rsn_ie_len = 0;\n\tstruct mwifiex_adapter *adapter = priv->adapter;\n\tstruct host_cmd_ds_802_11_ad_hoc_start *adhoc_start =\n\t\t&cmd->params.adhoc_start;\n\tstruct mwifiex_bssdescriptor *bss_desc;\n\tu32 cmd_append_size = 0;\n\tu32 i;\n\tu16 tmp_cap;\n\tstruct mwifiex_ie_types_chan_list_param_set *chan_tlv;\n\tu8 radio_type;\n\n\tstruct mwifiex_ie_types_htcap *ht_cap;\n\tstruct mwifiex_ie_types_htinfo *ht_info;\n\tu8 *pos = (u8 *) adhoc_start +\n\t\t\tsizeof(struct host_cmd_ds_802_11_ad_hoc_start);\n\n\tif (!adapter)\n\t\treturn -1;\n\n\tcmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_START);\n\n\tbss_desc = &priv->curr_bss_params.bss_descriptor;\n\tpriv->attempted_bss_desc = bss_desc;\n\n\t/*\n\t * Fill in the parameters for 2 data structures:\n\t * 1. struct host_cmd_ds_802_11_ad_hoc_start command\n\t * 2. bss_desc\n\t * Driver will fill up SSID, bss_mode,IBSS param, Physical Param,\n\t * probe delay, and Cap info.\n\t * Firmware will fill up beacon period, Basic rates\n\t * and operational rates.\n\t */\n\n\tmemset(adhoc_start->ssid, 0, IEEE80211_MAX_SSID_LEN);\n\n\tmemcpy(adhoc_start->ssid, req_ssid->ssid, req_ssid->ssid_len);\n\n\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: SSID = %s\\n\",\n\t\t adhoc_start->ssid);\n\n\tmemset(bss_desc->ssid.ssid, 0, IEEE80211_MAX_SSID_LEN);\n\tmemcpy(bss_desc->ssid.ssid, req_ssid->ssid, req_ssid->ssid_len);\n\n\tbss_desc->ssid.ssid_len = req_ssid->ssid_len;\n\n\t/* Set the BSS mode */\n\tadhoc_start->bss_mode = HostCmd_BSS_MODE_IBSS;\n\tbss_desc->bss_mode = NL80211_IFTYPE_ADHOC;\n\tadhoc_start->beacon_period = cpu_to_le16(priv->beacon_period);\n\tbss_desc->beacon_period = priv->beacon_period;\n\n\t/* Set Physical param set */\n/* Parameter IE Id */\n#define DS_PARA_IE_ID 3\n/* Parameter IE length */\n#define DS_PARA_IE_LEN 1\n\n\tadhoc_start->phy_param_set.ds_param_set.element_id = DS_PARA_IE_ID;\n\tadhoc_start->phy_param_set.ds_param_set.len = DS_PARA_IE_LEN;\n\n\tif (!mwifiex_get_cfp(priv, adapter->adhoc_start_band,\n\t\t\t (u16) priv->adhoc_channel, 0)) {\n\t\tstruct mwifiex_chan_freq_power *cfp;\n\t\tcfp = mwifiex_get_cfp(priv, adapter->adhoc_start_band,\n\t\t\t\t FIRST_VALID_CHANNEL, 0);\n\t\tif (cfp)\n\t\t\tpriv->adhoc_channel = (u8) cfp->channel;\n\t}\n\n\tif (!priv->adhoc_channel) {\n\t\tmwifiex_dbg(adapter, ERROR,\n\t\t\t \"ADHOC_S_CMD: adhoc_channel cannot be 0\\n\");\n\t\treturn -1;\n\t}\n\n\tmwifiex_dbg(adapter, INFO,\n\t\t \"info: ADHOC_S_CMD: creating ADHOC on channel %d\\n\",\n\t\t priv->adhoc_channel);\n\n\tpriv->curr_bss_params.bss_descriptor.channel = priv->adhoc_channel;\n\tpriv->curr_bss_params.band = adapter->adhoc_start_band;\n\n\tbss_desc->channel = priv->adhoc_channel;\n\tadhoc_start->phy_param_set.ds_param_set.current_chan =\n\t\tpriv->adhoc_channel;\n\n\tmemcpy(&bss_desc->phy_param_set, &adhoc_start->phy_param_set,\n\t sizeof(union ieee_types_phy_param_set));\n\n\t/* Set IBSS param set */\n/* IBSS parameter IE Id */\n#define IBSS_PARA_IE_ID 6\n/* IBSS parameter IE length */\n#define IBSS_PARA_IE_LEN 2\n\n\tadhoc_start->ss_param_set.ibss_param_set.element_id = IBSS_PARA_IE_ID;\n\tadhoc_start->ss_param_set.ibss_param_set.len = IBSS_PARA_IE_LEN;\n\tadhoc_start->ss_param_set.ibss_param_set.atim_window\n\t\t\t\t\t= cpu_to_le16(priv->atim_window);\n\tmemcpy(&bss_desc->ss_param_set, &adhoc_start->ss_param_set,\n\t sizeof(union ieee_types_ss_param_set));\n\n\t/* Set Capability info */\n\tbss_desc->cap_info_bitmap |= WLAN_CAPABILITY_IBSS;\n\ttmp_cap = WLAN_CAPABILITY_IBSS;\n\n\t/* Set up privacy in bss_desc */\n\tif (priv->sec_info.encryption_mode) {\n\t\t/* Ad-Hoc capability privacy on */\n\t\tmwifiex_dbg(adapter, INFO,\n\t\t\t \"info: ADHOC_S_CMD: wep_status set privacy to WEP\\n\");\n\t\tbss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP;\n\t\ttmp_cap |= WLAN_CAPABILITY_PRIVACY;\n\t} else {\n\t\tmwifiex_dbg(adapter, INFO,\n\t\t\t \"info: ADHOC_S_CMD: wep_status NOT set,\\t\"\n\t\t\t \"setting privacy to ACCEPT ALL\\n\");\n\t\tbss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL;\n\t}\n\n\tmemset(adhoc_start->data_rate, 0, sizeof(adhoc_start->data_rate));\n\tmwifiex_get_active_data_rates(priv, adhoc_start->data_rate);\n\tif ((adapter->adhoc_start_band & BAND_G) &&\n\t (priv->curr_pkt_filter & HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON)) {\n\t\tif (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL,\n\t\t\t\t HostCmd_ACT_GEN_SET, 0,\n\t\t\t\t &priv->curr_pkt_filter, false)) {\n\t\t\tmwifiex_dbg(adapter, ERROR,\n\t\t\t\t \"ADHOC_S_CMD: G Protection config failed\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\t/* Find the last non zero */\n\tfor (i = 0; i < sizeof(adhoc_start->data_rate); i++)\n\t\tif (!adhoc_start->data_rate[i])\n\t\t\tbreak;\n\n\tpriv->curr_bss_params.num_of_rates = i;\n\n\t/* Copy the ad-hoc creating rates into Current BSS rate structure */\n\tmemcpy(&priv->curr_bss_params.data_rates,\n\t &adhoc_start->data_rate, priv->curr_bss_params.num_of_rates);\n\n\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: rates=%4ph\\n\",\n\t\t adhoc_start->data_rate);\n\n\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: AD-HOC Start command is ready\\n\");\n\n\tif (IS_SUPPORT_MULTI_BANDS(adapter)) {\n\t\t/* Append a channel TLV */\n\t\tchan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos;\n\t\tchan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);\n\t\tchan_tlv->header.len =\n\t\t\tcpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set));\n\n\t\tmemset(chan_tlv->chan_scan_param, 0x00,\n\t\t sizeof(struct mwifiex_chan_scan_param_set));\n\t\tchan_tlv->chan_scan_param[0].chan_number =\n\t\t\t(u8) priv->curr_bss_params.bss_descriptor.channel;\n\n\t\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: TLV Chan = %d\\n\",\n\t\t\t chan_tlv->chan_scan_param[0].chan_number);\n\n\t\tchan_tlv->chan_scan_param[0].radio_type\n\t\t = mwifiex_band_to_radio_type(priv->curr_bss_params.band);\n\t\tif (adapter->adhoc_start_band & BAND_GN ||\n\t\t adapter->adhoc_start_band & BAND_AN) {\n\t\t\tif (adapter->sec_chan_offset ==\n\t\t\t\t\t IEEE80211_HT_PARAM_CHA_SEC_ABOVE)\n\t\t\t\tchan_tlv->chan_scan_param[0].radio_type |=\n\t\t\t\t\t(IEEE80211_HT_PARAM_CHA_SEC_ABOVE << 4);\n\t\t\telse if (adapter->sec_chan_offset ==\n\t\t\t\t\t IEEE80211_HT_PARAM_CHA_SEC_BELOW)\n\t\t\t\tchan_tlv->chan_scan_param[0].radio_type |=\n\t\t\t\t\t(IEEE80211_HT_PARAM_CHA_SEC_BELOW << 4);\n\t\t}\n\t\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: TLV Band = %d\\n\",\n\t\t\t chan_tlv->chan_scan_param[0].radio_type);\n\t\tpos += sizeof(chan_tlv->header) +\n\t\t\tsizeof(struct mwifiex_chan_scan_param_set);\n\t\tcmd_append_size +=\n\t\t\tsizeof(chan_tlv->header) +\n\t\t\tsizeof(struct mwifiex_chan_scan_param_set);\n\t}\n\n\t/* Append vendor specific IE TLV */\n\tcmd_append_size += mwifiex_cmd_append_vsie_tlv(priv,\n\t\t\t\tMWIFIEX_VSIE_MASK_ADHOC, &pos);\n\n\tif (priv->sec_info.wpa_enabled) {\n\t\trsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos);\n\t\tif (rsn_ie_len == -1)\n\t\t\treturn -1;\n\t\tcmd_append_size += rsn_ie_len;\n\t}\n\n\tif (adapter->adhoc_11n_enabled) {\n\t\t/* Fill HT CAPABILITY */\n\t\tht_cap = (struct mwifiex_ie_types_htcap *) pos;\n\t\tmemset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap));\n\t\tht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY);\n\t\tht_cap->header.len =\n\t\t cpu_to_le16(sizeof(struct ieee80211_ht_cap));\n\t\tradio_type = mwifiex_band_to_radio_type(\n\t\t\t\t\tpriv->adapter->config_bands);\n\t\tmwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap);\n\n\t\tif (adapter->sec_chan_offset ==\n\t\t\t\t\tIEEE80211_HT_PARAM_CHA_SEC_NONE) {\n\t\t\tu16 tmp_ht_cap;\n\n\t\t\ttmp_ht_cap = le16_to_cpu(ht_cap->ht_cap.cap_info);\n\t\t\ttmp_ht_cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40;\n\t\t\ttmp_ht_cap &= ~IEEE80211_HT_CAP_SGI_40;\n\t\t\tht_cap->ht_cap.cap_info = cpu_to_le16(tmp_ht_cap);\n\t\t}\n\n\t\tpos += sizeof(struct mwifiex_ie_types_htcap);\n\t\tcmd_append_size += sizeof(struct mwifiex_ie_types_htcap);\n\n\t\t/* Fill HT INFORMATION */\n\t\tht_info = (struct mwifiex_ie_types_htinfo *) pos;\n\t\tmemset(ht_info, 0, sizeof(struct mwifiex_ie_types_htinfo));\n\t\tht_info->header.type = cpu_to_le16(WLAN_EID_HT_OPERATION);\n\t\tht_info->header.len =\n\t\t\tcpu_to_le16(sizeof(struct ieee80211_ht_operation));\n\n\t\tht_info->ht_oper.primary_chan =\n\t\t\t(u8) priv->curr_bss_params.bss_descriptor.channel;\n\t\tif (adapter->sec_chan_offset) {\n\t\t\tht_info->ht_oper.ht_param = adapter->sec_chan_offset;\n\t\t\tht_info->ht_oper.ht_param |=\n\t\t\t\t\tIEEE80211_HT_PARAM_CHAN_WIDTH_ANY;\n\t\t}\n\t\tht_info->ht_oper.operation_mode =\n\t\t cpu_to_le16(IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT);\n\t\tht_info->ht_oper.basic_set[0] = 0xff;\n\t\tpos += sizeof(struct mwifiex_ie_types_htinfo);\n\t\tcmd_append_size +=\n\t\t\t\tsizeof(struct mwifiex_ie_types_htinfo);\n\t}\n\n\tcmd->size =\n\t\tcpu_to_le16((u16)(sizeof(struct host_cmd_ds_802_11_ad_hoc_start)\n\t\t\t\t + S_DS_GEN + cmd_append_size));\n\n\tif (adapter->adhoc_start_band == BAND_B)\n\t\ttmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME;\n\telse\n\t\ttmp_cap |= WLAN_CAPABILITY_SHORT_SLOT_TIME;\n\n\tadhoc_start->cap_info_bitmap = cpu_to_le16(tmp_cap);\n\n\treturn 0;\n}", "project": "linux", "hash": 70830342815127398723710324714713389506, "size": 260, "commit_id": "5c455c5ab332773464d02ba17015acdca198f03d", "message": "mwifiex: Fix possible buffer overflows in mwifiex_cmd_802_11_ad_hoc_start\n\nmwifiex_cmd_802_11_ad_hoc_start() calls memcpy() without checking\nthe destination size may trigger a buffer overflower,\nwhich a local user could use to cause denial of service\nor the execution of arbitrary code.\nFix it by putting the length check before calling memcpy().\n\nSigned-off-by: Zhang Xiaohui <ruc_zhangxiaohui@163.com>\nSigned-off-by: Kalle Valo <kvalo@codeaurora.org>\nLink: https://lore.kernel.org/r/20201206084801.26479-1-ruc_zhangxiaohui@163.com", "target": 1, "dataset": "other", "idx": 211030}
  860. {"func": "mwifiex_cmd_802_11_ad_hoc_start(struct mwifiex_private *priv,\n\t\t\t\tstruct host_cmd_ds_command *cmd,\n\t\t\t\tstruct cfg80211_ssid *req_ssid)\n{\n\tint rsn_ie_len = 0;\n\tstruct mwifiex_adapter *adapter = priv->adapter;\n\tstruct host_cmd_ds_802_11_ad_hoc_start *adhoc_start =\n\t\t&cmd->params.adhoc_start;\n\tstruct mwifiex_bssdescriptor *bss_desc;\n\tu32 cmd_append_size = 0;\n\tu32 i;\n\tu16 tmp_cap;\n\tstruct mwifiex_ie_types_chan_list_param_set *chan_tlv;\n\tu8 radio_type;\n\n\tstruct mwifiex_ie_types_htcap *ht_cap;\n\tstruct mwifiex_ie_types_htinfo *ht_info;\n\tu8 *pos = (u8 *) adhoc_start +\n\t\t\tsizeof(struct host_cmd_ds_802_11_ad_hoc_start);\n\n\tif (!adapter)\n\t\treturn -1;\n\n\tcmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_START);\n\n\tbss_desc = &priv->curr_bss_params.bss_descriptor;\n\tpriv->attempted_bss_desc = bss_desc;\n\n\t/*\n\t * Fill in the parameters for 2 data structures:\n\t * 1. struct host_cmd_ds_802_11_ad_hoc_start command\n\t * 2. bss_desc\n\t * Driver will fill up SSID, bss_mode,IBSS param, Physical Param,\n\t * probe delay, and Cap info.\n\t * Firmware will fill up beacon period, Basic rates\n\t * and operational rates.\n\t */\n\n\tmemset(adhoc_start->ssid, 0, IEEE80211_MAX_SSID_LEN);\n\n\tif (req_ssid->ssid_len > IEEE80211_MAX_SSID_LEN)\n\t\treq_ssid->ssid_len = IEEE80211_MAX_SSID_LEN;\n\tmemcpy(adhoc_start->ssid, req_ssid->ssid, req_ssid->ssid_len);\n\n\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: SSID = %s\\n\",\n\t\t adhoc_start->ssid);\n\n\tmemset(bss_desc->ssid.ssid, 0, IEEE80211_MAX_SSID_LEN);\n\tmemcpy(bss_desc->ssid.ssid, req_ssid->ssid, req_ssid->ssid_len);\n\n\tbss_desc->ssid.ssid_len = req_ssid->ssid_len;\n\n\t/* Set the BSS mode */\n\tadhoc_start->bss_mode = HostCmd_BSS_MODE_IBSS;\n\tbss_desc->bss_mode = NL80211_IFTYPE_ADHOC;\n\tadhoc_start->beacon_period = cpu_to_le16(priv->beacon_period);\n\tbss_desc->beacon_period = priv->beacon_period;\n\n\t/* Set Physical param set */\n/* Parameter IE Id */\n#define DS_PARA_IE_ID 3\n/* Parameter IE length */\n#define DS_PARA_IE_LEN 1\n\n\tadhoc_start->phy_param_set.ds_param_set.element_id = DS_PARA_IE_ID;\n\tadhoc_start->phy_param_set.ds_param_set.len = DS_PARA_IE_LEN;\n\n\tif (!mwifiex_get_cfp(priv, adapter->adhoc_start_band,\n\t\t\t (u16) priv->adhoc_channel, 0)) {\n\t\tstruct mwifiex_chan_freq_power *cfp;\n\t\tcfp = mwifiex_get_cfp(priv, adapter->adhoc_start_band,\n\t\t\t\t FIRST_VALID_CHANNEL, 0);\n\t\tif (cfp)\n\t\t\tpriv->adhoc_channel = (u8) cfp->channel;\n\t}\n\n\tif (!priv->adhoc_channel) {\n\t\tmwifiex_dbg(adapter, ERROR,\n\t\t\t \"ADHOC_S_CMD: adhoc_channel cannot be 0\\n\");\n\t\treturn -1;\n\t}\n\n\tmwifiex_dbg(adapter, INFO,\n\t\t \"info: ADHOC_S_CMD: creating ADHOC on channel %d\\n\",\n\t\t priv->adhoc_channel);\n\n\tpriv->curr_bss_params.bss_descriptor.channel = priv->adhoc_channel;\n\tpriv->curr_bss_params.band = adapter->adhoc_start_band;\n\n\tbss_desc->channel = priv->adhoc_channel;\n\tadhoc_start->phy_param_set.ds_param_set.current_chan =\n\t\tpriv->adhoc_channel;\n\n\tmemcpy(&bss_desc->phy_param_set, &adhoc_start->phy_param_set,\n\t sizeof(union ieee_types_phy_param_set));\n\n\t/* Set IBSS param set */\n/* IBSS parameter IE Id */\n#define IBSS_PARA_IE_ID 6\n/* IBSS parameter IE length */\n#define IBSS_PARA_IE_LEN 2\n\n\tadhoc_start->ss_param_set.ibss_param_set.element_id = IBSS_PARA_IE_ID;\n\tadhoc_start->ss_param_set.ibss_param_set.len = IBSS_PARA_IE_LEN;\n\tadhoc_start->ss_param_set.ibss_param_set.atim_window\n\t\t\t\t\t= cpu_to_le16(priv->atim_window);\n\tmemcpy(&bss_desc->ss_param_set, &adhoc_start->ss_param_set,\n\t sizeof(union ieee_types_ss_param_set));\n\n\t/* Set Capability info */\n\tbss_desc->cap_info_bitmap |= WLAN_CAPABILITY_IBSS;\n\ttmp_cap = WLAN_CAPABILITY_IBSS;\n\n\t/* Set up privacy in bss_desc */\n\tif (priv->sec_info.encryption_mode) {\n\t\t/* Ad-Hoc capability privacy on */\n\t\tmwifiex_dbg(adapter, INFO,\n\t\t\t \"info: ADHOC_S_CMD: wep_status set privacy to WEP\\n\");\n\t\tbss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP;\n\t\ttmp_cap |= WLAN_CAPABILITY_PRIVACY;\n\t} else {\n\t\tmwifiex_dbg(adapter, INFO,\n\t\t\t \"info: ADHOC_S_CMD: wep_status NOT set,\\t\"\n\t\t\t \"setting privacy to ACCEPT ALL\\n\");\n\t\tbss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL;\n\t}\n\n\tmemset(adhoc_start->data_rate, 0, sizeof(adhoc_start->data_rate));\n\tmwifiex_get_active_data_rates(priv, adhoc_start->data_rate);\n\tif ((adapter->adhoc_start_band & BAND_G) &&\n\t (priv->curr_pkt_filter & HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON)) {\n\t\tif (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL,\n\t\t\t\t HostCmd_ACT_GEN_SET, 0,\n\t\t\t\t &priv->curr_pkt_filter, false)) {\n\t\t\tmwifiex_dbg(adapter, ERROR,\n\t\t\t\t \"ADHOC_S_CMD: G Protection config failed\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\t/* Find the last non zero */\n\tfor (i = 0; i < sizeof(adhoc_start->data_rate); i++)\n\t\tif (!adhoc_start->data_rate[i])\n\t\t\tbreak;\n\n\tpriv->curr_bss_params.num_of_rates = i;\n\n\t/* Copy the ad-hoc creating rates into Current BSS rate structure */\n\tmemcpy(&priv->curr_bss_params.data_rates,\n\t &adhoc_start->data_rate, priv->curr_bss_params.num_of_rates);\n\n\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: rates=%4ph\\n\",\n\t\t adhoc_start->data_rate);\n\n\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: AD-HOC Start command is ready\\n\");\n\n\tif (IS_SUPPORT_MULTI_BANDS(adapter)) {\n\t\t/* Append a channel TLV */\n\t\tchan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos;\n\t\tchan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);\n\t\tchan_tlv->header.len =\n\t\t\tcpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set));\n\n\t\tmemset(chan_tlv->chan_scan_param, 0x00,\n\t\t sizeof(struct mwifiex_chan_scan_param_set));\n\t\tchan_tlv->chan_scan_param[0].chan_number =\n\t\t\t(u8) priv->curr_bss_params.bss_descriptor.channel;\n\n\t\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: TLV Chan = %d\\n\",\n\t\t\t chan_tlv->chan_scan_param[0].chan_number);\n\n\t\tchan_tlv->chan_scan_param[0].radio_type\n\t\t = mwifiex_band_to_radio_type(priv->curr_bss_params.band);\n\t\tif (adapter->adhoc_start_band & BAND_GN ||\n\t\t adapter->adhoc_start_band & BAND_AN) {\n\t\t\tif (adapter->sec_chan_offset ==\n\t\t\t\t\t IEEE80211_HT_PARAM_CHA_SEC_ABOVE)\n\t\t\t\tchan_tlv->chan_scan_param[0].radio_type |=\n\t\t\t\t\t(IEEE80211_HT_PARAM_CHA_SEC_ABOVE << 4);\n\t\t\telse if (adapter->sec_chan_offset ==\n\t\t\t\t\t IEEE80211_HT_PARAM_CHA_SEC_BELOW)\n\t\t\t\tchan_tlv->chan_scan_param[0].radio_type |=\n\t\t\t\t\t(IEEE80211_HT_PARAM_CHA_SEC_BELOW << 4);\n\t\t}\n\t\tmwifiex_dbg(adapter, INFO, \"info: ADHOC_S_CMD: TLV Band = %d\\n\",\n\t\t\t chan_tlv->chan_scan_param[0].radio_type);\n\t\tpos += sizeof(chan_tlv->header) +\n\t\t\tsizeof(struct mwifiex_chan_scan_param_set);\n\t\tcmd_append_size +=\n\t\t\tsizeof(chan_tlv->header) +\n\t\t\tsizeof(struct mwifiex_chan_scan_param_set);\n\t}\n\n\t/* Append vendor specific IE TLV */\n\tcmd_append_size += mwifiex_cmd_append_vsie_tlv(priv,\n\t\t\t\tMWIFIEX_VSIE_MASK_ADHOC, &pos);\n\n\tif (priv->sec_info.wpa_enabled) {\n\t\trsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos);\n\t\tif (rsn_ie_len == -1)\n\t\t\treturn -1;\n\t\tcmd_append_size += rsn_ie_len;\n\t}\n\n\tif (adapter->adhoc_11n_enabled) {\n\t\t/* Fill HT CAPABILITY */\n\t\tht_cap = (struct mwifiex_ie_types_htcap *) pos;\n\t\tmemset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap));\n\t\tht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY);\n\t\tht_cap->header.len =\n\t\t cpu_to_le16(sizeof(struct ieee80211_ht_cap));\n\t\tradio_type = mwifiex_band_to_radio_type(\n\t\t\t\t\tpriv->adapter->config_bands);\n\t\tmwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap);\n\n\t\tif (adapter->sec_chan_offset ==\n\t\t\t\t\tIEEE80211_HT_PARAM_CHA_SEC_NONE) {\n\t\t\tu16 tmp_ht_cap;\n\n\t\t\ttmp_ht_cap = le16_to_cpu(ht_cap->ht_cap.cap_info);\n\t\t\ttmp_ht_cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40;\n\t\t\ttmp_ht_cap &= ~IEEE80211_HT_CAP_SGI_40;\n\t\t\tht_cap->ht_cap.cap_info = cpu_to_le16(tmp_ht_cap);\n\t\t}\n\n\t\tpos += sizeof(struct mwifiex_ie_types_htcap);\n\t\tcmd_append_size += sizeof(struct mwifiex_ie_types_htcap);\n\n\t\t/* Fill HT INFORMATION */\n\t\tht_info = (struct mwifiex_ie_types_htinfo *) pos;\n\t\tmemset(ht_info, 0, sizeof(struct mwifiex_ie_types_htinfo));\n\t\tht_info->header.type = cpu_to_le16(WLAN_EID_HT_OPERATION);\n\t\tht_info->header.len =\n\t\t\tcpu_to_le16(sizeof(struct ieee80211_ht_operation));\n\n\t\tht_info->ht_oper.primary_chan =\n\t\t\t(u8) priv->curr_bss_params.bss_descriptor.channel;\n\t\tif (adapter->sec_chan_offset) {\n\t\t\tht_info->ht_oper.ht_param = adapter->sec_chan_offset;\n\t\t\tht_info->ht_oper.ht_param |=\n\t\t\t\t\tIEEE80211_HT_PARAM_CHAN_WIDTH_ANY;\n\t\t}\n\t\tht_info->ht_oper.operation_mode =\n\t\t cpu_to_le16(IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT);\n\t\tht_info->ht_oper.basic_set[0] = 0xff;\n\t\tpos += sizeof(struct mwifiex_ie_types_htinfo);\n\t\tcmd_append_size +=\n\t\t\t\tsizeof(struct mwifiex_ie_types_htinfo);\n\t}\n\n\tcmd->size =\n\t\tcpu_to_le16((u16)(sizeof(struct host_cmd_ds_802_11_ad_hoc_start)\n\t\t\t\t + S_DS_GEN + cmd_append_size));\n\n\tif (adapter->adhoc_start_band == BAND_B)\n\t\ttmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME;\n\telse\n\t\ttmp_cap |= WLAN_CAPABILITY_SHORT_SLOT_TIME;\n\n\tadhoc_start->cap_info_bitmap = cpu_to_le16(tmp_cap);\n\n\treturn 0;\n}", "project": "linux", "hash": 14309788059901564103388827559722802715, "size": 262, "commit_id": "5c455c5ab332773464d02ba17015acdca198f03d", "message": "mwifiex: Fix possible buffer overflows in mwifiex_cmd_802_11_ad_hoc_start\n\nmwifiex_cmd_802_11_ad_hoc_start() calls memcpy() without checking\nthe destination size may trigger a buffer overflower,\nwhich a local user could use to cause denial of service\nor the execution of arbitrary code.\nFix it by putting the length check before calling memcpy().\n\nSigned-off-by: Zhang Xiaohui <ruc_zhangxiaohui@163.com>\nSigned-off-by: Kalle Valo <kvalo@codeaurora.org>\nLink: https://lore.kernel.org/r/20201206084801.26479-1-ruc_zhangxiaohui@163.com", "target": 0, "dataset": "other", "idx": 444812}
  861. {"func": "gst_matroska_demux_add_wvpk_header (GstElement * element,\n GstMatroskaTrackContext * stream, GstBuffer ** buf)\n{\n GstMatroskaTrackAudioContext *audiocontext =\n (GstMatroskaTrackAudioContext *) stream;\n GstBuffer *newbuf = NULL;\n GstMapInfo map, outmap;\n guint8 *buf_data, *data;\n Wavpack4Header wvh;\n\n wvh.ck_id[0] = 'w';\n wvh.ck_id[1] = 'v';\n wvh.ck_id[2] = 'p';\n wvh.ck_id[3] = 'k';\n\n wvh.version = GST_READ_UINT16_LE (stream->codec_priv);\n wvh.track_no = 0;\n wvh.index_no = 0;\n wvh.total_samples = -1;\n wvh.block_index = audiocontext->wvpk_block_index;\n\n if (audiocontext->channels <= 2) {\n guint32 block_samples, tmp;\n gsize size = gst_buffer_get_size (*buf);\n\n gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));\n block_samples = GUINT32_FROM_LE (tmp);\n /* we need to reconstruct the header of the wavpack block */\n\n /* -20 because ck_size is the size of the wavpack block -8\n * and lace_size is the size of the wavpack block + 12\n * (the three guint32 of the header that already are in the buffer) */\n wvh.ck_size = size + sizeof (Wavpack4Header) - 20;\n\n /* block_samples, flags and crc are already in the buffer */\n newbuf = gst_buffer_new_allocate (NULL, sizeof (Wavpack4Header) - 12, NULL);\n\n gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);\n data = outmap.data;\n data[0] = 'w';\n data[1] = 'v';\n data[2] = 'p';\n data[3] = 'k';\n GST_WRITE_UINT32_LE (data + 4, wvh.ck_size);\n GST_WRITE_UINT16_LE (data + 8, wvh.version);\n GST_WRITE_UINT8 (data + 10, wvh.track_no);\n GST_WRITE_UINT8 (data + 11, wvh.index_no);\n GST_WRITE_UINT32_LE (data + 12, wvh.total_samples);\n GST_WRITE_UINT32_LE (data + 16, wvh.block_index);\n gst_buffer_unmap (newbuf, &outmap);\n\n /* Append data from buf: */\n gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |\n GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0, size);\n\n gst_buffer_unref (*buf);\n *buf = newbuf;\n audiocontext->wvpk_block_index += block_samples;\n } else {\n guint8 *outdata = NULL;\n guint outpos = 0;\n gsize buf_size, size, out_size = 0;\n guint32 block_samples, flags, crc, blocksize;\n\n gst_buffer_map (*buf, &map, GST_MAP_READ);\n buf_data = map.data;\n buf_size = map.size;\n\n if (buf_size < 4) {\n GST_ERROR_OBJECT (element, \"Too small wavpack buffer\");\n gst_buffer_unmap (*buf, &map);\n return GST_FLOW_ERROR;\n }\n\n data = buf_data;\n size = buf_size;\n\n block_samples = GST_READ_UINT32_LE (data);\n data += 4;\n size -= 4;\n\n while (size > 12) {\n flags = GST_READ_UINT32_LE (data);\n data += 4;\n size -= 4;\n crc = GST_READ_UINT32_LE (data);\n data += 4;\n size -= 4;\n blocksize = GST_READ_UINT32_LE (data);\n data += 4;\n size -= 4;\n\n if (blocksize == 0 || size < blocksize)\n break;\n\n g_assert ((newbuf == NULL) == (outdata == NULL));\n\n if (newbuf == NULL) {\n out_size = sizeof (Wavpack4Header) + blocksize;\n newbuf = gst_buffer_new_allocate (NULL, out_size, NULL);\n\n gst_buffer_copy_into (newbuf, *buf,\n GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, -1);\n\n outpos = 0;\n gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);\n outdata = outmap.data;\n } else {\n gst_buffer_unmap (newbuf, &outmap);\n out_size += sizeof (Wavpack4Header) + blocksize;\n gst_buffer_set_size (newbuf, out_size);\n gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);\n outdata = outmap.data;\n }\n\n outdata[outpos] = 'w';\n outdata[outpos + 1] = 'v';\n outdata[outpos + 2] = 'p';\n outdata[outpos + 3] = 'k';\n outpos += 4;\n\n GST_WRITE_UINT32_LE (outdata + outpos,\n blocksize + sizeof (Wavpack4Header) - 8);\n GST_WRITE_UINT16_LE (outdata + outpos + 4, wvh.version);\n GST_WRITE_UINT8 (outdata + outpos + 6, wvh.track_no);\n GST_WRITE_UINT8 (outdata + outpos + 7, wvh.index_no);\n GST_WRITE_UINT32_LE (outdata + outpos + 8, wvh.total_samples);\n GST_WRITE_UINT32_LE (outdata + outpos + 12, wvh.block_index);\n GST_WRITE_UINT32_LE (outdata + outpos + 16, block_samples);\n GST_WRITE_UINT32_LE (outdata + outpos + 20, flags);\n GST_WRITE_UINT32_LE (outdata + outpos + 24, crc);\n outpos += 28;\n\n memmove (outdata + outpos, data, blocksize);\n outpos += blocksize;\n data += blocksize;\n size -= blocksize;\n }\n gst_buffer_unmap (*buf, &map);\n gst_buffer_unref (*buf);\n\n if (newbuf)\n gst_buffer_unmap (newbuf, &outmap);\n\n *buf = newbuf;\n audiocontext->wvpk_block_index += block_samples;\n }\n\n return GST_FLOW_OK;\n}", "project": "gst-plugins-good", "hash": 268357661659485737291790303030263514365, "size": 150, "commit_id": "9181191511f9c0be6a89c98b311f49d66bd46dc3", "message": "matroskademux: Fix extraction of multichannel WavPack\n\nThe old code had a couple of issues that all lead to potential memory\nsafety bugs.\n\n - Use a constant for the Wavpack4Header size instead of using sizeof.\n It's written out into the data and not from the struct and who knows\n what special alignment/padding requirements some C compilers have.\n - gst_buffer_set_size() does not realloc the buffer when setting a\n bigger size than allocated, it only allows growing up to the maximum\n allocated size. Instead use a GstAdapter to collect all the blocks\n and take out everything at once in the end.\n - Check that enough data is actually available in the input and\n otherwise handle it an error in all cases instead of silently\n ignoring it.\n\nAmong other things this fixes out of bounds writes because the code\nassumed gst_buffer_set_size() can grow the buffer and simply wrote after\nthe end of the buffer.\n\nThanks to Natalie Silvanovich for reporting.\n\nFixes https://gitlab.freedesktop.org/gstreamer/gst-plugins-good/-/issues/859\n\nPart-of: <https://gitlab.freedesktop.org/gstreamer/gst-plugins-good/-/merge_requests/903>", "target": 1, "dataset": "other", "idx": 211032}
  862. {"func": "gst_matroska_demux_add_wvpk_header (GstElement * element,\n GstMatroskaTrackContext * stream, GstBuffer ** buf)\n{\n GstMatroskaTrackAudioContext *audiocontext =\n (GstMatroskaTrackAudioContext *) stream;\n GstBuffer *newbuf = NULL;\n GstMapInfo map, outmap;\n guint8 *buf_data, *data;\n Wavpack4Header wvh;\n\n wvh.ck_id[0] = 'w';\n wvh.ck_id[1] = 'v';\n wvh.ck_id[2] = 'p';\n wvh.ck_id[3] = 'k';\n\n wvh.version = GST_READ_UINT16_LE (stream->codec_priv);\n wvh.track_no = 0;\n wvh.index_no = 0;\n wvh.total_samples = -1;\n wvh.block_index = audiocontext->wvpk_block_index;\n\n if (audiocontext->channels <= 2) {\n guint32 block_samples, tmp;\n gsize size = gst_buffer_get_size (*buf);\n\n if (size < 4) {\n GST_ERROR_OBJECT (element, \"Too small wavpack buffer\");\n gst_buffer_unmap (*buf, &map);\n return GST_FLOW_ERROR;\n }\n\n gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));\n block_samples = GUINT32_FROM_LE (tmp);\n /* we need to reconstruct the header of the wavpack block */\n\n /* -20 because ck_size is the size of the wavpack block -8\n * and lace_size is the size of the wavpack block + 12\n * (the three guint32 of the header that already are in the buffer) */\n wvh.ck_size = size + WAVPACK4_HEADER_SIZE - 20;\n\n /* block_samples, flags and crc are already in the buffer */\n newbuf = gst_buffer_new_allocate (NULL, WAVPACK4_HEADER_SIZE - 12, NULL);\n\n gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);\n data = outmap.data;\n data[0] = 'w';\n data[1] = 'v';\n data[2] = 'p';\n data[3] = 'k';\n GST_WRITE_UINT32_LE (data + 4, wvh.ck_size);\n GST_WRITE_UINT16_LE (data + 8, wvh.version);\n GST_WRITE_UINT8 (data + 10, wvh.track_no);\n GST_WRITE_UINT8 (data + 11, wvh.index_no);\n GST_WRITE_UINT32_LE (data + 12, wvh.total_samples);\n GST_WRITE_UINT32_LE (data + 16, wvh.block_index);\n gst_buffer_unmap (newbuf, &outmap);\n\n /* Append data from buf: */\n gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |\n GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0, size);\n\n gst_buffer_unref (*buf);\n *buf = newbuf;\n audiocontext->wvpk_block_index += block_samples;\n } else {\n guint8 *outdata = NULL;\n gsize buf_size, size;\n guint32 block_samples, flags, crc, blocksize;\n GstAdapter *adapter;\n\n adapter = gst_adapter_new ();\n\n gst_buffer_map (*buf, &map, GST_MAP_READ);\n buf_data = map.data;\n buf_size = map.size;\n\n if (buf_size < 4) {\n GST_ERROR_OBJECT (element, \"Too small wavpack buffer\");\n gst_buffer_unmap (*buf, &map);\n g_object_unref (adapter);\n return GST_FLOW_ERROR;\n }\n\n data = buf_data;\n size = buf_size;\n\n block_samples = GST_READ_UINT32_LE (data);\n data += 4;\n size -= 4;\n\n while (size > 12) {\n flags = GST_READ_UINT32_LE (data);\n data += 4;\n size -= 4;\n crc = GST_READ_UINT32_LE (data);\n data += 4;\n size -= 4;\n blocksize = GST_READ_UINT32_LE (data);\n data += 4;\n size -= 4;\n\n if (blocksize == 0 || size < blocksize) {\n GST_ERROR_OBJECT (element, \"Too small wavpack buffer\");\n gst_buffer_unmap (*buf, &map);\n g_object_unref (adapter);\n return GST_FLOW_ERROR;\n }\n\n g_assert (newbuf == NULL);\n\n newbuf =\n gst_buffer_new_allocate (NULL, WAVPACK4_HEADER_SIZE + blocksize,\n NULL);\n gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);\n outdata = outmap.data;\n\n outdata[0] = 'w';\n outdata[1] = 'v';\n outdata[2] = 'p';\n outdata[3] = 'k';\n outdata += 4;\n\n GST_WRITE_UINT32_LE (outdata, blocksize + WAVPACK4_HEADER_SIZE - 8);\n GST_WRITE_UINT16_LE (outdata + 4, wvh.version);\n GST_WRITE_UINT8 (outdata + 6, wvh.track_no);\n GST_WRITE_UINT8 (outdata + 7, wvh.index_no);\n GST_WRITE_UINT32_LE (outdata + 8, wvh.total_samples);\n GST_WRITE_UINT32_LE (outdata + 12, wvh.block_index);\n GST_WRITE_UINT32_LE (outdata + 16, block_samples);\n GST_WRITE_UINT32_LE (outdata + 20, flags);\n GST_WRITE_UINT32_LE (outdata + 24, crc);\n outdata += 28;\n\n memcpy (outdata, data, blocksize);\n\n gst_buffer_unmap (newbuf, &outmap);\n gst_adapter_push (adapter, newbuf);\n newbuf = NULL;\n\n data += blocksize;\n size -= blocksize;\n }\n gst_buffer_unmap (*buf, &map);\n\n newbuf = gst_adapter_take_buffer (adapter, gst_adapter_available (adapter));\n g_object_unref (adapter);\n\n gst_buffer_copy_into (newbuf, *buf,\n GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, -1);\n gst_buffer_unref (*buf);\n *buf = newbuf;\n\n audiocontext->wvpk_block_index += block_samples;\n }\n\n return GST_FLOW_OK;\n}", "project": "gst-plugins-good", "hash": 171585410452689613966315464094758896783, "size": 157, "commit_id": "9181191511f9c0be6a89c98b311f49d66bd46dc3", "message": "matroskademux: Fix extraction of multichannel WavPack\n\nThe old code had a couple of issues that all lead to potential memory\nsafety bugs.\n\n - Use a constant for the Wavpack4Header size instead of using sizeof.\n It's written out into the data and not from the struct and who knows\n what special alignment/padding requirements some C compilers have.\n - gst_buffer_set_size() does not realloc the buffer when setting a\n bigger size than allocated, it only allows growing up to the maximum\n allocated size. Instead use a GstAdapter to collect all the blocks\n and take out everything at once in the end.\n - Check that enough data is actually available in the input and\n otherwise handle it an error in all cases instead of silently\n ignoring it.\n\nAmong other things this fixes out of bounds writes because the code\nassumed gst_buffer_set_size() can grow the buffer and simply wrote after\nthe end of the buffer.\n\nThanks to Natalie Silvanovich for reporting.\n\nFixes https://gitlab.freedesktop.org/gstreamer/gst-plugins-good/-/issues/859\n\nPart-of: <https://gitlab.freedesktop.org/gstreamer/gst-plugins-good/-/merge_requests/903>", "target": 0, "dataset": "other", "idx": 444835}
  863. {"func": "allocate_trace_buffer(struct trace_array *tr, struct trace_buffer *buf, int size)\n{\n\tenum ring_buffer_flags rb_flags;\n\n\trb_flags = tr->trace_flags & TRACE_ITER_OVERWRITE ? RB_FL_OVERWRITE : 0;\n\n\tbuf->tr = tr;\n\n\tbuf->buffer = ring_buffer_alloc(size, rb_flags);\n\tif (!buf->buffer)\n\t\treturn -ENOMEM;\n\n\tbuf->data = alloc_percpu(struct trace_array_cpu);\n\tif (!buf->data) {\n\t\tring_buffer_free(buf->buffer);\n\t\treturn -ENOMEM;\n\t}\n\n\t/* Allocate the first page for all buffers */\n\tset_buffer_entries(&tr->trace_buffer,\n\t\t\t ring_buffer_size(tr->trace_buffer.buffer, 0));\n\n\treturn 0;\n}", "project": "linux", "hash": 326507675290447432448249658202476844227, "size": 24, "commit_id": "4397f04575c44e1440ec2e49b6302785c95fd2f8", "message": "tracing: Fix possible double free on failure of allocating trace buffer\n\nJing Xia and Chunyan Zhang reported that on failing to allocate part of the\ntracing buffer, memory is freed, but the pointers that point to them are not\ninitialized back to NULL, and later paths may try to free the freed memory\nagain. Jing and Chunyan fixed one of the locations that does this, but\nmissed a spot.\n\nLink: http://lkml.kernel.org/r/20171226071253.8968-1-chunyan.zhang@spreadtrum.com\n\nCc: stable@vger.kernel.org\nFixes: 737223fbca3b1 (\"tracing: Consolidate buffer allocation code\")\nReported-by: Jing Xia <jing.xia@spreadtrum.com>\nReported-by: Chunyan Zhang <chunyan.zhang@spreadtrum.com>\nSigned-off-by: Steven Rostedt (VMware) <rostedt@goodmis.org>", "target": 1, "dataset": "other", "idx": 211099}
  864. {"func": "allocate_trace_buffer(struct trace_array *tr, struct trace_buffer *buf, int size)\n{\n\tenum ring_buffer_flags rb_flags;\n\n\trb_flags = tr->trace_flags & TRACE_ITER_OVERWRITE ? RB_FL_OVERWRITE : 0;\n\n\tbuf->tr = tr;\n\n\tbuf->buffer = ring_buffer_alloc(size, rb_flags);\n\tif (!buf->buffer)\n\t\treturn -ENOMEM;\n\n\tbuf->data = alloc_percpu(struct trace_array_cpu);\n\tif (!buf->data) {\n\t\tring_buffer_free(buf->buffer);\n\t\tbuf->buffer = NULL;\n\t\treturn -ENOMEM;\n\t}\n\n\t/* Allocate the first page for all buffers */\n\tset_buffer_entries(&tr->trace_buffer,\n\t\t\t ring_buffer_size(tr->trace_buffer.buffer, 0));\n\n\treturn 0;\n}", "project": "linux", "hash": 186387913486476739467017691738960848735, "size": 25, "commit_id": "4397f04575c44e1440ec2e49b6302785c95fd2f8", "message": "tracing: Fix possible double free on failure of allocating trace buffer\n\nJing Xia and Chunyan Zhang reported that on failing to allocate part of the\ntracing buffer, memory is freed, but the pointers that point to them are not\ninitialized back to NULL, and later paths may try to free the freed memory\nagain. Jing and Chunyan fixed one of the locations that does this, but\nmissed a spot.\n\nLink: http://lkml.kernel.org/r/20171226071253.8968-1-chunyan.zhang@spreadtrum.com\n\nCc: stable@vger.kernel.org\nFixes: 737223fbca3b1 (\"tracing: Consolidate buffer allocation code\")\nReported-by: Jing Xia <jing.xia@spreadtrum.com>\nReported-by: Chunyan Zhang <chunyan.zhang@spreadtrum.com>\nSigned-off-by: Steven Rostedt (VMware) <rostedt@goodmis.org>", "target": 0, "dataset": "other", "idx": 445672}
  865. {"func": "static int grep_tree(struct grep_opt *opt, const char **paths,\n\t\t struct tree_desc *tree,\n\t\t const char *tree_name, const char *base)\n{\n\tint len;\n\tint hit = 0;\n\tstruct name_entry entry;\n\tchar *down;\n\tint tn_len = strlen(tree_name);\n\tchar *path_buf = xmalloc(PATH_MAX + tn_len + 100);\n\n\tif (tn_len) {\n\t\ttn_len = sprintf(path_buf, \"%s:\", tree_name);\n\t\tdown = path_buf + tn_len;\n\t\tstrcat(down, base);\n\t}\n\telse {\n\t\tdown = path_buf;\n\t\tstrcpy(down, base);\n\t}\n\tlen = strlen(path_buf);\n\n\twhile (tree_entry(tree, &entry)) {\n\t\tstrcpy(path_buf + len, entry.path);\n\n\t\tif (S_ISDIR(entry.mode))\n\t\t\t/* Match \"abc/\" against pathspec to\n\t\t\t * decide if we want to descend into \"abc\"\n\t\t\t * directory.\n\t\t\t */\n\t\t\tstrcpy(path_buf + len + tree_entry_len(entry.path, entry.sha1), \"/\");\n\n\t\tif (!pathspec_matches(paths, down))\n\t\t\t;\n\t\telse if (S_ISREG(entry.mode))\n\t\t\thit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);\n\t\telse if (S_ISDIR(entry.mode)) {\n\t\t\tenum object_type type;\n\t\t\tstruct tree_desc sub;\n\t\t\tvoid *data;\n\t\t\tunsigned long size;\n\n\t\t\tdata = read_sha1_file(entry.sha1, &type, &size);\n\t\t\tif (!data)\n\t\t\t\tdie(\"unable to read tree (%s)\",\n\t\t\t\t sha1_to_hex(entry.sha1));\n\t\t\tinit_tree_desc(&sub, data, size);\n\t\t\thit |= grep_tree(opt, paths, &sub, tree_name, down);\n\t\t\tfree(data);\n\t\t}\n\t}\n\treturn hit;\n}", "project": "git", "hash": 77154386793728243633685029216704517884, "size": 53, "commit_id": "620e2bb93785ed8eb60846d94fd4753d4817c8ec", "message": "Fix buffer overflow in git-grep\n\nIf PATH_MAX on your system is smaller than any path stored in the git\nrepository, that can cause memory corruption inside of the grep_tree\nfunction used by git-grep.\n\nSigned-off-by: Dmitry Potapov <dpotapov@gmail.com>\nSigned-off-by: Junio C Hamano <gitster@pobox.com>", "target": 1, "dataset": "other", "idx": 211109}
  866. {"func": "static int grep_tree(struct grep_opt *opt, const char **paths,\n\t\t struct tree_desc *tree,\n\t\t const char *tree_name, const char *base)\n{\n\tint len;\n\tint hit = 0;\n\tstruct name_entry entry;\n\tchar *down;\n\tint tn_len = strlen(tree_name);\n\tstruct strbuf pathbuf;\n\n\tstrbuf_init(&pathbuf, PATH_MAX + tn_len);\n\n\tif (tn_len) {\n\t\tstrbuf_add(&pathbuf, tree_name, tn_len);\n\t\tstrbuf_addch(&pathbuf, ':');\n\t\ttn_len = pathbuf.len;\n\t}\n\tstrbuf_addstr(&pathbuf, base);\n\tlen = pathbuf.len;\n\n\twhile (tree_entry(tree, &entry)) {\n\t\tint te_len = tree_entry_len(entry.path, entry.sha1);\n\t\tpathbuf.len = len;\n\t\tstrbuf_add(&pathbuf, entry.path, te_len);\n\n\t\tif (S_ISDIR(entry.mode))\n\t\t\t/* Match \"abc/\" against pathspec to\n\t\t\t * decide if we want to descend into \"abc\"\n\t\t\t * directory.\n\t\t\t */\n\t\t\tstrbuf_addch(&pathbuf, '/');\n\n\t\tdown = pathbuf.buf + tn_len;\n\t\tif (!pathspec_matches(paths, down))\n\t\t\t;\n\t\telse if (S_ISREG(entry.mode))\n\t\t\thit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);\n\t\telse if (S_ISDIR(entry.mode)) {\n\t\t\tenum object_type type;\n\t\t\tstruct tree_desc sub;\n\t\t\tvoid *data;\n\t\t\tunsigned long size;\n\n\t\t\tdata = read_sha1_file(entry.sha1, &type, &size);\n\t\t\tif (!data)\n\t\t\t\tdie(\"unable to read tree (%s)\",\n\t\t\t\t sha1_to_hex(entry.sha1));\n\t\t\tinit_tree_desc(&sub, data, size);\n\t\t\thit |= grep_tree(opt, paths, &sub, tree_name, down);\n\t\t\tfree(data);\n\t\t}\n\t}\n\tstrbuf_release(&pathbuf);\n\treturn hit;\n}", "project": "git", "hash": 315062688524784334062144621049330398394, "size": 56, "commit_id": "620e2bb93785ed8eb60846d94fd4753d4817c8ec", "message": "Fix buffer overflow in git-grep\n\nIf PATH_MAX on your system is smaller than any path stored in the git\nrepository, that can cause memory corruption inside of the grep_tree\nfunction used by git-grep.\n\nSigned-off-by: Dmitry Potapov <dpotapov@gmail.com>\nSigned-off-by: Junio C Hamano <gitster@pobox.com>", "target": 0, "dataset": "other", "idx": 446048}
  867. {"func": "void ScanLineInputFile::initialize(const Header& header)\n{\n _data->header = header;\n\n _data->lineOrder = _data->header.lineOrder();\n\n const Box2i &dataWindow = _data->header.dataWindow();\n\n _data->minX = dataWindow.min.x;\n _data->maxX = dataWindow.max.x;\n _data->minY = dataWindow.min.y;\n _data->maxY = dataWindow.max.y;\n\n Compression comp = _data->header.compression();\n\n _data->linesInBuffer =\n numLinesInBuffer (comp);\n\n int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +\n _data->linesInBuffer) / _data->linesInBuffer;\n\n //\n // avoid allocating excessive memory due to large lineOffsets table size.\n // If the chunktablesize claims to be large,\n // check the file is big enough to contain the table before allocating memory\n // in the bytesPerLineTable and the lineOffsets table.\n // Attempt to read the last entry in the table. Either the seekg() or the read()\n // call will throw an exception if the file is too small to contain the table\n //\n if (lineOffsetSize > gLargeChunkTableSize)\n {\n Int64 pos = _streamData->is->tellg();\n _streamData->is->seekg(pos + (lineOffsetSize-1)*sizeof(Int64));\n Int64 temp;\n OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*_streamData->is, temp);\n _streamData->is->seekg(pos);\n\n }\n\n\n size_t maxBytesPerLine = bytesPerLineTable (_data->header,\n _data->bytesPerLine);\n\n if (maxBytesPerLine*numLinesInBuffer(comp) > INT_MAX)\n {\n throw IEX_NAMESPACE::InputExc(\"maximum bytes per scanline exceeds maximum permissible size\");\n }\n\n\n //\n // allocate compressor objects\n //\n for (size_t i = 0; i < _data->lineBuffers.size(); i++)\n {\n _data->lineBuffers[i] = new LineBuffer (newCompressor(comp,\n maxBytesPerLine,\n _data->header));\n }\n\n\n\n _data->lineBufferSize = maxBytesPerLine * _data->linesInBuffer;\n\n if (!_streamData->is->isMemoryMapped())\n {\n for (size_t i = 0; i < _data->lineBuffers.size(); i++)\n {\n _data->lineBuffers[i]->buffer = (char *) EXRAllocAligned(_data->lineBufferSize*sizeof(char),16);\n if (!_data->lineBuffers[i]->buffer)\n {\n throw IEX_NAMESPACE::LogicExc(\"Failed to allocate memory for scanline buffers\");\n }\n }\n }\n _data->nextLineBufferMinY = _data->minY - 1;\n\n offsetInLineBufferTable (_data->bytesPerLine,\n _data->linesInBuffer,\n _data->offsetInLineBuffer);\n\n\n _data->lineOffsets.resize (lineOffsetSize);\n}", "project": "openexr", "hash": 22351819646121800230325071822285424033, "size": 83, "commit_id": "bc88cdb6c97fbf5bc5d11ad8ca55306da931283a", "message": "sanity check ScanlineInput bytesPerLine instead of lineOffset size (#863)\n\nSigned-off-by: Peter Hillman <peterh@wetafx.co.nz>\r\n\r\nCo-authored-by: Cary Phillips <cary@ilm.com>", "target": 1, "dataset": "other", "idx": 211127}
  868. {"func": "void ScanLineInputFile::initialize(const Header& header)\n{\n _data->header = header;\n\n _data->lineOrder = _data->header.lineOrder();\n\n const Box2i &dataWindow = _data->header.dataWindow();\n\n _data->minX = dataWindow.min.x;\n _data->maxX = dataWindow.max.x;\n _data->minY = dataWindow.min.y;\n _data->maxY = dataWindow.max.y;\n\n Compression comp = _data->header.compression();\n\n _data->linesInBuffer =\n numLinesInBuffer (comp);\n\n int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +\n _data->linesInBuffer) / _data->linesInBuffer;\n\n //\n // avoid allocating excessive memory due to large lineOffsets and bytesPerLine table sizes.\n // If the chunktablesize claims to be large,\n // check the file is big enough to contain the lineOffsets table before allocating memory\n // in the bytesPerLineTable and the lineOffsets table.\n // Attempt to read the last entry in the table. Either the seekg() or the read()\n // call will throw an exception if the file is too small to contain the table\n //\n if (lineOffsetSize * _data->linesInBuffer > gLargeChunkTableSize)\n {\n Int64 pos = _streamData->is->tellg();\n _streamData->is->seekg(pos + (lineOffsetSize-1)*sizeof(Int64));\n Int64 temp;\n OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*_streamData->is, temp);\n _streamData->is->seekg(pos);\n\n }\n\n\n size_t maxBytesPerLine = bytesPerLineTable (_data->header,\n _data->bytesPerLine);\n\n if (maxBytesPerLine*numLinesInBuffer(comp) > INT_MAX)\n {\n throw IEX_NAMESPACE::InputExc(\"maximum bytes per scanline exceeds maximum permissible size\");\n }\n\n\n //\n // allocate compressor objects\n //\n for (size_t i = 0; i < _data->lineBuffers.size(); i++)\n {\n _data->lineBuffers[i] = new LineBuffer (newCompressor(comp,\n maxBytesPerLine,\n _data->header));\n }\n\n\n\n _data->lineBufferSize = maxBytesPerLine * _data->linesInBuffer;\n\n if (!_streamData->is->isMemoryMapped())\n {\n for (size_t i = 0; i < _data->lineBuffers.size(); i++)\n {\n _data->lineBuffers[i]->buffer = (char *) EXRAllocAligned(_data->lineBufferSize*sizeof(char),16);\n if (!_data->lineBuffers[i]->buffer)\n {\n throw IEX_NAMESPACE::LogicExc(\"Failed to allocate memory for scanline buffers\");\n }\n }\n }\n _data->nextLineBufferMinY = _data->minY - 1;\n\n offsetInLineBufferTable (_data->bytesPerLine,\n _data->linesInBuffer,\n _data->offsetInLineBuffer);\n\n\n _data->lineOffsets.resize (lineOffsetSize);\n}", "project": "openexr", "hash": 103823671992022679830878815429871629942, "size": 83, "commit_id": "bc88cdb6c97fbf5bc5d11ad8ca55306da931283a", "message": "sanity check ScanlineInput bytesPerLine instead of lineOffset size (#863)\n\nSigned-off-by: Peter Hillman <peterh@wetafx.co.nz>\r\n\r\nCo-authored-by: Cary Phillips <cary@ilm.com>", "target": 0, "dataset": "other", "idx": 446283}
  869. {"func": "static struct kobject *cdev_get(struct cdev *p)\n{\n\tstruct module *owner = p->owner;\n\tstruct kobject *kobj;\n\n\tif (owner && !try_module_get(owner))\n\t\treturn NULL;\n\tkobj = kobject_get(&p->kobj);\n\tif (!kobj)\n\t\tmodule_put(owner);\n\treturn kobj;\n}", "project": "linux", "hash": 81735454176414824678551654951534930012, "size": 12, "commit_id": "68faa679b8be1a74e6663c21c3a9d25d32f1c079", "message": "chardev: Avoid potential use-after-free in 'chrdev_open()'\n\n'chrdev_open()' calls 'cdev_get()' to obtain a reference to the\n'struct cdev *' stashed in the 'i_cdev' field of the target inode\nstructure. If the pointer is NULL, then it is initialised lazily by\nlooking up the kobject in the 'cdev_map' and so the whole procedure is\nprotected by the 'cdev_lock' spinlock to serialise initialisation of\nthe shared pointer.\n\nUnfortunately, it is possible for the initialising thread to fail *after*\ninstalling the new pointer, for example if the subsequent '->open()' call\non the file fails. In this case, 'cdev_put()' is called, the reference\ncount on the kobject is dropped and, if nobody else has taken a reference,\nthe release function is called which finally clears 'inode->i_cdev' from\n'cdev_purge()' before potentially freeing the object. The problem here\nis that a racing thread can happily take the 'cdev_lock' and see the\nnon-NULL pointer in the inode, which can result in a refcount increment\nfrom zero and a warning:\n\n | ------------[ cut here ]------------\n | refcount_t: addition on 0; use-after-free.\n | WARNING: CPU: 2 PID: 6385 at lib/refcount.c:25 refcount_warn_saturate+0x6d/0xf0\n | Modules linked in:\n | CPU: 2 PID: 6385 Comm: repro Not tainted 5.5.0-rc2+ #22\n | Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.12.0-1 04/01/2014\n | RIP: 0010:refcount_warn_saturate+0x6d/0xf0\n | Code: 05 55 9a 15 01 01 e8 9d aa c8 ff 0f 0b c3 80 3d 45 9a 15 01 00 75 ce 48 c7 c7 00 9c 62 b3 c6 08\n | RSP: 0018:ffffb524c1b9bc70 EFLAGS: 00010282\n | RAX: 0000000000000000 RBX: ffff9e9da1f71390 RCX: 0000000000000000\n | RDX: ffff9e9dbbd27618 RSI: ffff9e9dbbd18798 RDI: ffff9e9dbbd18798\n | RBP: 0000000000000000 R08: 000000000000095f R09: 0000000000000039\n | R10: 0000000000000000 R11: ffffb524c1b9bb20 R12: ffff9e9da1e8c700\n | R13: ffffffffb25ee8b0 R14: 0000000000000000 R15: ffff9e9da1e8c700\n | FS: 00007f3b87d26700(0000) GS:ffff9e9dbbd00000(0000) knlGS:0000000000000000\n | CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n | CR2: 00007fc16909c000 CR3: 000000012df9c000 CR4: 00000000000006e0\n | DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\n | DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\n | Call Trace:\n | kobject_get+0x5c/0x60\n | cdev_get+0x2b/0x60\n | chrdev_open+0x55/0x220\n | ? cdev_put.part.3+0x20/0x20\n | do_dentry_open+0x13a/0x390\n | path_openat+0x2c8/0x1470\n | do_filp_open+0x93/0x100\n | ? selinux_file_ioctl+0x17f/0x220\n | do_sys_open+0x186/0x220\n | do_syscall_64+0x48/0x150\n | entry_SYSCALL_64_after_hwframe+0x44/0xa9\n | RIP: 0033:0x7f3b87efcd0e\n | Code: 89 54 24 08 e8 a3 f4 ff ff 8b 74 24 0c 48 8b 3c 24 41 89 c0 44 8b 54 24 08 b8 01 01 00 00 89 f4\n | RSP: 002b:00007f3b87d259f0 EFLAGS: 00000293 ORIG_RAX: 0000000000000101\n | RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007f3b87efcd0e\n | RDX: 0000000000000000 RSI: 00007f3b87d25a80 RDI: 00000000ffffff9c\n | RBP: 00007f3b87d25e90 R08: 0000000000000000 R09: 0000000000000000\n | R10: 0000000000000000 R11: 0000000000000293 R12: 00007ffe188f504e\n | R13: 00007ffe188f504f R14: 00007f3b87d26700 R15: 0000000000000000\n | ---[ end trace 24f53ca58db8180a ]---\n\nSince 'cdev_get()' can already fail to obtain a reference, simply move\nit over to use 'kobject_get_unless_zero()' instead of 'kobject_get()',\nwhich will cause the racing thread to return -ENXIO if the initialising\nthread fails unexpectedly.\n\nCc: Hillf Danton <hdanton@sina.com>\nCc: Andrew Morton <akpm@linux-foundation.org>\nCc: Al Viro <viro@zeniv.linux.org.uk>\nReported-by: syzbot+82defefbbd8527e1c2cb@syzkaller.appspotmail.com\nSigned-off-by: Will Deacon <will@kernel.org>\nCc: stable <stable@vger.kernel.org>\nLink: https://lore.kernel.org/r/20191219120203.32691-1-will@kernel.org\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 1, "dataset": "other", "idx": 211135}
  870. {"func": "static struct kobject *cdev_get(struct cdev *p)\n{\n\tstruct module *owner = p->owner;\n\tstruct kobject *kobj;\n\n\tif (owner && !try_module_get(owner))\n\t\treturn NULL;\n\tkobj = kobject_get_unless_zero(&p->kobj);\n\tif (!kobj)\n\t\tmodule_put(owner);\n\treturn kobj;\n}", "project": "linux", "hash": 94936488811761889392788452521795882904, "size": 12, "commit_id": "68faa679b8be1a74e6663c21c3a9d25d32f1c079", "message": "chardev: Avoid potential use-after-free in 'chrdev_open()'\n\n'chrdev_open()' calls 'cdev_get()' to obtain a reference to the\n'struct cdev *' stashed in the 'i_cdev' field of the target inode\nstructure. If the pointer is NULL, then it is initialised lazily by\nlooking up the kobject in the 'cdev_map' and so the whole procedure is\nprotected by the 'cdev_lock' spinlock to serialise initialisation of\nthe shared pointer.\n\nUnfortunately, it is possible for the initialising thread to fail *after*\ninstalling the new pointer, for example if the subsequent '->open()' call\non the file fails. In this case, 'cdev_put()' is called, the reference\ncount on the kobject is dropped and, if nobody else has taken a reference,\nthe release function is called which finally clears 'inode->i_cdev' from\n'cdev_purge()' before potentially freeing the object. The problem here\nis that a racing thread can happily take the 'cdev_lock' and see the\nnon-NULL pointer in the inode, which can result in a refcount increment\nfrom zero and a warning:\n\n | ------------[ cut here ]------------\n | refcount_t: addition on 0; use-after-free.\n | WARNING: CPU: 2 PID: 6385 at lib/refcount.c:25 refcount_warn_saturate+0x6d/0xf0\n | Modules linked in:\n | CPU: 2 PID: 6385 Comm: repro Not tainted 5.5.0-rc2+ #22\n | Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.12.0-1 04/01/2014\n | RIP: 0010:refcount_warn_saturate+0x6d/0xf0\n | Code: 05 55 9a 15 01 01 e8 9d aa c8 ff 0f 0b c3 80 3d 45 9a 15 01 00 75 ce 48 c7 c7 00 9c 62 b3 c6 08\n | RSP: 0018:ffffb524c1b9bc70 EFLAGS: 00010282\n | RAX: 0000000000000000 RBX: ffff9e9da1f71390 RCX: 0000000000000000\n | RDX: ffff9e9dbbd27618 RSI: ffff9e9dbbd18798 RDI: ffff9e9dbbd18798\n | RBP: 0000000000000000 R08: 000000000000095f R09: 0000000000000039\n | R10: 0000000000000000 R11: ffffb524c1b9bb20 R12: ffff9e9da1e8c700\n | R13: ffffffffb25ee8b0 R14: 0000000000000000 R15: ffff9e9da1e8c700\n | FS: 00007f3b87d26700(0000) GS:ffff9e9dbbd00000(0000) knlGS:0000000000000000\n | CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n | CR2: 00007fc16909c000 CR3: 000000012df9c000 CR4: 00000000000006e0\n | DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\n | DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\n | Call Trace:\n | kobject_get+0x5c/0x60\n | cdev_get+0x2b/0x60\n | chrdev_open+0x55/0x220\n | ? cdev_put.part.3+0x20/0x20\n | do_dentry_open+0x13a/0x390\n | path_openat+0x2c8/0x1470\n | do_filp_open+0x93/0x100\n | ? selinux_file_ioctl+0x17f/0x220\n | do_sys_open+0x186/0x220\n | do_syscall_64+0x48/0x150\n | entry_SYSCALL_64_after_hwframe+0x44/0xa9\n | RIP: 0033:0x7f3b87efcd0e\n | Code: 89 54 24 08 e8 a3 f4 ff ff 8b 74 24 0c 48 8b 3c 24 41 89 c0 44 8b 54 24 08 b8 01 01 00 00 89 f4\n | RSP: 002b:00007f3b87d259f0 EFLAGS: 00000293 ORIG_RAX: 0000000000000101\n | RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007f3b87efcd0e\n | RDX: 0000000000000000 RSI: 00007f3b87d25a80 RDI: 00000000ffffff9c\n | RBP: 00007f3b87d25e90 R08: 0000000000000000 R09: 0000000000000000\n | R10: 0000000000000000 R11: 0000000000000293 R12: 00007ffe188f504e\n | R13: 00007ffe188f504f R14: 00007f3b87d26700 R15: 0000000000000000\n | ---[ end trace 24f53ca58db8180a ]---\n\nSince 'cdev_get()' can already fail to obtain a reference, simply move\nit over to use 'kobject_get_unless_zero()' instead of 'kobject_get()',\nwhich will cause the racing thread to return -ENXIO if the initialising\nthread fails unexpectedly.\n\nCc: Hillf Danton <hdanton@sina.com>\nCc: Andrew Morton <akpm@linux-foundation.org>\nCc: Al Viro <viro@zeniv.linux.org.uk>\nReported-by: syzbot+82defefbbd8527e1c2cb@syzkaller.appspotmail.com\nSigned-off-by: Will Deacon <will@kernel.org>\nCc: stable <stable@vger.kernel.org>\nLink: https://lore.kernel.org/r/20191219120203.32691-1-will@kernel.org\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 0, "dataset": "other", "idx": 446395}
  871. {"func": "static Image *ReadTIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define ThrowTIFFException(severity,message) \\\n{ \\\n if (pixel_info != (MemoryInfo *) NULL) \\\n pixel_info=RelinquishVirtualMemory(pixel_info); \\\n if (quantum_info != (QuantumInfo *) NULL) \\\n quantum_info=DestroyQuantumInfo(quantum_info); \\\n TIFFClose(tiff); \\\n ThrowReaderException(severity,message); \\\n}\n\n const char\n *option;\n\n float\n *chromaticity,\n x_position,\n y_position,\n x_resolution,\n y_resolution;\n\n Image\n *image;\n\n int\n tiff_status;\n\n MagickBooleanType\n more_frames,\n status;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info = (MemoryInfo *) NULL;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n pad;\n\n ssize_t\n y;\n\n TIFF\n *tiff;\n\n TIFFMethodType\n method;\n\n uint16\n compress_tag,\n bits_per_sample,\n endian,\n extra_samples,\n interlace,\n max_sample_value,\n min_sample_value,\n orientation,\n pages,\n photometric,\n *sample_info,\n sample_format,\n samples_per_pixel,\n units,\n value;\n\n uint32\n height,\n rows_per_strip,\n width;\n\n unsigned char\n *pixels;\n\n void\n *sans[2] = { NULL, NULL };\n\n /*\n Open image.\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,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) SetMagickThreadValue(tiff_exception,exception);\n tiff=TIFFClientOpen(image->filename,\"rb\",(thandle_t) image,TIFFReadBlob,\n TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n TIFFUnmapBlob);\n if (tiff == (TIFF *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (exception->severity > ErrorException)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (image_info->number_scenes != 0)\n {\n /*\n Generate blank images for subimage specification (e.g. image.tif[4].\n We need to check the number of directores because it is possible that\n the subimage(s) are stored in the photoshop profile.\n */\n if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))\n {\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n }\n }\n }\n more_frames=MagickTrue;\n do\n {\n /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */\n photometric=PHOTOMETRIC_RGB;\n if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) &&\n ((bits_per_sample <= 0) || (bits_per_sample > 32)))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\");\n }\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n (void) SetImageProperty(image,\"quantum:format\",\"floating-point\",\n exception);\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-black\",\n exception);\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-white\",\n exception);\n break;\n }\n case PHOTOMETRIC_PALETTE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"palette\",exception);\n break;\n }\n case PHOTOMETRIC_RGB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"RGB\",exception);\n break;\n }\n case PHOTOMETRIC_CIELAB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIELAB\",exception);\n break;\n }\n case PHOTOMETRIC_LOGL:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIE Log2(L)\",\n exception);\n break;\n }\n case PHOTOMETRIC_LOGLUV:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"LOGLUV\",exception);\n break;\n }\n#if defined(PHOTOMETRIC_MASK)\n case PHOTOMETRIC_MASK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"MASK\",exception);\n break;\n }\n#endif\n case PHOTOMETRIC_SEPARATED:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"separated\",exception);\n break;\n }\n case PHOTOMETRIC_YCBCR:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"YCBCR\",exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"unknown\",exception);\n break;\n }\n }\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Geometry: %ux%u\",\n (unsigned int) width,(unsigned int) height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Interlace: %u\",\n interlace);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Bits per sample: %u\",bits_per_sample);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Min sample value: %u\",min_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Max sample value: %u\",max_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Photometric \"\n \"interpretation: %s\",GetImageProperty(image,\"tiff:photometric\",\n exception));\n }\n image->columns=(size_t) width;\n image->rows=(size_t) height;\n image->depth=(size_t) bits_per_sample;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Image depth: %.20g\",\n (double) image->depth);\n image->endian=MSBEndian;\n if (endian == FILLORDER_LSB2MSB)\n image->endian=LSBEndian;\n#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)\n if (TIFFIsBigEndian(tiff) == 0)\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"lsb\",exception);\n image->endian=LSBEndian;\n }\n else\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"msb\",exception);\n image->endian=MSBEndian;\n }\n#endif\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n image->colorspace=GRAYColorspace;\n if (photometric == PHOTOMETRIC_SEPARATED)\n image->colorspace=CMYKColorspace;\n if (photometric == PHOTOMETRIC_CIELAB)\n image->colorspace=LabColorspace;\n if ((photometric == PHOTOMETRIC_YCBCR) && (compress_tag != COMPRESSION_JPEG))\n image->colorspace=YCbCrColorspace;\n status=TIFFGetProfiles(tiff,image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n status=TIFFGetProperties(tiff,image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n option=GetImageOption(image_info,\"tiff:exif-properties\");\n if (IsStringFalse(option) == MagickFalse) /* enabled by default */\n TIFFGetEXIFProperties(tiff,image,exception);\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1))\n {\n image->resolution.x=x_resolution;\n image->resolution.y=y_resolution;\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1)\n {\n if (units == RESUNIT_INCH)\n image->units=PixelsPerInchResolution;\n if (units == RESUNIT_CENTIMETER)\n image->units=PixelsPerCentimeterResolution;\n }\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1))\n {\n image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);\n image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1)\n image->orientation=(OrientationType) orientation;\n if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)\n {\n if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n {\n image->chromaticity.white_point.x=chromaticity[0];\n image->chromaticity.white_point.y=chromaticity[1];\n }\n }\n if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)\n {\n if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n {\n image->chromaticity.red_primary.x=chromaticity[0];\n image->chromaticity.red_primary.y=chromaticity[1];\n image->chromaticity.green_primary.x=chromaticity[2];\n image->chromaticity.green_primary.y=chromaticity[3];\n image->chromaticity.blue_primary.x=chromaticity[4];\n image->chromaticity.blue_primary.y=chromaticity[5];\n }\n }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n if ((compress_tag != COMPRESSION_NONE) &&\n (TIFFIsCODECConfigured(compress_tag) == 0))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"CompressNotSupported\");\n }\n#endif\n switch (compress_tag)\n {\n case COMPRESSION_NONE: image->compression=NoCompression; break;\n case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;\n case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;\n case COMPRESSION_JPEG:\n {\n image->compression=JPEGCompression;\n#if defined(JPEG_SUPPORT)\n {\n char\n sampling_factor[MagickPathExtent];\n\n uint16\n horizontal,\n vertical;\n\n tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,\n &vertical);\n if (tiff_status == 1)\n {\n (void) FormatLocaleString(sampling_factor,MagickPathExtent,\n \"%dx%d\",horizontal,vertical);\n (void) SetImageProperty(image,\"jpeg:sampling-factor\",\n sampling_factor,exception);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Sampling Factors: %s\",sampling_factor);\n }\n }\n#endif\n break;\n }\n case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;\n#if defined(COMPRESSION_LZMA)\n case COMPRESSION_LZMA: image->compression=LZMACompression; break;\n#endif\n case COMPRESSION_LZW: image->compression=LZWCompression; break;\n case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;\n case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;\n#if defined(COMPRESSION_WEBP)\n case COMPRESSION_WEBP: image->compression=WebPCompression; break;\n#endif\n#if defined(COMPRESSION_ZSTD)\n case COMPRESSION_ZSTD: image->compression=ZstdCompression; break;\n#endif\n default: image->compression=RLECompression; break;\n }\n quantum_info=(QuantumInfo *) NULL;\n if ((photometric == PHOTOMETRIC_PALETTE) &&\n (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))\n {\n size_t\n colors;\n\n colors=(size_t) GetQuantumRange(bits_per_sample)+1;\n if (AcquireImageColormap(image,colors,exception) == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n value=(unsigned short) image->scene;\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1)\n image->scene=value;\n if (image->storage_class == PseudoClass)\n {\n size_t\n range;\n\n uint16\n *blue_colormap,\n *green_colormap,\n *red_colormap;\n\n /*\n Initialize colormap.\n */\n tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,\n &green_colormap,&blue_colormap);\n if (tiff_status == 1)\n {\n if ((red_colormap != (uint16 *) NULL) &&\n (green_colormap != (uint16 *) NULL) &&\n (blue_colormap != (uint16 *) NULL))\n {\n range=255; /* might be old style 8-bit colormap */\n for (i=0; i < (ssize_t) image->colors; i++)\n if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||\n (blue_colormap[i] >= 256))\n {\n range=65535;\n break;\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=ClampToQuantum(((double)\n QuantumRange*red_colormap[i])/range);\n image->colormap[i].green=ClampToQuantum(((double)\n QuantumRange*green_colormap[i])/range);\n image->colormap[i].blue=ClampToQuantum(((double)\n QuantumRange*blue_colormap[i])/range);\n }\n }\n }\n }\n if (image_info->ping != MagickFalse)\n {\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n goto next_tiff_frame;\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n status=SetImageColorspace(image,image->colorspace,exception);\n status&=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n /*\n Allocate memory for the image and pixel buffer.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (sample_format == SAMPLEFORMAT_UINT)\n status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_INT)\n status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=MagickTrue;\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n quantum_info->min_is_white=MagickFalse;\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n quantum_info->min_is_white=MagickTrue;\n break;\n }\n default:\n break;\n }\n extra_samples=0;\n tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,\n &sample_info,sans);\n if (tiff_status == 1)\n {\n (void) SetImageProperty(image,\"tiff:alpha\",\"unspecified\",exception);\n if (extra_samples == 0)\n {\n if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))\n image->alpha_trait=BlendPixelTrait;\n }\n else\n for (i=0; i < extra_samples; i++)\n {\n image->alpha_trait=BlendPixelTrait;\n if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)\n {\n SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"associated\",\n exception);\n }\n else\n if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)\n {\n SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"unassociated\",\n exception);\n }\n }\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n if (samples_per_pixel > MaxPixelChannels)\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n }\n method=ReadGenericMethod;\n rows_per_strip=(uint32) image->rows;\n if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)\n {\n char\n buffer[MagickPathExtent];\n\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%u\",\n (unsigned int) rows_per_strip);\n (void) SetImageProperty(image,\"tiff:rows-per-strip\",buffer,exception);\n method=ReadStripMethod;\n if (rows_per_strip > (uint32) image->rows)\n rows_per_strip=(uint32) image->rows;\n }\n if (TIFFIsTiled(tiff) != MagickFalse)\n {\n uint32\n columns,\n rows;\n\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||\n (AcquireMagickResource(HeightResource,rows) == MagickFalse))\n ThrowTIFFException(ImageError,\"WidthOrHeightExceedsLimit\");\n method=ReadTileMethod;\n }\n if (image->compression == JPEGCompression)\n method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,\n samples_per_pixel);\n if (photometric == PHOTOMETRIC_LOGLUV)\n method=ReadGenericMethod;\n quantum_info->endian=LSBEndian;\n quantum_type=RGBQuantum;\n if (TIFFScanlineSize(tiff) <= 0)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((1.0*TIFFScanlineSize(tiff)) > (2.53*GetBlobSize(image)))\n ThrowTIFFException(CorruptImageError,\"InsufficientImageDataInFile\");\n number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t)\n image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/\n log(2.0))),image->columns*rows_per_strip));\n pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) memset(pixels,0,number_pixels*sizeof(uint32));\n quantum_type=IndexQuantum;\n pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n if (image->storage_class == PseudoClass)\n quantum_type=IndexAlphaQuantum;\n else\n quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum;\n }\n else\n if (image->storage_class != PseudoClass)\n quantum_type=GrayQuantum;\n if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE))\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=RGBAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n }\n if (image->colorspace == CMYKColorspace)\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=CMYKAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);\n }\n }\n status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));\n if (status == MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n switch (method)\n {\n case ReadYCCKMethod:\n {\n /*\n Convert YCC TIFF image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n unsigned char\n *p;\n\n tiff_status=TIFFReadPixels(tiff,0,y,(char *) pixels);\n if (tiff_status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n p=pixels;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.402*(double) *(p+2))-179.456)),q);\n SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-\n (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+\n 135.45984)),q);\n SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.772*(double) *(p+1))-226.816)),q);\n SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);\n q+=GetPixelChannels(image);\n p+=4;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadStripMethod:\n {\n register unsigned char\n *p;\n\n size_t\n extent;\n\n ssize_t\n stride,\n strip_id;\n\n tsize_t\n strip_size;\n\n unsigned char\n *strip_pixels;\n\n /*\n Convert stripped TIFF image.\n */\n extent=TIFFStripSize(tiff);\n#if defined(TIFF_VERSION_BIG)\n extent+=image->columns*sizeof(uint64);\n#else\n extent+=image->columns*sizeof(uint32);\n#endif\n strip_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n sizeof(*strip_pixels));\n if (strip_pixels == (unsigned char *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels));\n stride=TIFFVStripSize(tiff,1);\n strip_id=0;\n p=strip_pixels;\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n size_t\n rows_remaining;\n\n switch (i)\n {\n case 0: break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n quantum_type=BlackQuantum;\n break;\n }\n case 4: quantum_type=AlphaQuantum; break;\n }\n rows_remaining=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (rows_remaining == 0)\n {\n strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels,\n TIFFStripSize(tiff));\n if (strip_size == -1)\n break;\n rows_remaining=rows_per_strip;\n if ((y+rows_per_strip) > image->rows)\n rows_remaining=(rows_per_strip-(y+rows_per_strip-\n image->rows));\n p=strip_pixels;\n strip_id++;\n }\n (void) ImportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,quantum_type,p,exception);\n p+=stride;\n rows_remaining--;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n break;\n }\n strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels);\n break;\n }\n case ReadTileMethod:\n {\n register unsigned char\n *p;\n\n size_t\n extent;\n\n uint32\n columns,\n rows;\n\n unsigned char\n *tile_pixels;\n\n /*\n Convert tiled TIFF image.\n */\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n number_pixels=(MagickSizeType) columns*rows;\n if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n extent=TIFFTileSize(tiff);\n#if defined(TIFF_VERSION_BIG)\n extent+=columns*sizeof(uint64);\n#else\n extent+=columns*sizeof(uint32);\n#endif\n tile_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n sizeof(*tile_pixels));\n if (tile_pixels == (unsigned char *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels));\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n switch (i)\n {\n case 0: break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n quantum_type=BlackQuantum;\n break;\n }\n case 4: quantum_type=AlphaQuantum; break;\n }\n for (y=0; y < (ssize_t) image->rows; y+=rows)\n {\n register ssize_t\n x;\n\n size_t\n rows_remaining;\n\n rows_remaining=image->rows-y;\n if ((ssize_t) (y+rows) < (ssize_t) image->rows)\n rows_remaining=rows;\n for (x=0; x < (ssize_t) image->columns; x+=columns)\n {\n size_t\n columns_remaining,\n row;\n\n columns_remaining=image->columns-x;\n if ((ssize_t) (x+columns) < (ssize_t) image->columns)\n columns_remaining=columns;\n if (TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y,0,i) == 0)\n break;\n p=tile_pixels;\n for (row=0; row < rows_remaining; row++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetAuthenticPixels(image,x,y+row,columns_remaining,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,quantum_type,p,exception);\n p+=TIFFTileRowSize(tiff);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n }\n if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i,\n samples_per_pixel);\n if (status == MagickFalse)\n break;\n }\n }\n tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels);\n break;\n }\n case ReadGenericMethod:\n default:\n {\n MemoryInfo\n *generic_info = (MemoryInfo * ) NULL;\n\n register uint32\n *p;\n\n uint32\n *pixels;\n\n /*\n Convert generic TIFF image.\n */\n if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n number_pixels=(MagickSizeType) image->columns*image->rows;\n number_pixels+=image->columns*sizeof(uint32);\n generic_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));\n if (generic_info == (MemoryInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(uint32 *) GetVirtualMemoryBlob(generic_info);\n (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)\n image->rows,(uint32 *) pixels,0);\n p=pixels+(image->columns*image->rows)-1;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n q+=GetPixelChannels(image)*(image->columns-1);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p--;\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) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n generic_info=RelinquishVirtualMemory(generic_info);\n break;\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n SetQuantumImageType(image,quantum_type);\n next_tiff_frame:\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (photometric == PHOTOMETRIC_CIELAB)\n DecodeLabImage(image,exception);\n if ((photometric == PHOTOMETRIC_LOGL) ||\n (photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n {\n image->type=GrayscaleType;\n if (bits_per_sample == 1)\n image->type=BilevelType;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (more_frames != MagickFalse)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,image->scene-1,\n image->scene);\n if (status == MagickFalse)\n break;\n }\n } while ((status != MagickFalse) && (more_frames != MagickFalse));\n TIFFClose(tiff);\n if (status != MagickFalse)\n TIFFReadPhotoshopLayers(image_info,image,exception);\n if ((image_info->number_scenes != 0) &&\n (image_info->scene >= GetImageListLength(image)))\n status=MagickFalse;\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick", "hash": 319829534730769094685806470185595012447, "size": 989, "commit_id": "6ee5059cd3ac8d82714a1ab1321399b88539abf0", "message": "possible TIFF related-heap buffer overflow (alert & POC by Hardik Shah)", "target": 1, "dataset": "other", "idx": 211237}
  872. {"func": "static Image *ReadTIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define ThrowTIFFException(severity,message) \\\n{ \\\n if (pixel_info != (MemoryInfo *) NULL) \\\n pixel_info=RelinquishVirtualMemory(pixel_info); \\\n if (quantum_info != (QuantumInfo *) NULL) \\\n quantum_info=DestroyQuantumInfo(quantum_info); \\\n TIFFClose(tiff); \\\n ThrowReaderException(severity,message); \\\n}\n\n const char\n *option;\n\n float\n *chromaticity,\n x_position,\n y_position,\n x_resolution,\n y_resolution;\n\n Image\n *image;\n\n int\n tiff_status;\n\n MagickBooleanType\n more_frames,\n status;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info = (MemoryInfo *) NULL;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n pad;\n\n ssize_t\n y;\n\n TIFF\n *tiff;\n\n TIFFMethodType\n method;\n\n uint16\n compress_tag,\n bits_per_sample,\n endian,\n extra_samples,\n interlace,\n max_sample_value,\n min_sample_value,\n orientation,\n pages,\n photometric,\n *sample_info,\n sample_format,\n samples_per_pixel,\n units,\n value;\n\n uint32\n height,\n rows_per_strip,\n width;\n\n unsigned char\n *pixels;\n\n void\n *sans[2] = { NULL, NULL };\n\n /*\n Open image.\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,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) SetMagickThreadValue(tiff_exception,exception);\n tiff=TIFFClientOpen(image->filename,\"rb\",(thandle_t) image,TIFFReadBlob,\n TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n TIFFUnmapBlob);\n if (tiff == (TIFF *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (exception->severity > ErrorException)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (image_info->number_scenes != 0)\n {\n /*\n Generate blank images for subimage specification (e.g. image.tif[4].\n We need to check the number of directores because it is possible that\n the subimage(s) are stored in the photoshop profile.\n */\n if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))\n {\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n }\n }\n }\n more_frames=MagickTrue;\n do\n {\n /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */\n photometric=PHOTOMETRIC_RGB;\n if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) &&\n ((bits_per_sample <= 0) || (bits_per_sample > 32)))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\");\n }\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n (void) SetImageProperty(image,\"quantum:format\",\"floating-point\",\n exception);\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-black\",\n exception);\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-white\",\n exception);\n break;\n }\n case PHOTOMETRIC_PALETTE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"palette\",exception);\n break;\n }\n case PHOTOMETRIC_RGB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"RGB\",exception);\n break;\n }\n case PHOTOMETRIC_CIELAB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIELAB\",exception);\n break;\n }\n case PHOTOMETRIC_LOGL:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIE Log2(L)\",\n exception);\n break;\n }\n case PHOTOMETRIC_LOGLUV:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"LOGLUV\",exception);\n break;\n }\n#if defined(PHOTOMETRIC_MASK)\n case PHOTOMETRIC_MASK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"MASK\",exception);\n break;\n }\n#endif\n case PHOTOMETRIC_SEPARATED:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"separated\",exception);\n break;\n }\n case PHOTOMETRIC_YCBCR:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"YCBCR\",exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"unknown\",exception);\n break;\n }\n }\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Geometry: %ux%u\",\n (unsigned int) width,(unsigned int) height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Interlace: %u\",\n interlace);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Bits per sample: %u\",bits_per_sample);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Min sample value: %u\",min_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Max sample value: %u\",max_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Photometric \"\n \"interpretation: %s\",GetImageProperty(image,\"tiff:photometric\",\n exception));\n }\n image->columns=(size_t) width;\n image->rows=(size_t) height;\n image->depth=(size_t) bits_per_sample;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Image depth: %.20g\",\n (double) image->depth);\n image->endian=MSBEndian;\n if (endian == FILLORDER_LSB2MSB)\n image->endian=LSBEndian;\n#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)\n if (TIFFIsBigEndian(tiff) == 0)\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"lsb\",exception);\n image->endian=LSBEndian;\n }\n else\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"msb\",exception);\n image->endian=MSBEndian;\n }\n#endif\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n image->colorspace=GRAYColorspace;\n if (photometric == PHOTOMETRIC_SEPARATED)\n image->colorspace=CMYKColorspace;\n if (photometric == PHOTOMETRIC_CIELAB)\n image->colorspace=LabColorspace;\n if ((photometric == PHOTOMETRIC_YCBCR) && (compress_tag != COMPRESSION_JPEG))\n image->colorspace=YCbCrColorspace;\n status=TIFFGetProfiles(tiff,image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n status=TIFFGetProperties(tiff,image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n option=GetImageOption(image_info,\"tiff:exif-properties\");\n if (IsStringFalse(option) == MagickFalse) /* enabled by default */\n TIFFGetEXIFProperties(tiff,image,exception);\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1))\n {\n image->resolution.x=x_resolution;\n image->resolution.y=y_resolution;\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1)\n {\n if (units == RESUNIT_INCH)\n image->units=PixelsPerInchResolution;\n if (units == RESUNIT_CENTIMETER)\n image->units=PixelsPerCentimeterResolution;\n }\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1))\n {\n image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);\n image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1)\n image->orientation=(OrientationType) orientation;\n if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)\n {\n if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n {\n image->chromaticity.white_point.x=chromaticity[0];\n image->chromaticity.white_point.y=chromaticity[1];\n }\n }\n if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)\n {\n if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n {\n image->chromaticity.red_primary.x=chromaticity[0];\n image->chromaticity.red_primary.y=chromaticity[1];\n image->chromaticity.green_primary.x=chromaticity[2];\n image->chromaticity.green_primary.y=chromaticity[3];\n image->chromaticity.blue_primary.x=chromaticity[4];\n image->chromaticity.blue_primary.y=chromaticity[5];\n }\n }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n if ((compress_tag != COMPRESSION_NONE) &&\n (TIFFIsCODECConfigured(compress_tag) == 0))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"CompressNotSupported\");\n }\n#endif\n switch (compress_tag)\n {\n case COMPRESSION_NONE: image->compression=NoCompression; break;\n case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;\n case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;\n case COMPRESSION_JPEG:\n {\n image->compression=JPEGCompression;\n#if defined(JPEG_SUPPORT)\n {\n char\n sampling_factor[MagickPathExtent];\n\n uint16\n horizontal,\n vertical;\n\n tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,\n &vertical);\n if (tiff_status == 1)\n {\n (void) FormatLocaleString(sampling_factor,MagickPathExtent,\n \"%dx%d\",horizontal,vertical);\n (void) SetImageProperty(image,\"jpeg:sampling-factor\",\n sampling_factor,exception);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Sampling Factors: %s\",sampling_factor);\n }\n }\n#endif\n break;\n }\n case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;\n#if defined(COMPRESSION_LZMA)\n case COMPRESSION_LZMA: image->compression=LZMACompression; break;\n#endif\n case COMPRESSION_LZW: image->compression=LZWCompression; break;\n case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;\n case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;\n#if defined(COMPRESSION_WEBP)\n case COMPRESSION_WEBP: image->compression=WebPCompression; break;\n#endif\n#if defined(COMPRESSION_ZSTD)\n case COMPRESSION_ZSTD: image->compression=ZstdCompression; break;\n#endif\n default: image->compression=RLECompression; break;\n }\n quantum_info=(QuantumInfo *) NULL;\n if ((photometric == PHOTOMETRIC_PALETTE) &&\n (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))\n {\n size_t\n colors;\n\n colors=(size_t) GetQuantumRange(bits_per_sample)+1;\n if (AcquireImageColormap(image,colors,exception) == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n value=(unsigned short) image->scene;\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1)\n image->scene=value;\n if (image->storage_class == PseudoClass)\n {\n size_t\n range;\n\n uint16\n *blue_colormap,\n *green_colormap,\n *red_colormap;\n\n /*\n Initialize colormap.\n */\n tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,\n &green_colormap,&blue_colormap);\n if (tiff_status == 1)\n {\n if ((red_colormap != (uint16 *) NULL) &&\n (green_colormap != (uint16 *) NULL) &&\n (blue_colormap != (uint16 *) NULL))\n {\n range=255; /* might be old style 8-bit colormap */\n for (i=0; i < (ssize_t) image->colors; i++)\n if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||\n (blue_colormap[i] >= 256))\n {\n range=65535;\n break;\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=ClampToQuantum(((double)\n QuantumRange*red_colormap[i])/range);\n image->colormap[i].green=ClampToQuantum(((double)\n QuantumRange*green_colormap[i])/range);\n image->colormap[i].blue=ClampToQuantum(((double)\n QuantumRange*blue_colormap[i])/range);\n }\n }\n }\n }\n if (image_info->ping != MagickFalse)\n {\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n goto next_tiff_frame;\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n status=SetImageColorspace(image,image->colorspace,exception);\n status&=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n /*\n Allocate memory for the image and pixel buffer.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (sample_format == SAMPLEFORMAT_UINT)\n status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_INT)\n status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=MagickTrue;\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n quantum_info->min_is_white=MagickFalse;\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n quantum_info->min_is_white=MagickTrue;\n break;\n }\n default:\n break;\n }\n extra_samples=0;\n tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,\n &sample_info,sans);\n if (tiff_status == 1)\n {\n (void) SetImageProperty(image,\"tiff:alpha\",\"unspecified\",exception);\n if (extra_samples == 0)\n {\n if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))\n image->alpha_trait=BlendPixelTrait;\n }\n else\n for (i=0; i < extra_samples; i++)\n {\n image->alpha_trait=BlendPixelTrait;\n if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)\n {\n SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"associated\",\n exception);\n }\n else\n if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)\n {\n SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"unassociated\",\n exception);\n }\n }\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n if (samples_per_pixel > MaxPixelChannels)\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n }\n method=ReadGenericMethod;\n rows_per_strip=(uint32) image->rows;\n if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)\n {\n char\n buffer[MagickPathExtent];\n\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%u\",\n (unsigned int) rows_per_strip);\n (void) SetImageProperty(image,\"tiff:rows-per-strip\",buffer,exception);\n method=ReadStripMethod;\n if (rows_per_strip > (uint32) image->rows)\n rows_per_strip=(uint32) image->rows;\n }\n if (TIFFIsTiled(tiff) != MagickFalse)\n {\n uint32\n columns,\n rows;\n\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||\n (AcquireMagickResource(HeightResource,rows) == MagickFalse))\n ThrowTIFFException(ImageError,\"WidthOrHeightExceedsLimit\");\n method=ReadTileMethod;\n }\n if (image->compression == JPEGCompression)\n method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,\n samples_per_pixel);\n if (photometric == PHOTOMETRIC_LOGLUV)\n method=ReadGenericMethod;\n quantum_info->endian=LSBEndian;\n quantum_type=RGBQuantum;\n if (TIFFScanlineSize(tiff) <= 0)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((1.0*TIFFScanlineSize(tiff)) > (2.53*GetBlobSize(image)))\n ThrowTIFFException(CorruptImageError,\"InsufficientImageDataInFile\");\n number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t)\n image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/\n log(2.0))),image->columns*rows_per_strip));\n pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) memset(pixels,0,number_pixels*sizeof(uint32));\n quantum_type=IndexQuantum;\n pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n if (image->storage_class == PseudoClass)\n quantum_type=IndexAlphaQuantum;\n else\n quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum;\n }\n else\n if (image->storage_class != PseudoClass)\n quantum_type=GrayQuantum;\n if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE))\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=RGBAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n }\n if (image->colorspace == CMYKColorspace)\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=CMYKAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);\n }\n }\n status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));\n if (status == MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n switch (method)\n {\n case ReadYCCKMethod:\n {\n /*\n Convert YCC TIFF image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n unsigned char\n *p;\n\n tiff_status=TIFFReadPixels(tiff,0,y,(char *) pixels);\n if (tiff_status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n p=pixels;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.402*(double) *(p+2))-179.456)),q);\n SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-\n (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+\n 135.45984)),q);\n SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.772*(double) *(p+1))-226.816)),q);\n SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);\n q+=GetPixelChannels(image);\n p+=4;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadStripMethod:\n {\n register unsigned char\n *p;\n\n size_t\n extent;\n\n ssize_t\n stride,\n strip_id;\n\n tsize_t\n strip_size;\n\n unsigned char\n *strip_pixels;\n\n /*\n Convert stripped TIFF image.\n */\n extent=TIFFStripSize(tiff);\n#if defined(TIFF_VERSION_BIG)\n extent+=image->columns*sizeof(uint64);\n#else\n extent+=image->columns*sizeof(uint32);\n#endif\n strip_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n 2*sizeof(*strip_pixels));\n if (strip_pixels == (unsigned char *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels));\n stride=TIFFVStripSize(tiff,1);\n strip_id=0;\n p=strip_pixels;\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n size_t\n rows_remaining;\n\n switch (i)\n {\n case 0: break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n quantum_type=BlackQuantum;\n break;\n }\n case 4: quantum_type=AlphaQuantum; break;\n }\n rows_remaining=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (rows_remaining == 0)\n {\n strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels,\n TIFFStripSize(tiff));\n if (strip_size == -1)\n break;\n rows_remaining=rows_per_strip;\n if ((y+rows_per_strip) > image->rows)\n rows_remaining=(rows_per_strip-(y+rows_per_strip-\n image->rows));\n p=strip_pixels;\n strip_id++;\n }\n (void) ImportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,quantum_type,p,exception);\n p+=stride;\n rows_remaining--;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n break;\n }\n strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels);\n break;\n }\n case ReadTileMethod:\n {\n register unsigned char\n *p;\n\n size_t\n extent;\n\n uint32\n columns,\n rows;\n\n unsigned char\n *tile_pixels;\n\n /*\n Convert tiled TIFF image.\n */\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n number_pixels=(MagickSizeType) columns*rows;\n if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n extent=TIFFTileSize(tiff);\n#if defined(TIFF_VERSION_BIG)\n extent+=columns*sizeof(uint64);\n#else\n extent+=columns*sizeof(uint32);\n#endif\n tile_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n sizeof(*tile_pixels));\n if (tile_pixels == (unsigned char *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels));\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n switch (i)\n {\n case 0: break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n quantum_type=BlackQuantum;\n break;\n }\n case 4: quantum_type=AlphaQuantum; break;\n }\n for (y=0; y < (ssize_t) image->rows; y+=rows)\n {\n register ssize_t\n x;\n\n size_t\n rows_remaining;\n\n rows_remaining=image->rows-y;\n if ((ssize_t) (y+rows) < (ssize_t) image->rows)\n rows_remaining=rows;\n for (x=0; x < (ssize_t) image->columns; x+=columns)\n {\n size_t\n columns_remaining,\n row;\n\n columns_remaining=image->columns-x;\n if ((ssize_t) (x+columns) < (ssize_t) image->columns)\n columns_remaining=columns;\n if (TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y,0,i) == 0)\n break;\n p=tile_pixels;\n for (row=0; row < rows_remaining; row++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetAuthenticPixels(image,x,y+row,columns_remaining,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,quantum_type,p,exception);\n p+=TIFFTileRowSize(tiff);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n }\n if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i,\n samples_per_pixel);\n if (status == MagickFalse)\n break;\n }\n }\n tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels);\n break;\n }\n case ReadGenericMethod:\n default:\n {\n MemoryInfo\n *generic_info = (MemoryInfo * ) NULL;\n\n register uint32\n *p;\n\n uint32\n *pixels;\n\n /*\n Convert generic TIFF image.\n */\n if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n number_pixels=(MagickSizeType) image->columns*image->rows;\n number_pixels+=image->columns*sizeof(uint32);\n generic_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));\n if (generic_info == (MemoryInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(uint32 *) GetVirtualMemoryBlob(generic_info);\n (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)\n image->rows,(uint32 *) pixels,0);\n p=pixels+(image->columns*image->rows)-1;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n q+=GetPixelChannels(image)*(image->columns-1);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p--;\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) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n generic_info=RelinquishVirtualMemory(generic_info);\n break;\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n SetQuantumImageType(image,quantum_type);\n next_tiff_frame:\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (photometric == PHOTOMETRIC_CIELAB)\n DecodeLabImage(image,exception);\n if ((photometric == PHOTOMETRIC_LOGL) ||\n (photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n {\n image->type=GrayscaleType;\n if (bits_per_sample == 1)\n image->type=BilevelType;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (more_frames != MagickFalse)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,image->scene-1,\n image->scene);\n if (status == MagickFalse)\n break;\n }\n } while ((status != MagickFalse) && (more_frames != MagickFalse));\n TIFFClose(tiff);\n if (status != MagickFalse)\n TIFFReadPhotoshopLayers(image_info,image,exception);\n if ((image_info->number_scenes != 0) &&\n (image_info->scene >= GetImageListLength(image)))\n status=MagickFalse;\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick", "hash": 83966095014944881926814286235105422470, "size": 989, "commit_id": "6ee5059cd3ac8d82714a1ab1321399b88539abf0", "message": "possible TIFF related-heap buffer overflow (alert & POC by Hardik Shah)", "target": 0, "dataset": "other", "idx": 447633}
  873. {"func": "static apr_byte_t oidc_validate_post_logout_url(request_rec *r, const char *url,\n\t\tchar **err_str, char **err_desc) {\n\tapr_uri_t uri;\n\tconst char *c_host = NULL;\n\n\tif (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {\n\t\t*err_str = apr_pstrdup(r->pool, \"Malformed URL\");\n\t\t*err_desc = apr_psprintf(r->pool, \"Logout URL malformed: %s\", url);\n\t\toidc_error(r, \"%s: %s\", *err_str, *err_desc);\n\t\treturn FALSE;\n\t}\n\n\tc_host = oidc_get_current_url_host(r);\n\tif ((uri.hostname != NULL)\n\t\t\t&& ((strstr(c_host, uri.hostname) == NULL)\n\t\t\t\t\t|| (strstr(uri.hostname, c_host) == NULL))) {\n\t\t*err_str = apr_pstrdup(r->pool, \"Invalid Request\");\n\t\t*err_desc =\n\t\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\t\"logout value \\\"%s\\\" does not match the hostname of the current request \\\"%s\\\"\",\n\t\t\t\t\t\tapr_uri_unparse(r->pool, &uri, 0), c_host);\n\t\toidc_error(r, \"%s: %s\", *err_str, *err_desc);\n\t\treturn FALSE;\n\t} else if (strstr(url, \"/\") != url) {\n\t\t*err_str = apr_pstrdup(r->pool, \"Malformed URL\");\n\t\t*err_desc =\n\t\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\t\"No hostname was parsed and it does not seem to be relative, i.e starting with '/': %s\",\n\t\t\t\t\t\turl);\n\t\toidc_error(r, \"%s: %s\", *err_str, *err_desc);\n\t\treturn FALSE;\n\t}\n\n\t/* validate the URL to prevent HTTP header splitting */\n\tif (((strstr(url, \"\\n\") != NULL) || strstr(url, \"\\r\") != NULL)) {\n\t\t*err_str = apr_pstrdup(r->pool, \"Invalid Request\");\n\t\t*err_desc =\n\t\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\t\"logout value \\\"%s\\\" contains illegal \\\"\\n\\\" or \\\"\\r\\\" character(s)\",\n\t\t\t\t\t\turl);\n\t\toidc_error(r, \"%s: %s\", *err_str, *err_desc);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "project": "mod_auth_openidc", "hash": 194756554862366516881552658213654354928, "size": 46, "commit_id": "ce37080c6aea30aabae8b4a9b4eea7808445cc8e", "message": "2.4.0.2 oops\n\nSigned-off-by: Hans Zandbelt <hans.zandbelt@zmartzone.eu>", "target": 1, "dataset": "other", "idx": 211253}
  874. {"func": "static apr_byte_t oidc_validate_post_logout_url(request_rec *r, const char *url,\n\t\tchar **err_str, char **err_desc) {\n\tapr_uri_t uri;\n\tconst char *c_host = NULL;\n\n\tif (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {\n\t\t*err_str = apr_pstrdup(r->pool, \"Malformed URL\");\n\t\t*err_desc = apr_psprintf(r->pool, \"Logout URL malformed: %s\", url);\n\t\toidc_error(r, \"%s: %s\", *err_str, *err_desc);\n\t\treturn FALSE;\n\t}\n\n\tc_host = oidc_get_current_url_host(r);\n\tif ((uri.hostname != NULL)\n\t\t\t&& ((strstr(c_host, uri.hostname) == NULL)\n\t\t\t\t\t|| (strstr(uri.hostname, c_host) == NULL))) {\n\t\t*err_str = apr_pstrdup(r->pool, \"Invalid Request\");\n\t\t*err_desc =\n\t\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\t\"logout value \\\"%s\\\" does not match the hostname of the current request \\\"%s\\\"\",\n\t\t\t\t\t\tapr_uri_unparse(r->pool, &uri, 0), c_host);\n\t\toidc_error(r, \"%s: %s\", *err_str, *err_desc);\n\t\treturn FALSE;\n\t} else if ((uri.hostname == NULL) && (strstr(url, \"/\") != url)) {\n\t\t*err_str = apr_pstrdup(r->pool, \"Malformed URL\");\n\t\t*err_desc =\n\t\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\t\"No hostname was parsed and it does not seem to be relative, i.e starting with '/': %s\",\n\t\t\t\t\t\turl);\n\t\toidc_error(r, \"%s: %s\", *err_str, *err_desc);\n\t\treturn FALSE;\n\t}\n\n\t/* validate the URL to prevent HTTP header splitting */\n\tif (((strstr(url, \"\\n\") != NULL) || strstr(url, \"\\r\") != NULL)) {\n\t\t*err_str = apr_pstrdup(r->pool, \"Invalid Request\");\n\t\t*err_desc =\n\t\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\t\"logout value \\\"%s\\\" contains illegal \\\"\\n\\\" or \\\"\\r\\\" character(s)\",\n\t\t\t\t\t\turl);\n\t\toidc_error(r, \"%s: %s\", *err_str, *err_desc);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "project": "mod_auth_openidc", "hash": 168048052487772235272643922731757152176, "size": 46, "commit_id": "ce37080c6aea30aabae8b4a9b4eea7808445cc8e", "message": "2.4.0.2 oops\n\nSigned-off-by: Hans Zandbelt <hans.zandbelt@zmartzone.eu>", "target": 0, "dataset": "other", "idx": 447708}
  875. {"func": "int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr)\n{\n\tjp2_box_t *box;\n\tjp2_ftyp_t *ftyp;\n\tjp2_ihdr_t *ihdr;\n\tjas_stream_t *tmpstream;\n\tint allcmptssame;\n\tjp2_bpcc_t *bpcc;\n\tlong len;\n\tuint_fast16_t cmptno;\n\tjp2_colr_t *colr;\n\tchar buf[4096];\n\tuint_fast32_t overhead;\n\tjp2_cdefchan_t *cdefchanent;\n\tjp2_cdef_t *cdef;\n\tint i;\n\tuint_fast32_t typeasoc;\n\tjas_iccprof_t *iccprof;\n\tjas_stream_t *iccstream;\n\tint pos;\n\tint needcdef;\n\tint prec;\n\tint sgnd;\n\n\tbox = 0;\n\ttmpstream = 0;\n\ticcstream = 0;\n\ticcprof = 0;\n\n\tif (jas_image_numcmpts(image) < 1) {\n\t\tjas_eprintf(\"image must have at least one component\\n\");\n\t\tgoto error;\n\t}\n\n\tallcmptssame = 1;\n\tsgnd = jas_image_cmptsgnd(image, 0);\n\tprec = jas_image_cmptprec(image, 0);\n\tfor (i = 1; i < jas_image_numcmpts(image); ++i) {\n\t\tif (jas_image_cmptsgnd(image, i) != sgnd ||\n\t\t jas_image_cmptprec(image, i) != prec) {\n\t\t\tallcmptssame = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Output the signature box. */\n\n\tif (!(box = jp2_box_create(JP2_BOX_JP))) {\n\t\tjas_eprintf(\"cannot create JP box\\n\");\n\t\tgoto error;\n\t}\n\tbox->data.jp.magic = JP2_JP_MAGIC;\n\tif (jp2_box_put(box, out)) {\n\t\tjas_eprintf(\"cannot write JP box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Output the file type box. */\n\n\tif (!(box = jp2_box_create(JP2_BOX_FTYP))) {\n\t\tjas_eprintf(\"cannot create FTYP box\\n\");\n\t\tgoto error;\n\t}\n\tftyp = &box->data.ftyp;\n\tftyp->majver = JP2_FTYP_MAJVER;\n\tftyp->minver = JP2_FTYP_MINVER;\n\tftyp->numcompatcodes = 1;\n\tftyp->compatcodes[0] = JP2_FTYP_COMPATCODE;\n\tif (jp2_box_put(box, out)) {\n\t\tjas_eprintf(\"cannot write FTYP box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/*\n\t * Generate the data portion of the JP2 header box.\n\t * We cannot simply output the header for this box\n\t * since we do not yet know the correct value for the length\n\t * field.\n\t */\n\n\tif (!(tmpstream = jas_stream_memopen(0, 0))) {\n\t\tjas_eprintf(\"cannot create temporary stream\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Generate image header box. */\n\n\tif (!(box = jp2_box_create(JP2_BOX_IHDR))) {\n\t\tjas_eprintf(\"cannot create IHDR box\\n\");\n\t\tgoto error;\n\t}\n\tihdr = &box->data.ihdr;\n\tihdr->width = jas_image_width(image);\n\tihdr->height = jas_image_height(image);\n\tihdr->numcmpts = jas_image_numcmpts(image);\n\tihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0),\n\t jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL;\n\tihdr->comptype = JP2_IHDR_COMPTYPE;\n\tihdr->csunk = 0;\n\tihdr->ipr = 0;\n\tif (jp2_box_put(box, tmpstream)) {\n\t\tjas_eprintf(\"cannot write IHDR box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Generate bits per component box. */\n\n\tif (!allcmptssame) {\n\t\tif (!(box = jp2_box_create(JP2_BOX_BPCC))) {\n\t\t\tjas_eprintf(\"cannot create BPCC box\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tbpcc = &box->data.bpcc;\n\t\tbpcc->numcmpts = jas_image_numcmpts(image);\n\t\tif (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts,\n\t\t sizeof(uint_fast8_t)))) {\n\t\t\tjas_eprintf(\"memory allocation failed\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tfor (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) {\n\t\t\tbpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image,\n\t\t\t cmptno), jas_image_cmptprec(image, cmptno));\n\t\t}\n\t\tif (jp2_box_put(box, tmpstream)) {\n\t\t\tjas_eprintf(\"cannot write BPCC box\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjp2_box_destroy(box);\n\t\tbox = 0;\n\t}\n\n\t/* Generate color specification box. */\n\n\tif (!(box = jp2_box_create(JP2_BOX_COLR))) {\n\t\tjas_eprintf(\"cannot create COLR box\\n\");\n\t\tgoto error;\n\t}\n\tcolr = &box->data.colr;\n\tswitch (jas_image_clrspc(image)) {\n\tcase JAS_CLRSPC_SRGB:\n\tcase JAS_CLRSPC_SYCBCR:\n\tcase JAS_CLRSPC_SGRAY:\n\t\tcolr->method = JP2_COLR_ENUM;\n\t\tcolr->csid = clrspctojp2(jas_image_clrspc(image));\n\t\tcolr->pri = JP2_COLR_PRI;\n\t\tcolr->approx = 0;\n\t\tbreak;\n\tdefault:\n\t\tcolr->method = JP2_COLR_ICC;\n\t\tcolr->pri = JP2_COLR_PRI;\n\t\tcolr->approx = 0;\n\t\t/* Ensure that cmprof_ is not null. */\n\t\tif (!jas_image_cmprof(image)) {\n\t\t\tjas_eprintf(\"CM profile is null\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif (!(iccprof = jas_iccprof_createfromcmprof(\n\t\t jas_image_cmprof(image)))) {\n\t\t\tjas_eprintf(\"cannot create ICC profile\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif (!(iccstream = jas_stream_memopen(0, 0))) {\n\t\t\tjas_eprintf(\"cannot create temporary stream\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif (jas_iccprof_save(iccprof, iccstream)) {\n\t\t\tjas_eprintf(\"cannot write ICC profile\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif ((pos = jas_stream_tell(iccstream)) < 0) {\n\t\t\tjas_eprintf(\"cannot get stream position\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tcolr->iccplen = pos;\n\t\tif (!(colr->iccp = jas_malloc(pos))) {\n\t\t\tjas_eprintf(\"memory allocation failed\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjas_stream_rewind(iccstream);\n\t\tif (jas_stream_read(iccstream, colr->iccp, colr->iccplen) !=\n\t\t colr->iccplen) {\n\t\t\tjas_eprintf(\"cannot read temporary stream\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjas_stream_close(iccstream);\n\t\ticcstream = 0;\n\t\tjas_iccprof_destroy(iccprof);\n\t\ticcprof = 0;\n\t\tbreak;\n\t}\n\tif (jp2_box_put(box, tmpstream)) {\n\t\tjas_eprintf(\"cannot write box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\tneedcdef = 1;\n\tswitch (jas_clrspc_fam(jas_image_clrspc(image))) {\n\tcase JAS_CLRSPC_FAM_RGB:\n\t\tif (jas_image_cmpttype(image, 0) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) &&\n\t\t jas_image_cmpttype(image, 1) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) &&\n\t\t jas_image_cmpttype(image, 2) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))\n\t\t\tneedcdef = 0;\n\t\tbreak;\n\tcase JAS_CLRSPC_FAM_YCBCR:\n\t\tif (jas_image_cmpttype(image, 0) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) &&\n\t\t jas_image_cmpttype(image, 1) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) &&\n\t\t jas_image_cmpttype(image, 2) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))\n\t\t\tneedcdef = 0;\n\t\tbreak;\n\tcase JAS_CLRSPC_FAM_GRAY:\n\t\tif (jas_image_cmpttype(image, 0) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))\n\t\t\tneedcdef = 0;\n\t\tbreak;\n\tdefault:\n\t\tabort();\n\t\tbreak;\n\t}\n\n\tif (needcdef) {\n\t\tif (!(box = jp2_box_create(JP2_BOX_CDEF))) {\n\t\t\tjas_eprintf(\"cannot create CDEF box\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tcdef = &box->data.cdef;\n\t\tcdef->numchans = jas_image_numcmpts(image);\n\t\tcdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t));\n\t\tfor (i = 0; i < jas_image_numcmpts(image); ++i) {\n\t\t\tcdefchanent = &cdef->ents[i];\n\t\t\tcdefchanent->channo = i;\n\t\t\ttypeasoc = jp2_gettypeasoc(jas_image_clrspc(image), jas_image_cmpttype(image, i));\n\t\t\tcdefchanent->type = typeasoc >> 16;\n\t\t\tcdefchanent->assoc = typeasoc & 0x7fff;\n\t\t}\n\t\tif (jp2_box_put(box, tmpstream)) {\n\t\t\tjas_eprintf(\"cannot write CDEF box\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjp2_box_destroy(box);\n\t\tbox = 0;\n\t}\n\n\t/* Determine the total length of the JP2 header box. */\n\n\tlen = jas_stream_tell(tmpstream);\n\tjas_stream_rewind(tmpstream);\n\n\t/*\n\t * Output the JP2 header box and all of the boxes which it contains.\n\t */\n\n\tif (!(box = jp2_box_create(JP2_BOX_JP2H))) {\n\t\tjas_eprintf(\"cannot create JP2H box\\n\");\n\t\tgoto error;\n\t}\n\tbox->len = len + JP2_BOX_HDRLEN(false);\n\tif (jp2_box_put(box, out)) {\n\t\tjas_eprintf(\"cannot write JP2H box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\tif (jas_stream_copy(out, tmpstream, len)) {\n\t\tjas_eprintf(\"cannot copy stream\\n\");\n\t\tgoto error;\n\t}\n\n\tjas_stream_close(tmpstream);\n\ttmpstream = 0;\n\n\t/*\n\t * Output the contiguous code stream box.\n\t */\n\n\tif (!(box = jp2_box_create(JP2_BOX_JP2C))) {\n\t\tjas_eprintf(\"cannot create JP2C box\\n\");\n\t\tgoto error;\n\t}\n\tbox->len = 0;\n\tif (jp2_box_put(box, out)) {\n\t\tjas_eprintf(\"cannot write JP2C box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Output the JPEG-2000 code stream. */\n\n\toverhead = jas_stream_getrwcount(out);\n\tsprintf(buf, \"%s\\n_jp2overhead=%lu\\n\", (optstr ? optstr : \"\"),\n\t (unsigned long) overhead);\n\n\tif (jpc_encode(image, out, buf)) {\n\t\tjas_eprintf(\"jpc_encode failed\\n\");\n\t\tgoto error;\n\t}\n\n\treturn 0;\n\nerror:\n\n\tif (iccprof) {\n\t\tjas_iccprof_destroy(iccprof);\n\t}\n\tif (iccstream) {\n\t\tjas_stream_close(iccstream);\n\t}\n\tif (box) {\n\t\tjp2_box_destroy(box);\n\t}\n\tif (tmpstream) {\n\t\tjas_stream_close(tmpstream);\n\t}\n\treturn -1;\n}", "project": "jasper", "hash": 19879316639441336270204162551441027935, "size": 330, "commit_id": "03db7c81f6a8a92d896249bc673877749987fd7a", "message": "jp2_enc: check number of components before dereferencing them\n\nFixes CVE-2018-20570\n\nCloses https://github.com/jasper-maint/jasper/issues/11\nCloses https://github.com/mdadams/jasper/issues/191", "target": 1, "dataset": "other", "idx": 211483}
  876. {"func": "int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr)\n{\n\tjp2_box_t *box;\n\tjp2_ftyp_t *ftyp;\n\tjp2_ihdr_t *ihdr;\n\tjas_stream_t *tmpstream;\n\tint allcmptssame;\n\tjp2_bpcc_t *bpcc;\n\tlong len;\n\tuint_fast16_t cmptno;\n\tjp2_colr_t *colr;\n\tchar buf[4096];\n\tuint_fast32_t overhead;\n\tjp2_cdefchan_t *cdefchanent;\n\tjp2_cdef_t *cdef;\n\tint i;\n\tuint_fast32_t typeasoc;\n\tjas_iccprof_t *iccprof;\n\tjas_stream_t *iccstream;\n\tint pos;\n\tint needcdef;\n\tint prec;\n\tint sgnd;\n\n\tbox = 0;\n\ttmpstream = 0;\n\ticcstream = 0;\n\ticcprof = 0;\n\n\tif (jas_image_numcmpts(image) < 1) {\n\t\tjas_eprintf(\"image must have at least one component\\n\");\n\t\tgoto error;\n\t}\n\n\tallcmptssame = 1;\n\tsgnd = jas_image_cmptsgnd(image, 0);\n\tprec = jas_image_cmptprec(image, 0);\n\tfor (i = 1; i < jas_image_numcmpts(image); ++i) {\n\t\tif (jas_image_cmptsgnd(image, i) != sgnd ||\n\t\t jas_image_cmptprec(image, i) != prec) {\n\t\t\tallcmptssame = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Output the signature box. */\n\n\tif (!(box = jp2_box_create(JP2_BOX_JP))) {\n\t\tjas_eprintf(\"cannot create JP box\\n\");\n\t\tgoto error;\n\t}\n\tbox->data.jp.magic = JP2_JP_MAGIC;\n\tif (jp2_box_put(box, out)) {\n\t\tjas_eprintf(\"cannot write JP box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Output the file type box. */\n\n\tif (!(box = jp2_box_create(JP2_BOX_FTYP))) {\n\t\tjas_eprintf(\"cannot create FTYP box\\n\");\n\t\tgoto error;\n\t}\n\tftyp = &box->data.ftyp;\n\tftyp->majver = JP2_FTYP_MAJVER;\n\tftyp->minver = JP2_FTYP_MINVER;\n\tftyp->numcompatcodes = 1;\n\tftyp->compatcodes[0] = JP2_FTYP_COMPATCODE;\n\tif (jp2_box_put(box, out)) {\n\t\tjas_eprintf(\"cannot write FTYP box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/*\n\t * Generate the data portion of the JP2 header box.\n\t * We cannot simply output the header for this box\n\t * since we do not yet know the correct value for the length\n\t * field.\n\t */\n\n\tif (!(tmpstream = jas_stream_memopen(0, 0))) {\n\t\tjas_eprintf(\"cannot create temporary stream\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Generate image header box. */\n\n\tif (!(box = jp2_box_create(JP2_BOX_IHDR))) {\n\t\tjas_eprintf(\"cannot create IHDR box\\n\");\n\t\tgoto error;\n\t}\n\tihdr = &box->data.ihdr;\n\tihdr->width = jas_image_width(image);\n\tihdr->height = jas_image_height(image);\n\tihdr->numcmpts = jas_image_numcmpts(image);\n\tihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0),\n\t jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL;\n\tihdr->comptype = JP2_IHDR_COMPTYPE;\n\tihdr->csunk = 0;\n\tihdr->ipr = 0;\n\tif (jp2_box_put(box, tmpstream)) {\n\t\tjas_eprintf(\"cannot write IHDR box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Generate bits per component box. */\n\n\tif (!allcmptssame) {\n\t\tif (!(box = jp2_box_create(JP2_BOX_BPCC))) {\n\t\t\tjas_eprintf(\"cannot create BPCC box\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tbpcc = &box->data.bpcc;\n\t\tbpcc->numcmpts = jas_image_numcmpts(image);\n\t\tif (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts,\n\t\t sizeof(uint_fast8_t)))) {\n\t\t\tjas_eprintf(\"memory allocation failed\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tfor (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) {\n\t\t\tbpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image,\n\t\t\t cmptno), jas_image_cmptprec(image, cmptno));\n\t\t}\n\t\tif (jp2_box_put(box, tmpstream)) {\n\t\t\tjas_eprintf(\"cannot write BPCC box\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjp2_box_destroy(box);\n\t\tbox = 0;\n\t}\n\n\t/* Generate color specification box. */\n\n\tif (!(box = jp2_box_create(JP2_BOX_COLR))) {\n\t\tjas_eprintf(\"cannot create COLR box\\n\");\n\t\tgoto error;\n\t}\n\tcolr = &box->data.colr;\n\tswitch (jas_image_clrspc(image)) {\n\tcase JAS_CLRSPC_SRGB:\n\tcase JAS_CLRSPC_SYCBCR:\n\tcase JAS_CLRSPC_SGRAY:\n\t\tcolr->method = JP2_COLR_ENUM;\n\t\tcolr->csid = clrspctojp2(jas_image_clrspc(image));\n\t\tcolr->pri = JP2_COLR_PRI;\n\t\tcolr->approx = 0;\n\t\tbreak;\n\tdefault:\n\t\tcolr->method = JP2_COLR_ICC;\n\t\tcolr->pri = JP2_COLR_PRI;\n\t\tcolr->approx = 0;\n\t\t/* Ensure that cmprof_ is not null. */\n\t\tif (!jas_image_cmprof(image)) {\n\t\t\tjas_eprintf(\"CM profile is null\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif (!(iccprof = jas_iccprof_createfromcmprof(\n\t\t jas_image_cmprof(image)))) {\n\t\t\tjas_eprintf(\"cannot create ICC profile\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif (!(iccstream = jas_stream_memopen(0, 0))) {\n\t\t\tjas_eprintf(\"cannot create temporary stream\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif (jas_iccprof_save(iccprof, iccstream)) {\n\t\t\tjas_eprintf(\"cannot write ICC profile\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tif ((pos = jas_stream_tell(iccstream)) < 0) {\n\t\t\tjas_eprintf(\"cannot get stream position\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tcolr->iccplen = pos;\n\t\tif (!(colr->iccp = jas_malloc(pos))) {\n\t\t\tjas_eprintf(\"memory allocation failed\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjas_stream_rewind(iccstream);\n\t\tif (jas_stream_read(iccstream, colr->iccp, colr->iccplen) !=\n\t\t colr->iccplen) {\n\t\t\tjas_eprintf(\"cannot read temporary stream\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjas_stream_close(iccstream);\n\t\ticcstream = 0;\n\t\tjas_iccprof_destroy(iccprof);\n\t\ticcprof = 0;\n\t\tbreak;\n\t}\n\tif (jp2_box_put(box, tmpstream)) {\n\t\tjas_eprintf(\"cannot write box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\tneedcdef = 1;\n\tswitch (jas_clrspc_fam(jas_image_clrspc(image))) {\n\tcase JAS_CLRSPC_FAM_RGB:\n\t\tif (jas_image_numcmpts(image) >= 3 &&\n\t\t jas_image_cmpttype(image, 0) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) &&\n\t\t jas_image_cmpttype(image, 1) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) &&\n\t\t jas_image_cmpttype(image, 2) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))\n\t\t\tneedcdef = 0;\n\t\tbreak;\n\tcase JAS_CLRSPC_FAM_YCBCR:\n\t\tif (jas_image_numcmpts(image) >= 3 &&\n\t\t jas_image_cmpttype(image, 0) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) &&\n\t\t jas_image_cmpttype(image, 1) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) &&\n\t\t jas_image_cmpttype(image, 2) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))\n\t\t\tneedcdef = 0;\n\t\tbreak;\n\tcase JAS_CLRSPC_FAM_GRAY:\n\t\tif (jas_image_numcmpts(image) >= 1 &&\n\t\t jas_image_cmpttype(image, 0) ==\n\t\t JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))\n\t\t\tneedcdef = 0;\n\t\tbreak;\n\tdefault:\n\t\tabort();\n\t\tbreak;\n\t}\n\n\tif (needcdef) {\n\t\tif (!(box = jp2_box_create(JP2_BOX_CDEF))) {\n\t\t\tjas_eprintf(\"cannot create CDEF box\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tcdef = &box->data.cdef;\n\t\tcdef->numchans = jas_image_numcmpts(image);\n\t\tcdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t));\n\t\tfor (i = 0; i < jas_image_numcmpts(image); ++i) {\n\t\t\tcdefchanent = &cdef->ents[i];\n\t\t\tcdefchanent->channo = i;\n\t\t\ttypeasoc = jp2_gettypeasoc(jas_image_clrspc(image), jas_image_cmpttype(image, i));\n\t\t\tcdefchanent->type = typeasoc >> 16;\n\t\t\tcdefchanent->assoc = typeasoc & 0x7fff;\n\t\t}\n\t\tif (jp2_box_put(box, tmpstream)) {\n\t\t\tjas_eprintf(\"cannot write CDEF box\\n\");\n\t\t\tgoto error;\n\t\t}\n\t\tjp2_box_destroy(box);\n\t\tbox = 0;\n\t}\n\n\t/* Determine the total length of the JP2 header box. */\n\n\tlen = jas_stream_tell(tmpstream);\n\tjas_stream_rewind(tmpstream);\n\n\t/*\n\t * Output the JP2 header box and all of the boxes which it contains.\n\t */\n\n\tif (!(box = jp2_box_create(JP2_BOX_JP2H))) {\n\t\tjas_eprintf(\"cannot create JP2H box\\n\");\n\t\tgoto error;\n\t}\n\tbox->len = len + JP2_BOX_HDRLEN(false);\n\tif (jp2_box_put(box, out)) {\n\t\tjas_eprintf(\"cannot write JP2H box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\tif (jas_stream_copy(out, tmpstream, len)) {\n\t\tjas_eprintf(\"cannot copy stream\\n\");\n\t\tgoto error;\n\t}\n\n\tjas_stream_close(tmpstream);\n\ttmpstream = 0;\n\n\t/*\n\t * Output the contiguous code stream box.\n\t */\n\n\tif (!(box = jp2_box_create(JP2_BOX_JP2C))) {\n\t\tjas_eprintf(\"cannot create JP2C box\\n\");\n\t\tgoto error;\n\t}\n\tbox->len = 0;\n\tif (jp2_box_put(box, out)) {\n\t\tjas_eprintf(\"cannot write JP2C box\\n\");\n\t\tgoto error;\n\t}\n\tjp2_box_destroy(box);\n\tbox = 0;\n\n\t/* Output the JPEG-2000 code stream. */\n\n\toverhead = jas_stream_getrwcount(out);\n\tsprintf(buf, \"%s\\n_jp2overhead=%lu\\n\", (optstr ? optstr : \"\"),\n\t (unsigned long) overhead);\n\n\tif (jpc_encode(image, out, buf)) {\n\t\tjas_eprintf(\"jpc_encode failed\\n\");\n\t\tgoto error;\n\t}\n\n\treturn 0;\n\nerror:\n\n\tif (iccprof) {\n\t\tjas_iccprof_destroy(iccprof);\n\t}\n\tif (iccstream) {\n\t\tjas_stream_close(iccstream);\n\t}\n\tif (box) {\n\t\tjp2_box_destroy(box);\n\t}\n\tif (tmpstream) {\n\t\tjas_stream_close(tmpstream);\n\t}\n\treturn -1;\n}", "project": "jasper", "hash": 151144374110773996368945460482067623366, "size": 333, "commit_id": "03db7c81f6a8a92d896249bc673877749987fd7a", "message": "jp2_enc: check number of components before dereferencing them\n\nFixes CVE-2018-20570\n\nCloses https://github.com/jasper-maint/jasper/issues/11\nCloses https://github.com/mdadams/jasper/issues/191", "target": 0, "dataset": "other", "idx": 448645}
  877. {"func": "static BOOL clear_decompress_subcode_rlex(wStream* s, UINT32 bitmapDataByteCount, UINT32 width,\n UINT32 height, BYTE* pDstData, UINT32 DstFormat,\n UINT32 nDstStep, UINT32 nXDstRel, UINT32 nYDstRel,\n UINT32 nDstWidth, UINT32 nDstHeight)\n{\n\tUINT32 x = 0, y = 0;\n\tUINT32 i;\n\tUINT32 pixelCount;\n\tUINT32 bitmapDataOffset;\n\tUINT32 pixelIndex;\n\tUINT32 numBits;\n\tBYTE startIndex;\n\tBYTE stopIndex;\n\tBYTE suiteIndex;\n\tBYTE suiteDepth;\n\tBYTE paletteCount;\n\tUINT32 palette[128] = { 0 };\n\n\tif (Stream_GetRemainingLength(s) < bitmapDataByteCount)\n\t{\n\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [%\" PRIu32 \" expected]\",\n\t\t Stream_GetRemainingLength(s), bitmapDataByteCount);\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT8(s, paletteCount);\n\tbitmapDataOffset = 1 + (paletteCount * 3);\n\n\tif ((paletteCount > 127) || (paletteCount < 1))\n\t{\n\t\tWLog_ERR(TAG, \"paletteCount %\" PRIu8 \"\", paletteCount);\n\t\treturn FALSE;\n\t}\n\n\tfor (i = 0; i < paletteCount; i++)\n\t{\n\t\tBYTE r, g, b;\n\t\tStream_Read_UINT8(s, b);\n\t\tStream_Read_UINT8(s, g);\n\t\tStream_Read_UINT8(s, r);\n\t\tpalette[i] = FreeRDPGetColor(DstFormat, r, g, b, 0xFF);\n\t}\n\n\tpixelIndex = 0;\n\tpixelCount = width * height;\n\tnumBits = CLEAR_LOG2_FLOOR[paletteCount - 1] + 1;\n\n\twhile (bitmapDataOffset < bitmapDataByteCount)\n\t{\n\t\tUINT32 tmp;\n\t\tUINT32 color;\n\t\tUINT32 runLengthFactor;\n\n\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [2 expected]\", Stream_GetRemainingLength(s));\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tStream_Read_UINT8(s, tmp);\n\t\tStream_Read_UINT8(s, runLengthFactor);\n\t\tbitmapDataOffset += 2;\n\t\tsuiteDepth = (tmp >> numBits) & CLEAR_8BIT_MASKS[(8 - numBits)];\n\t\tstopIndex = tmp & CLEAR_8BIT_MASKS[numBits];\n\t\tstartIndex = stopIndex - suiteDepth;\n\n\t\tif (runLengthFactor >= 0xFF)\n\t\t{\n\t\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [2 expected]\", Stream_GetRemainingLength(s));\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\tStream_Read_UINT16(s, runLengthFactor);\n\t\t\tbitmapDataOffset += 2;\n\n\t\t\tif (runLengthFactor >= 0xFFFF)\n\t\t\t{\n\t\t\t\tif (Stream_GetRemainingLength(s) < 4)\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [4 expected]\",\n\t\t\t\t\t Stream_GetRemainingLength(s));\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tStream_Read_UINT32(s, runLengthFactor);\n\t\t\t\tbitmapDataOffset += 4;\n\t\t\t}\n\t\t}\n\n\t\tif (startIndex >= paletteCount)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"startIndex %\" PRIu8 \" > paletteCount %\" PRIu8 \"]\", startIndex,\n\t\t\t paletteCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tif (stopIndex >= paletteCount)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"stopIndex %\" PRIu8 \" > paletteCount %\" PRIu8 \"]\", stopIndex,\n\t\t\t paletteCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tsuiteIndex = startIndex;\n\n\t\tif (suiteIndex > 127)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"suiteIndex %\" PRIu8 \" > 127]\", suiteIndex);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tcolor = palette[suiteIndex];\n\n\t\tif ((pixelIndex + runLengthFactor) > pixelCount)\n\t\t{\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"pixelIndex %\" PRIu32 \" + runLengthFactor %\" PRIu32 \" > pixelCount %\" PRIu32\n\t\t\t \"\",\n\t\t\t pixelIndex, runLengthFactor, pixelCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tfor (i = 0; i < runLengthFactor; i++)\n\t\t{\n\t\t\tBYTE* pTmpData =\n\t\t\t &pDstData[(nXDstRel + x) * GetBytesPerPixel(DstFormat) + (nYDstRel + y) * nDstStep];\n\n\t\t\tif ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight))\n\t\t\t\tWriteColor(pTmpData, DstFormat, color);\n\n\t\t\tif (++x >= width)\n\t\t\t{\n\t\t\t\ty++;\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t}\n\n\t\tpixelIndex += runLengthFactor;\n\n\t\tif ((pixelIndex + (suiteDepth + 1)) > pixelCount)\n\t\t{\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"pixelIndex %\" PRIu32 \" + suiteDepth %\" PRIu8 \" + 1 > pixelCount %\" PRIu32 \"\",\n\t\t\t pixelIndex, suiteDepth, pixelCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tfor (i = 0; i <= suiteDepth; i++)\n\t\t{\n\t\t\tBYTE* pTmpData =\n\t\t\t &pDstData[(nXDstRel + x) * GetBytesPerPixel(DstFormat) + (nYDstRel + y) * nDstStep];\n\t\t\tUINT32 color = palette[suiteIndex];\n\n\t\t\tif (suiteIndex > 127)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"suiteIndex %\" PRIu8 \" > 127\", suiteIndex);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\tsuiteIndex++;\n\n\t\t\tif ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight))\n\t\t\t\tWriteColor(pTmpData, DstFormat, color);\n\n\t\t\tif (++x >= width)\n\t\t\t{\n\t\t\t\ty++;\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t}\n\n\t\tpixelIndex += (suiteDepth + 1);\n\t}\n\n\tif (pixelIndex != pixelCount)\n\t{\n\t\tWLog_ERR(TAG, \"pixelIndex %\" PRIu32 \" != pixelCount %\" PRIu32 \"\", pixelIndex, pixelCount);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 145478480184200339868644033923186345312, "size": 184, "commit_id": "363d7046dfec4003b91aecf7867e3b05905f3843", "message": "Fixed oob read in clear_decompress_subcode_rlex\n\nFixed length checks before stream read.\nThanks to hac425 CVE-2020-11040", "target": 1, "dataset": "other", "idx": 211489}
  878. {"func": "static BOOL clear_decompress_subcode_rlex(wStream* s, UINT32 bitmapDataByteCount, UINT32 width,\n UINT32 height, BYTE* pDstData, UINT32 DstFormat,\n UINT32 nDstStep, UINT32 nXDstRel, UINT32 nYDstRel,\n UINT32 nDstWidth, UINT32 nDstHeight)\n{\n\tUINT32 x = 0, y = 0;\n\tUINT32 i;\n\tUINT32 pixelCount;\n\tUINT32 bitmapDataOffset;\n\tsize_t pixelIndex;\n\tUINT32 numBits;\n\tBYTE startIndex;\n\tBYTE stopIndex;\n\tBYTE suiteIndex;\n\tBYTE suiteDepth;\n\tBYTE paletteCount;\n\tUINT32 palette[128] = { 0 };\n\n\tif (Stream_GetRemainingLength(s) < bitmapDataByteCount)\n\t{\n\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [%\" PRIu32 \" expected]\",\n\t\t Stream_GetRemainingLength(s), bitmapDataByteCount);\n\t\treturn FALSE;\n\t}\n\n\tif (Stream_GetRemainingLength(s) < 1)\n\t\treturn FALSE;\n\tStream_Read_UINT8(s, paletteCount);\n\tbitmapDataOffset = 1 + (paletteCount * 3);\n\n\tif ((paletteCount > 127) || (paletteCount < 1))\n\t{\n\t\tWLog_ERR(TAG, \"paletteCount %\" PRIu8 \"\", paletteCount);\n\t\treturn FALSE;\n\t}\n\n\tif (Stream_GetRemainingLength(s) < 3ULL * paletteCount)\n\t\treturn FALSE;\n\n\tfor (i = 0; i < paletteCount; i++)\n\t{\n\t\tBYTE r, g, b;\n\t\tStream_Read_UINT8(s, b);\n\t\tStream_Read_UINT8(s, g);\n\t\tStream_Read_UINT8(s, r);\n\t\tpalette[i] = FreeRDPGetColor(DstFormat, r, g, b, 0xFF);\n\t}\n\n\tpixelIndex = 0;\n\tpixelCount = width * height;\n\tnumBits = CLEAR_LOG2_FLOOR[paletteCount - 1] + 1;\n\n\twhile (bitmapDataOffset < bitmapDataByteCount)\n\t{\n\t\tUINT32 tmp;\n\t\tUINT32 color;\n\t\tUINT32 runLengthFactor;\n\n\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [2 expected]\", Stream_GetRemainingLength(s));\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tStream_Read_UINT8(s, tmp);\n\t\tStream_Read_UINT8(s, runLengthFactor);\n\t\tbitmapDataOffset += 2;\n\t\tsuiteDepth = (tmp >> numBits) & CLEAR_8BIT_MASKS[(8 - numBits)];\n\t\tstopIndex = tmp & CLEAR_8BIT_MASKS[numBits];\n\t\tstartIndex = stopIndex - suiteDepth;\n\n\t\tif (runLengthFactor >= 0xFF)\n\t\t{\n\t\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [2 expected]\", Stream_GetRemainingLength(s));\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\tStream_Read_UINT16(s, runLengthFactor);\n\t\t\tbitmapDataOffset += 2;\n\n\t\t\tif (runLengthFactor >= 0xFFFF)\n\t\t\t{\n\t\t\t\tif (Stream_GetRemainingLength(s) < 4)\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [4 expected]\",\n\t\t\t\t\t Stream_GetRemainingLength(s));\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tStream_Read_UINT32(s, runLengthFactor);\n\t\t\t\tbitmapDataOffset += 4;\n\t\t\t}\n\t\t}\n\n\t\tif (startIndex >= paletteCount)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"startIndex %\" PRIu8 \" > paletteCount %\" PRIu8 \"]\", startIndex,\n\t\t\t paletteCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tif (stopIndex >= paletteCount)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"stopIndex %\" PRIu8 \" > paletteCount %\" PRIu8 \"]\", stopIndex,\n\t\t\t paletteCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tsuiteIndex = startIndex;\n\n\t\tif (suiteIndex > 127)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"suiteIndex %\" PRIu8 \" > 127]\", suiteIndex);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tcolor = palette[suiteIndex];\n\n\t\tif ((pixelIndex + runLengthFactor) > pixelCount)\n\t\t{\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"pixelIndex %\" PRIu32 \" + runLengthFactor %\" PRIu32 \" > pixelCount %\" PRIu32\n\t\t\t \"\",\n\t\t\t pixelIndex, runLengthFactor, pixelCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tfor (i = 0; i < runLengthFactor; i++)\n\t\t{\n\t\t\tBYTE* pTmpData =\n\t\t\t &pDstData[(nXDstRel + x) * GetBytesPerPixel(DstFormat) + (nYDstRel + y) * nDstStep];\n\n\t\t\tif ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight))\n\t\t\t\tWriteColor(pTmpData, DstFormat, color);\n\n\t\t\tif (++x >= width)\n\t\t\t{\n\t\t\t\ty++;\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t}\n\n\t\tpixelIndex += runLengthFactor;\n\n\t\tif ((pixelIndex + (suiteDepth + 1)) > pixelCount)\n\t\t{\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"pixelIndex %\" PRIu32 \" + suiteDepth %\" PRIu8 \" + 1 > pixelCount %\" PRIu32 \"\",\n\t\t\t pixelIndex, suiteDepth, pixelCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tfor (i = 0; i <= suiteDepth; i++)\n\t\t{\n\t\t\tBYTE* pTmpData =\n\t\t\t &pDstData[(nXDstRel + x) * GetBytesPerPixel(DstFormat) + (nYDstRel + y) * nDstStep];\n\t\t\tUINT32 color = palette[suiteIndex];\n\n\t\t\tif (suiteIndex > 127)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"suiteIndex %\" PRIu8 \" > 127\", suiteIndex);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\tsuiteIndex++;\n\n\t\t\tif ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight))\n\t\t\t\tWriteColor(pTmpData, DstFormat, color);\n\n\t\t\tif (++x >= width)\n\t\t\t{\n\t\t\t\ty++;\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t}\n\n\t\tpixelIndex += (suiteDepth + 1);\n\t}\n\n\tif (pixelIndex != pixelCount)\n\t{\n\t\tWLog_ERR(TAG, \"pixelIndex %\" PRIdz \" != pixelCount %\" PRIu32 \"\", pixelIndex, pixelCount);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 241001505274535680660475700376958696237, "size": 189, "commit_id": "363d7046dfec4003b91aecf7867e3b05905f3843", "message": "Fixed oob read in clear_decompress_subcode_rlex\n\nFixed length checks before stream read.\nThanks to hac425 CVE-2020-11040", "target": 0, "dataset": "other", "idx": 448692}
  879. {"func": "ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8* ptr;\n int framesize;\n int c, chunks, advance;\n int l, lines;\n int i, j, x = 0, y, ymax;\n\n /* If not even the chunk size is present, we'd better leave */\n\n if (bytes < 4)\n\treturn 0;\n\n /* We don't decode anything unless we have a full chunk in the\n input buffer (on the other hand, the Python part of the driver\n makes sure this is always the case) */\n\n ptr = buf;\n\n framesize = I32(ptr);\n if (framesize < I32(ptr))\n\treturn 0;\n\n /* Make sure this is a frame chunk. The Python driver takes\n case of other chunk types. */\n\n if (I16(ptr+4) != 0xF1FA) {\n\tstate->errcode = IMAGING_CODEC_UNKNOWN;\n\treturn -1;\n }\n\n chunks = I16(ptr+6);\n ptr += 16;\n bytes -= 16;\n\n /* Process subchunks */\n for (c = 0; c < chunks; c++) {\n\tUINT8* data;\n\tif (bytes < 10) {\n\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t return -1;\n\t}\n\tdata = ptr + 6;\n\tswitch (I16(ptr+4)) {\n\tcase 4: case 11:\n\t /* FLI COLOR chunk */\n\t break; /* ignored; handled by Python code */\n\tcase 7:\n\t /* FLI SS2 chunk (word delta) */\n\t lines = I16(data); data += 2;\n\t for (l = y = 0; l < lines && y < state->ysize; l++, y++) {\n\t\tUINT8* buf = (UINT8*) im->image[y];\n\t\tint p, packets;\n\t\tpackets = I16(data); data += 2;\n\t\twhile (packets & 0x8000) {\n\t\t /* flag word */\n\t\t if (packets & 0x4000) {\n\t\t\ty += 65536 - packets; /* skip lines */\n\t\t\tif (y >= state->ysize) {\n\t\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t\t return -1;\n\t\t\t}\n\t\t\tbuf = (UINT8*) im->image[y];\n\t\t } else {\n\t\t\t/* store last byte (used if line width is odd) */\n\t\t\tbuf[state->xsize-1] = (UINT8) packets;\n\t\t }\n\t\t packets = I16(data); data += 2;\n\t\t}\n\t\tfor (p = x = 0; p < packets; p++) {\n\t\t x += data[0]; /* pixel skip */\n\t\t if (data[1] >= 128) {\n\t\t\ti = 256-data[1]; /* run */\n\t\t\tif (x + i + i > state->xsize)\n\t\t\t break;\n\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t buf[x++] = data[2];\n\t\t\t buf[x++] = data[3];\n\t\t\t}\n\t\t\tdata += 2 + 2;\n\t\t } else {\n\t\t\ti = 2 * (int) data[1]; /* chunk */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemcpy(buf + x, data + 2, i);\n\t\t\tdata += 2 + i;\n\t\t\tx += i;\n\t\t }\n\t\t}\n\t\tif (p < packets)\n\t\t break; /* didn't process all packets */\n\t }\n\t if (l < lines) {\n\t\t/* didn't process all lines */\n\t\tstate->errcode = IMAGING_CODEC_OVERRUN;\n\t\treturn -1;\n\t }\n\t break;\n\tcase 12:\n\t /* FLI LC chunk (byte delta) */\n\t y = I16(data); ymax = y + I16(data+2); data += 4;\n\t for (; y < ymax && y < state->ysize; y++) {\n\t\tUINT8* out = (UINT8*) im->image[y];\n\t\tint p, packets = *data++;\n\t\tfor (p = x = 0; p < packets; p++, x += i) {\n\t\t x += data[0]; /* skip pixels */\n\t\t if (data[1] & 0x80) {\n\t\t\ti = 256-data[1]; /* run */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemset(out + x, data[2], i);\n\t\t\tdata += 3;\n\t\t } else {\n\t\t\ti = data[1]; /* chunk */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemcpy(out + x, data + 2, i);\n\t\t\tdata += i + 2;\n\t\t }\n\t\t}\n\t\tif (p < packets)\n\t\t break; /* didn't process all packets */\n\t }\n\t if (y < ymax) {\n\t\t/* didn't process all lines */\n\t\tstate->errcode = IMAGING_CODEC_OVERRUN;\n\t\treturn -1;\n\t }\n\t break;\n\tcase 13:\n\t /* FLI BLACK chunk */\n\t for (y = 0; y < state->ysize; y++)\n\t\tmemset(im->image[y], 0, state->xsize);\n\t break;\n\tcase 15:\n\t /* FLI BRUN chunk */\n\t for (y = 0; y < state->ysize; y++) {\n\t\tUINT8* out = (UINT8*) im->image[y];\n\t\tdata += 1; /* ignore packetcount byte */\n\t\tfor (x = 0; x < state->xsize; x += i) {\n\t\t if (data[0] & 0x80) {\n\t\t\ti = 256 - data[0];\n\t\t\tif (x + i > state->xsize)\n\t\t\t break; /* safety first */\n\t\t\tmemcpy(out + x, data + 1, i);\n\t\t\tdata += i + 1;\n\t\t } else {\n\t\t\ti = data[0];\n\t\t\tif (x + i > state->xsize)\n\t\t\t break; /* safety first */\n\t\t\tmemset(out + x, data[1], i);\n\t\t\tdata += 2;\n\t\t }\n\t\t}\n\t\tif (x != state->xsize) {\n\t\t /* didn't unpack whole line */\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t return -1;\n\t\t}\n\t }\n\t break;\n\tcase 16:\n\t /* COPY chunk */\n\t for (y = 0; y < state->ysize; y++) {\n\t\tUINT8* buf = (UINT8*) im->image[y];\n\t\tmemcpy(buf, data, state->xsize);\n\t\tdata += state->xsize;\n\t }\n\t break;\n\tcase 18:\n\t /* PSTAMP chunk */\n\t break; /* ignored */\n\tdefault:\n\t /* unknown chunk */\n\t /* printf(\"unknown FLI/FLC chunk: %d\\n\", I16(ptr+4)); */\n\t state->errcode = IMAGING_CODEC_UNKNOWN;\n\t return -1;\n\t}\n\tadvance = I32(ptr);\n\tptr += advance;\n\tbytes -= advance;\n }\n\n return -1; /* end of frame */\n}", "project": "Pillow", "hash": 134252300941587921790955744187697074809, "size": 185, "commit_id": "a09acd0decd8a87ccce939d5ff65dab59e7d365b", "message": "Catch FLI buffer overrun", "target": 1, "dataset": "other", "idx": 211493}
  880. {"func": "ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8* ptr;\n int framesize;\n int c, chunks, advance;\n int l, lines;\n int i, j, x = 0, y, ymax;\n\n /* If not even the chunk size is present, we'd better leave */\n\n if (bytes < 4)\n\treturn 0;\n\n /* We don't decode anything unless we have a full chunk in the\n input buffer */\n\n ptr = buf;\n\n framesize = I32(ptr);\n if (framesize < I32(ptr))\n\treturn 0;\n\n /* Make sure this is a frame chunk. The Python driver takes\n case of other chunk types. */\n\n if (bytes < 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n if (I16(ptr+4) != 0xF1FA) {\n\tstate->errcode = IMAGING_CODEC_UNKNOWN;\n\treturn -1;\n }\n\n chunks = I16(ptr+6);\n ptr += 16;\n bytes -= 16;\n\n /* Process subchunks */\n for (c = 0; c < chunks; c++) {\n\tUINT8* data;\n\tif (bytes < 10) {\n\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t return -1;\n\t}\n\tdata = ptr + 6;\n\tswitch (I16(ptr+4)) {\n\tcase 4: case 11:\n\t /* FLI COLOR chunk */\n\t break; /* ignored; handled by Python code */\n\tcase 7:\n\t /* FLI SS2 chunk (word delta) */\n\t lines = I16(data); data += 2;\n\t for (l = y = 0; l < lines && y < state->ysize; l++, y++) {\n\t\tUINT8* buf = (UINT8*) im->image[y];\n\t\tint p, packets;\n\t\tpackets = I16(data); data += 2;\n\t\twhile (packets & 0x8000) {\n\t\t /* flag word */\n\t\t if (packets & 0x4000) {\n\t\t\ty += 65536 - packets; /* skip lines */\n\t\t\tif (y >= state->ysize) {\n\t\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t\t return -1;\n\t\t\t}\n\t\t\tbuf = (UINT8*) im->image[y];\n\t\t } else {\n\t\t\t/* store last byte (used if line width is odd) */\n\t\t\tbuf[state->xsize-1] = (UINT8) packets;\n\t\t }\n\t\t packets = I16(data); data += 2;\n\t\t}\n\t\tfor (p = x = 0; p < packets; p++) {\n\t\t x += data[0]; /* pixel skip */\n\t\t if (data[1] >= 128) {\n\t\t\ti = 256-data[1]; /* run */\n\t\t\tif (x + i + i > state->xsize)\n\t\t\t break;\n\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t buf[x++] = data[2];\n\t\t\t buf[x++] = data[3];\n\t\t\t}\n\t\t\tdata += 2 + 2;\n\t\t } else {\n\t\t\ti = 2 * (int) data[1]; /* chunk */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemcpy(buf + x, data + 2, i);\n\t\t\tdata += 2 + i;\n\t\t\tx += i;\n\t\t }\n\t\t}\n\t\tif (p < packets)\n\t\t break; /* didn't process all packets */\n\t }\n\t if (l < lines) {\n\t\t/* didn't process all lines */\n\t\tstate->errcode = IMAGING_CODEC_OVERRUN;\n\t\treturn -1;\n\t }\n\t break;\n\tcase 12:\n\t /* FLI LC chunk (byte delta) */\n\t y = I16(data); ymax = y + I16(data+2); data += 4;\n\t for (; y < ymax && y < state->ysize; y++) {\n\t\tUINT8* out = (UINT8*) im->image[y];\n\t\tint p, packets = *data++;\n\t\tfor (p = x = 0; p < packets; p++, x += i) {\n\t\t x += data[0]; /* skip pixels */\n\t\t if (data[1] & 0x80) {\n\t\t\ti = 256-data[1]; /* run */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemset(out + x, data[2], i);\n\t\t\tdata += 3;\n\t\t } else {\n\t\t\ti = data[1]; /* chunk */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemcpy(out + x, data + 2, i);\n\t\t\tdata += i + 2;\n\t\t }\n\t\t}\n\t\tif (p < packets)\n\t\t break; /* didn't process all packets */\n\t }\n\t if (y < ymax) {\n\t\t/* didn't process all lines */\n\t\tstate->errcode = IMAGING_CODEC_OVERRUN;\n\t\treturn -1;\n\t }\n\t break;\n\tcase 13:\n\t /* FLI BLACK chunk */\n\t for (y = 0; y < state->ysize; y++)\n\t\tmemset(im->image[y], 0, state->xsize);\n\t break;\n\tcase 15:\n\t /* FLI BRUN chunk */\n\t for (y = 0; y < state->ysize; y++) {\n\t\tUINT8* out = (UINT8*) im->image[y];\n\t\tdata += 1; /* ignore packetcount byte */\n\t\tfor (x = 0; x < state->xsize; x += i) {\n\t\t if (data[0] & 0x80) {\n\t\t\ti = 256 - data[0];\n\t\t\tif (x + i > state->xsize)\n\t\t\t break; /* safety first */\n\t\t\tmemcpy(out + x, data + 1, i);\n\t\t\tdata += i + 1;\n\t\t } else {\n\t\t\ti = data[0];\n\t\t\tif (x + i > state->xsize)\n\t\t\t break; /* safety first */\n\t\t\tmemset(out + x, data[1], i);\n\t\t\tdata += 2;\n\t\t }\n\t\t}\n\t\tif (x != state->xsize) {\n\t\t /* didn't unpack whole line */\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t return -1;\n\t\t}\n\t }\n\t break;\n\tcase 16:\n\t /* COPY chunk */\n\t for (y = 0; y < state->ysize; y++) {\n\t\tUINT8* buf = (UINT8*) im->image[y];\n\t\tmemcpy(buf, data, state->xsize);\n\t\tdata += state->xsize;\n\t }\n\t break;\n\tcase 18:\n\t /* PSTAMP chunk */\n\t break; /* ignored */\n\tdefault:\n\t /* unknown chunk */\n\t /* printf(\"unknown FLI/FLC chunk: %d\\n\", I16(ptr+4)); */\n\t state->errcode = IMAGING_CODEC_UNKNOWN;\n\t return -1;\n\t}\n\tadvance = I32(ptr);\n\tptr += advance;\n\tbytes -= advance;\n }\n\n return -1; /* end of frame */\n}", "project": "Pillow", "hash": 303061285771598319385557632079841780973, "size": 188, "commit_id": "a09acd0decd8a87ccce939d5ff65dab59e7d365b", "message": "Catch FLI buffer overrun", "target": 0, "dataset": "other", "idx": 448723}
  881. {"func": "bool RGWSwiftWebsiteHandler::is_web_dir() const\n{\n std::string subdir_name = url_decode(s->object.name);\n\n /* Remove character from the subdir name if it is \"/\". */\n if (subdir_name.empty()) {\n return false;\n } else if (subdir_name.back() == '/') {\n subdir_name.pop_back();\n }\n\n rgw_obj obj(s->bucket, std::move(subdir_name));\n\n /* First, get attrset of the object we'll try to retrieve. */\n RGWObjectCtx& obj_ctx = *static_cast<RGWObjectCtx *>(s->obj_ctx);\n obj_ctx.set_atomic(obj);\n obj_ctx.set_prefetch_data(obj);\n\n RGWObjState* state = nullptr;\n if (store->get_obj_state(&obj_ctx, s->bucket_info, obj, &state, false) < 0) {\n return false;\n }\n\n /* A nonexistent object cannot be a considered as a marker representing\n * the emulation of catalog in FS hierarchy. */\n if (! state->exists) {\n return false;\n }\n\n /* Decode the content type. */\n std::string content_type;\n get_contype_from_attrs(state->attrset, content_type);\n\n const auto& ws_conf = s->bucket_info.website_conf;\n const std::string subdir_marker = ws_conf.subdir_marker.empty()\n ? \"application/directory\"\n : ws_conf.subdir_marker;\n return subdir_marker == content_type && state->size <= 1;\n}", "project": "ceph", "hash": 48255843606487150326028348212204674985, "size": 39, "commit_id": "f44a8ae8aa27ecef69528db9aec220f12492810e", "message": "rgw: RGWSwiftWebsiteHandler::is_web_dir checks empty subdir_name\n\nchecking for empty name avoids later assertion in RGWObjectCtx::set_atomic\n\nFixes: CVE-2021-3531\n\nReviewed-by: Casey Bodley <cbodley@redhat.com>\nSigned-off-by: Casey Bodley <cbodley@redhat.com>\n(cherry picked from commit 7196a469b4470f3c8628489df9a41ec8b00a5610)", "target": 1, "dataset": "other", "idx": 211502}
  882. {"func": "bool RGWSwiftWebsiteHandler::is_web_dir() const\n{\n std::string subdir_name = url_decode(s->object.name);\n\n /* Remove character from the subdir name if it is \"/\". */\n if (subdir_name.empty()) {\n return false;\n } else if (subdir_name.back() == '/') {\n subdir_name.pop_back();\n if (subdir_name.empty()) {\n return false;\n }\n }\n\n rgw_obj obj(s->bucket, std::move(subdir_name));\n\n /* First, get attrset of the object we'll try to retrieve. */\n RGWObjectCtx& obj_ctx = *static_cast<RGWObjectCtx *>(s->obj_ctx);\n obj_ctx.set_atomic(obj);\n obj_ctx.set_prefetch_data(obj);\n\n RGWObjState* state = nullptr;\n if (store->get_obj_state(&obj_ctx, s->bucket_info, obj, &state, false) < 0) {\n return false;\n }\n\n /* A nonexistent object cannot be a considered as a marker representing\n * the emulation of catalog in FS hierarchy. */\n if (! state->exists) {\n return false;\n }\n\n /* Decode the content type. */\n std::string content_type;\n get_contype_from_attrs(state->attrset, content_type);\n\n const auto& ws_conf = s->bucket_info.website_conf;\n const std::string subdir_marker = ws_conf.subdir_marker.empty()\n ? \"application/directory\"\n : ws_conf.subdir_marker;\n return subdir_marker == content_type && state->size <= 1;\n}", "project": "ceph", "hash": 298807666171918733354542069578347162633, "size": 42, "commit_id": "f44a8ae8aa27ecef69528db9aec220f12492810e", "message": "rgw: RGWSwiftWebsiteHandler::is_web_dir checks empty subdir_name\n\nchecking for empty name avoids later assertion in RGWObjectCtx::set_atomic\n\nFixes: CVE-2021-3531\n\nReviewed-by: Casey Bodley <cbodley@redhat.com>\nSigned-off-by: Casey Bodley <cbodley@redhat.com>\n(cherry picked from commit 7196a469b4470f3c8628489df9a41ec8b00a5610)", "target": 0, "dataset": "other", "idx": 448852}
  883. {"func": "PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2(\n pj_pool_t *pool,\n\t\t\t\t pjmedia_sdp_neg *neg,\n unsigned flags,\n\t\t\t\t const pjmedia_sdp_session *local)\n{\n pjmedia_sdp_session *new_offer;\n pjmedia_sdp_session *old_offer;\n char media_used[PJMEDIA_MAX_SDP_MEDIA];\n unsigned oi; /* old offer media index */\n pj_status_t status;\n\n /* Check arguments are valid. */\n PJ_ASSERT_RETURN(pool && neg && local, PJ_EINVAL);\n\n /* Can only do this in STATE_DONE. */\n PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE, \n\t\t PJMEDIA_SDPNEG_EINSTATE);\n\n /* Validate the new offer */\n status = pjmedia_sdp_validate(local);\n if (status != PJ_SUCCESS)\n\treturn status;\n\n /* Change state to STATE_LOCAL_OFFER */\n neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER;\n\n /* Init vars */\n pj_bzero(media_used, sizeof(media_used));\n old_offer = neg->active_local_sdp;\n new_offer = pjmedia_sdp_session_clone(pool, local);\n\n /* RFC 3264 Section 8: When issuing an offer that modifies the session,\n * the \"o=\" line of the new SDP MUST be identical to that in the\n * previous SDP, except that the version in the origin field MUST\n * increment by one from the previous SDP.\n */\n pj_strdup(pool, &new_offer->origin.user, &old_offer->origin.user);\n new_offer->origin.id = old_offer->origin.id;\n\n pj_strdup(pool, &new_offer->origin.net_type, &old_offer->origin.net_type);\n pj_strdup(pool, &new_offer->origin.addr_type,&old_offer->origin.addr_type);\n pj_strdup(pool, &new_offer->origin.addr, &old_offer->origin.addr);\n\n if ((flags & PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE) == 0) {\n /* Generating the new offer, in the case media lines doesn't match the\n * active SDP (e.g. current/active SDP's have m=audio and m=video lines,\n * and the new offer only has m=audio line), the negotiator will fix \n * the new offer by reordering and adding the missing media line with \n * port number set to zero.\n */\n for (oi = 0; oi < old_offer->media_count; ++oi) {\n\t pjmedia_sdp_media *om;\n\t pjmedia_sdp_media *nm;\n\t unsigned ni; /* new offer media index */\n\t pj_bool_t found = PJ_FALSE;\n\n\t om = old_offer->media[oi];\n\t for (ni = oi; ni < new_offer->media_count; ++ni) {\n\t nm = new_offer->media[ni];\n\t if (pj_strcmp(&nm->desc.media, &om->desc.media) == 0) {\n\t\t if (ni != oi) {\n\t\t /* The same media found but the position unmatched to\n * the old offer, so let's put this media in the right\n * place, and keep the order of the rest.\n\t\t */\n\t\t pj_array_insert(\n new_offer->media,\t\t /* array */\n\t\t\t sizeof(new_offer->media[0]), /* elmt size*/\n\t\t\t ni,\t\t\t\t /* count */\n\t\t oi,\t\t\t\t /* pos */\n\t\t\t &nm);\t\t\t /* new elmt */\n\t\t }\n\t\t found = PJ_TRUE;\n\t\t break;\n\t }\n\t }\n\t if (!found) {\n\t pjmedia_sdp_media *m;\n\n\t m = sdp_media_clone_deactivate(pool, om, om, local);\n\n\t pj_array_insert(new_offer->media, sizeof(new_offer->media[0]),\n\t\t\t new_offer->media_count++, oi, &m);\n\t }\n }\n } else {\n /* If media type change is allowed, the negotiator only needs to fix \n * the new offer by adding the missing media line(s) with port number\n * set to zero.\n */\n for (oi = new_offer->media_count; oi < old_offer->media_count; ++oi) {\n pjmedia_sdp_media *m;\n\n\t m = sdp_media_clone_deactivate(pool, old_offer->media[oi],\n old_offer->media[oi], local);\n\n\t pj_array_insert(new_offer->media, sizeof(new_offer->media[0]),\n\t new_offer->media_count++, oi, &m);\n\n }\n }\n\n /* New_offer fixed */\n#if PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION\n new_offer->origin.version = old_offer->origin.version;\n\n if (pjmedia_sdp_session_cmp(new_offer, neg->initial_sdp, 0) != PJ_SUCCESS)\n {\n\t++new_offer->origin.version;\n } \n#else\n new_offer->origin.version = old_offer->origin.version + 1;\n#endif\n \n neg->initial_sdp_tmp = neg->initial_sdp;\n neg->initial_sdp = new_offer;\n neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, new_offer);\n\n return PJ_SUCCESS;\n}", "project": "pjproject", "hash": 197312442692241206063456839234745127746, "size": 121, "commit_id": "97b3d7addbaa720b7ddb0af9bf6f3e443e664365", "message": "Merge pull request from GHSA-hvq6-f89p-frvp", "target": 1, "dataset": "other", "idx": 211591}
  884. {"func": "PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2(\n pj_pool_t *pool,\n\t\t\t\t pjmedia_sdp_neg *neg,\n unsigned flags,\n\t\t\t\t const pjmedia_sdp_session *local)\n{\n pjmedia_sdp_session *new_offer;\n pjmedia_sdp_session *old_offer;\n unsigned oi; /* old offer media index */\n pj_status_t status;\n\n /* Check arguments are valid. */\n PJ_ASSERT_RETURN(pool && neg && local, PJ_EINVAL);\n\n /* Can only do this in STATE_DONE. */\n PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE, \n\t\t PJMEDIA_SDPNEG_EINSTATE);\n\n /* Validate the new offer */\n status = pjmedia_sdp_validate(local);\n if (status != PJ_SUCCESS)\n\treturn status;\n\n /* Change state to STATE_LOCAL_OFFER */\n neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER;\n\n /* When there is no active local SDP in state PJMEDIA_SDP_NEG_STATE_DONE,\n * it means that the previous initial SDP nego must have been failed,\n * so we'll just set the local SDP offer here.\n */\n if (!neg->active_local_sdp) {\n\tneg->initial_sdp_tmp = NULL;\n\tneg->initial_sdp = pjmedia_sdp_session_clone(pool, local);\n\tneg->neg_local_sdp = pjmedia_sdp_session_clone(pool, local);\n\n\treturn PJ_SUCCESS;\n }\n\n /* Init vars */\n old_offer = neg->active_local_sdp;\n new_offer = pjmedia_sdp_session_clone(pool, local);\n\n /* RFC 3264 Section 8: When issuing an offer that modifies the session,\n * the \"o=\" line of the new SDP MUST be identical to that in the\n * previous SDP, except that the version in the origin field MUST\n * increment by one from the previous SDP.\n */\n pj_strdup(pool, &new_offer->origin.user, &old_offer->origin.user);\n new_offer->origin.id = old_offer->origin.id;\n\n pj_strdup(pool, &new_offer->origin.net_type, &old_offer->origin.net_type);\n pj_strdup(pool, &new_offer->origin.addr_type,&old_offer->origin.addr_type);\n pj_strdup(pool, &new_offer->origin.addr, &old_offer->origin.addr);\n\n if ((flags & PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE) == 0) {\n /* Generating the new offer, in the case media lines doesn't match the\n * active SDP (e.g. current/active SDP's have m=audio and m=video lines,\n * and the new offer only has m=audio line), the negotiator will fix \n * the new offer by reordering and adding the missing media line with \n * port number set to zero.\n */\n for (oi = 0; oi < old_offer->media_count; ++oi) {\n\t pjmedia_sdp_media *om;\n\t pjmedia_sdp_media *nm;\n\t unsigned ni; /* new offer media index */\n\t pj_bool_t found = PJ_FALSE;\n\n\t om = old_offer->media[oi];\n\t for (ni = oi; ni < new_offer->media_count; ++ni) {\n\t nm = new_offer->media[ni];\n\t if (pj_strcmp(&nm->desc.media, &om->desc.media) == 0) {\n\t\t if (ni != oi) {\n\t\t /* The same media found but the position unmatched to\n * the old offer, so let's put this media in the right\n * place, and keep the order of the rest.\n\t\t */\n\t\t pj_array_insert(\n new_offer->media,\t\t /* array */\n\t\t\t sizeof(new_offer->media[0]), /* elmt size*/\n\t\t\t ni,\t\t\t\t /* count */\n\t\t oi,\t\t\t\t /* pos */\n\t\t\t &nm);\t\t\t /* new elmt */\n\t\t }\n\t\t found = PJ_TRUE;\n\t\t break;\n\t }\n\t }\n\t if (!found) {\n\t pjmedia_sdp_media *m;\n\n\t m = sdp_media_clone_deactivate(pool, om, om, local);\n\n\t pj_array_insert(new_offer->media, sizeof(new_offer->media[0]),\n\t\t\t new_offer->media_count++, oi, &m);\n\t }\n }\n } else {\n /* If media type change is allowed, the negotiator only needs to fix \n * the new offer by adding the missing media line(s) with port number\n * set to zero.\n */\n for (oi = new_offer->media_count; oi < old_offer->media_count; ++oi) {\n pjmedia_sdp_media *m;\n\n\t m = sdp_media_clone_deactivate(pool, old_offer->media[oi],\n old_offer->media[oi], local);\n\n\t pj_array_insert(new_offer->media, sizeof(new_offer->media[0]),\n\t new_offer->media_count++, oi, &m);\n\n }\n }\n\n /* New_offer fixed */\n#if PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION\n new_offer->origin.version = old_offer->origin.version;\n\n if (pjmedia_sdp_session_cmp(new_offer, neg->initial_sdp, 0) != PJ_SUCCESS)\n {\n\t++new_offer->origin.version;\n } \n#else\n new_offer->origin.version = old_offer->origin.version + 1;\n#endif\n \n neg->initial_sdp_tmp = neg->initial_sdp;\n neg->initial_sdp = new_offer;\n neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, new_offer);\n\n return PJ_SUCCESS;\n}", "project": "pjproject", "hash": 195009002714543189743300644043816489769, "size": 131, "commit_id": "97b3d7addbaa720b7ddb0af9bf6f3e443e664365", "message": "Merge pull request from GHSA-hvq6-f89p-frvp", "target": 0, "dataset": "other", "idx": 449653}
  885. {"func": "static int __init lp_setup (char *str)\n{\n\tstatic int parport_ptr;\n\tint x;\n\n\tif (get_option(&str, &x)) {\n\t\tif (x == 0) {\n\t\t\t/* disable driver on \"lp=\" or \"lp=0\" */\n\t\t\tparport_nr[0] = LP_PARPORT_OFF;\n\t\t} else {\n\t\t\tprintk(KERN_WARNING \"warning: 'lp=0x%x' is deprecated, ignored\\n\", x);\n\t\t\treturn 0;\n\t\t}\n\t} else if (!strncmp(str, \"parport\", 7)) {\n\t\tint n = simple_strtoul(str+7, NULL, 10);\n\t\tif (parport_ptr < LP_NO)\n\t\t\tparport_nr[parport_ptr++] = n;\n\t\telse\n\t\t\tprintk(KERN_INFO \"lp: too many ports, %s ignored.\\n\",\n\t\t\t str);\n\t} else if (!strcmp(str, \"auto\")) {\n\t\tparport_nr[0] = LP_PARPORT_AUTO;\n\t} else if (!strcmp(str, \"none\")) {\n\t\tparport_nr[parport_ptr++] = LP_PARPORT_NONE;\n\t} else if (!strcmp(str, \"reset\")) {\n\t\treset = 1;\n\t}\n\treturn 1;\n}", "project": "linux", "hash": 245258957937587766339739480970569790552, "size": 29, "commit_id": "3e21f4af170bebf47c187c1ff8bf155583c9f3b1", "message": "char: lp: fix possible integer overflow in lp_setup()\n\nThe lp_setup() code doesn't apply any bounds checking when passing\n\"lp=none\", and only in this case, resulting in an overflow of the\nparport_nr[] array. All versions in Git history are affected.\n\nReported-By: Roee Hay <roee.hay@hcl.com>\nCc: Ben Hutchings <ben@decadent.org.uk>\nCc: stable@vger.kernel.org\nSigned-off-by: Willy Tarreau <w@1wt.eu>\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 1, "dataset": "other", "idx": 211709}
  886. {"func": "static int __init lp_setup (char *str)\n{\n\tstatic int parport_ptr;\n\tint x;\n\n\tif (get_option(&str, &x)) {\n\t\tif (x == 0) {\n\t\t\t/* disable driver on \"lp=\" or \"lp=0\" */\n\t\t\tparport_nr[0] = LP_PARPORT_OFF;\n\t\t} else {\n\t\t\tprintk(KERN_WARNING \"warning: 'lp=0x%x' is deprecated, ignored\\n\", x);\n\t\t\treturn 0;\n\t\t}\n\t} else if (!strncmp(str, \"parport\", 7)) {\n\t\tint n = simple_strtoul(str+7, NULL, 10);\n\t\tif (parport_ptr < LP_NO)\n\t\t\tparport_nr[parport_ptr++] = n;\n\t\telse\n\t\t\tprintk(KERN_INFO \"lp: too many ports, %s ignored.\\n\",\n\t\t\t str);\n\t} else if (!strcmp(str, \"auto\")) {\n\t\tparport_nr[0] = LP_PARPORT_AUTO;\n\t} else if (!strcmp(str, \"none\")) {\n\t\tif (parport_ptr < LP_NO)\n\t\t\tparport_nr[parport_ptr++] = LP_PARPORT_NONE;\n\t\telse\n\t\t\tprintk(KERN_INFO \"lp: too many ports, %s ignored.\\n\",\n\t\t\t str);\n\t} else if (!strcmp(str, \"reset\")) {\n\t\treset = 1;\n\t}\n\treturn 1;\n}", "project": "linux", "hash": 46004058772895788984844550774932256768, "size": 33, "commit_id": "3e21f4af170bebf47c187c1ff8bf155583c9f3b1", "message": "char: lp: fix possible integer overflow in lp_setup()\n\nThe lp_setup() code doesn't apply any bounds checking when passing\n\"lp=none\", and only in this case, resulting in an overflow of the\nparport_nr[] array. All versions in Git history are affected.\n\nReported-By: Roee Hay <roee.hay@hcl.com>\nCc: Ben Hutchings <ben@decadent.org.uk>\nCc: stable@vger.kernel.org\nSigned-off-by: Willy Tarreau <w@1wt.eu>\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 0, "dataset": "other", "idx": 450878}
  887. {"func": "static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,\n\t\t\tstruct buffer_head **bh,struct dx_frame *frame,\n\t\t\tstruct dx_hash_info *hinfo)\n{\n\tunsigned blocksize = dir->i_sb->s_blocksize;\n\tunsigned count, continued;\n\tstruct buffer_head *bh2;\n\text4_lblk_t newblock;\n\tu32 hash2;\n\tstruct dx_map_entry *map;\n\tchar *data1 = (*bh)->b_data, *data2;\n\tunsigned split, move, size;\n\tstruct ext4_dir_entry_2 *de = NULL, *de2;\n\tint\tcsum_size = 0;\n\tint\terr = 0, i;\n\n\tif (ext4_has_metadata_csum(dir->i_sb))\n\t\tcsum_size = sizeof(struct ext4_dir_entry_tail);\n\n\tbh2 = ext4_append(handle, dir, &newblock);\n\tif (IS_ERR(bh2)) {\n\t\tbrelse(*bh);\n\t\t*bh = NULL;\n\t\treturn (struct ext4_dir_entry_2 *) bh2;\n\t}\n\n\tBUFFER_TRACE(*bh, \"get_write_access\");\n\terr = ext4_journal_get_write_access(handle, *bh);\n\tif (err)\n\t\tgoto journal_error;\n\n\tBUFFER_TRACE(frame->bh, \"get_write_access\");\n\terr = ext4_journal_get_write_access(handle, frame->bh);\n\tif (err)\n\t\tgoto journal_error;\n\n\tdata2 = bh2->b_data;\n\n\t/* create map in the end of data2 block */\n\tmap = (struct dx_map_entry *) (data2 + blocksize);\n\tcount = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,\n\t\t\t blocksize, hinfo, map);\n\tmap -= count;\n\tdx_sort_map(map, count);\n\t/* Split the existing block in the middle, size-wise */\n\tsize = 0;\n\tmove = 0;\n\tfor (i = count-1; i >= 0; i--) {\n\t\t/* is more than half of this entry in 2nd half of the block? */\n\t\tif (size + map[i].size/2 > blocksize/2)\n\t\t\tbreak;\n\t\tsize += map[i].size;\n\t\tmove++;\n\t}\n\t/* map index at which we will split */\n\tsplit = count - move;\n\thash2 = map[split].hash;\n\tcontinued = hash2 == map[split - 1].hash;\n\tdxtrace(printk(KERN_INFO \"Split block %lu at %x, %i/%i\\n\",\n\t\t\t(unsigned long)dx_get_block(frame->at),\n\t\t\t\t\thash2, split, count-split));\n\n\t/* Fancy dance to stay within two buffers */\n\tde2 = dx_move_dirents(data1, data2, map + split, count - split,\n\t\t\t blocksize);\n\tde = dx_pack_dirents(data1, blocksize);\n\tde->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -\n\t\t\t\t\t (char *) de,\n\t\t\t\t\t blocksize);\n\tde2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -\n\t\t\t\t\t (char *) de2,\n\t\t\t\t\t blocksize);\n\tif (csum_size) {\n\t\text4_initialize_dirent_tail(*bh, blocksize);\n\t\text4_initialize_dirent_tail(bh2, blocksize);\n\t}\n\n\tdxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,\n\t\t\tblocksize, 1));\n\tdxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,\n\t\t\tblocksize, 1));\n\n\t/* Which block gets the new entry? */\n\tif (hinfo->hash >= hash2) {\n\t\tswap(*bh, bh2);\n\t\tde = de2;\n\t}\n\tdx_insert_block(frame, hash2 + continued, newblock);\n\terr = ext4_handle_dirty_dirblock(handle, dir, bh2);\n\tif (err)\n\t\tgoto journal_error;\n\terr = ext4_handle_dirty_dx_node(handle, dir, frame->bh);\n\tif (err)\n\t\tgoto journal_error;\n\tbrelse(bh2);\n\tdxtrace(dx_show_index(\"frame\", frame->entries));\n\treturn de;\n\njournal_error:\n\tbrelse(*bh);\n\tbrelse(bh2);\n\t*bh = NULL;\n\text4_std_error(dir->i_sb, err);\n\treturn ERR_PTR(err);\n}", "project": "linux", "hash": 303167763486678289730668385446929678121, "size": 105, "commit_id": "5872331b3d91820e14716632ebb56b1399b34fe1", "message": "ext4: fix potential negative array index in do_split()\n\nIf for any reason a directory passed to do_split() does not have enough\nactive entries to exceed half the size of the block, we can end up\niterating over all \"count\" entries without finding a split point.\n\nIn this case, count == move, and split will be zero, and we will\nattempt a negative index into map[].\n\nGuard against this by detecting this case, and falling back to\nsplit-to-half-of-count instead; in this case we will still have\nplenty of space (> half blocksize) in each split block.\n\nFixes: ef2b02d3e617 (\"ext34: ensure do_split leaves enough free space in both blocks\")\nSigned-off-by: Eric Sandeen <sandeen@redhat.com>\nReviewed-by: Andreas Dilger <adilger@dilger.ca>\nReviewed-by: Jan Kara <jack@suse.cz>\nLink: https://lore.kernel.org/r/f53e246b-647c-64bb-16ec-135383c70ad7@redhat.com\nSigned-off-by: Theodore Ts'o <tytso@mit.edu>", "target": 1, "dataset": "other", "idx": 211725}
  888. {"func": "static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,\n\t\t\tstruct buffer_head **bh,struct dx_frame *frame,\n\t\t\tstruct dx_hash_info *hinfo)\n{\n\tunsigned blocksize = dir->i_sb->s_blocksize;\n\tunsigned count, continued;\n\tstruct buffer_head *bh2;\n\text4_lblk_t newblock;\n\tu32 hash2;\n\tstruct dx_map_entry *map;\n\tchar *data1 = (*bh)->b_data, *data2;\n\tunsigned split, move, size;\n\tstruct ext4_dir_entry_2 *de = NULL, *de2;\n\tint\tcsum_size = 0;\n\tint\terr = 0, i;\n\n\tif (ext4_has_metadata_csum(dir->i_sb))\n\t\tcsum_size = sizeof(struct ext4_dir_entry_tail);\n\n\tbh2 = ext4_append(handle, dir, &newblock);\n\tif (IS_ERR(bh2)) {\n\t\tbrelse(*bh);\n\t\t*bh = NULL;\n\t\treturn (struct ext4_dir_entry_2 *) bh2;\n\t}\n\n\tBUFFER_TRACE(*bh, \"get_write_access\");\n\terr = ext4_journal_get_write_access(handle, *bh);\n\tif (err)\n\t\tgoto journal_error;\n\n\tBUFFER_TRACE(frame->bh, \"get_write_access\");\n\terr = ext4_journal_get_write_access(handle, frame->bh);\n\tif (err)\n\t\tgoto journal_error;\n\n\tdata2 = bh2->b_data;\n\n\t/* create map in the end of data2 block */\n\tmap = (struct dx_map_entry *) (data2 + blocksize);\n\tcount = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,\n\t\t\t blocksize, hinfo, map);\n\tmap -= count;\n\tdx_sort_map(map, count);\n\t/* Ensure that neither split block is over half full */\n\tsize = 0;\n\tmove = 0;\n\tfor (i = count-1; i >= 0; i--) {\n\t\t/* is more than half of this entry in 2nd half of the block? */\n\t\tif (size + map[i].size/2 > blocksize/2)\n\t\t\tbreak;\n\t\tsize += map[i].size;\n\t\tmove++;\n\t}\n\t/*\n\t * map index at which we will split\n\t *\n\t * If the sum of active entries didn't exceed half the block size, just\n\t * split it in half by count; each resulting block will have at least\n\t * half the space free.\n\t */\n\tif (i > 0)\n\t\tsplit = count - move;\n\telse\n\t\tsplit = count/2;\n\n\thash2 = map[split].hash;\n\tcontinued = hash2 == map[split - 1].hash;\n\tdxtrace(printk(KERN_INFO \"Split block %lu at %x, %i/%i\\n\",\n\t\t\t(unsigned long)dx_get_block(frame->at),\n\t\t\t\t\thash2, split, count-split));\n\n\t/* Fancy dance to stay within two buffers */\n\tde2 = dx_move_dirents(data1, data2, map + split, count - split,\n\t\t\t blocksize);\n\tde = dx_pack_dirents(data1, blocksize);\n\tde->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -\n\t\t\t\t\t (char *) de,\n\t\t\t\t\t blocksize);\n\tde2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -\n\t\t\t\t\t (char *) de2,\n\t\t\t\t\t blocksize);\n\tif (csum_size) {\n\t\text4_initialize_dirent_tail(*bh, blocksize);\n\t\text4_initialize_dirent_tail(bh2, blocksize);\n\t}\n\n\tdxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,\n\t\t\tblocksize, 1));\n\tdxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,\n\t\t\tblocksize, 1));\n\n\t/* Which block gets the new entry? */\n\tif (hinfo->hash >= hash2) {\n\t\tswap(*bh, bh2);\n\t\tde = de2;\n\t}\n\tdx_insert_block(frame, hash2 + continued, newblock);\n\terr = ext4_handle_dirty_dirblock(handle, dir, bh2);\n\tif (err)\n\t\tgoto journal_error;\n\terr = ext4_handle_dirty_dx_node(handle, dir, frame->bh);\n\tif (err)\n\t\tgoto journal_error;\n\tbrelse(bh2);\n\tdxtrace(dx_show_index(\"frame\", frame->entries));\n\treturn de;\n\njournal_error:\n\tbrelse(*bh);\n\tbrelse(bh2);\n\t*bh = NULL;\n\text4_std_error(dir->i_sb, err);\n\treturn ERR_PTR(err);\n}", "project": "linux", "hash": 129777832969130454101953936431569714950, "size": 115, "commit_id": "5872331b3d91820e14716632ebb56b1399b34fe1", "message": "ext4: fix potential negative array index in do_split()\n\nIf for any reason a directory passed to do_split() does not have enough\nactive entries to exceed half the size of the block, we can end up\niterating over all \"count\" entries without finding a split point.\n\nIn this case, count == move, and split will be zero, and we will\nattempt a negative index into map[].\n\nGuard against this by detecting this case, and falling back to\nsplit-to-half-of-count instead; in this case we will still have\nplenty of space (> half blocksize) in each split block.\n\nFixes: ef2b02d3e617 (\"ext34: ensure do_split leaves enough free space in both blocks\")\nSigned-off-by: Eric Sandeen <sandeen@redhat.com>\nReviewed-by: Andreas Dilger <adilger@dilger.ca>\nReviewed-by: Jan Kara <jack@suse.cz>\nLink: https://lore.kernel.org/r/f53e246b-647c-64bb-16ec-135383c70ad7@redhat.com\nSigned-off-by: Theodore Ts'o <tytso@mit.edu>", "target": 0, "dataset": "other", "idx": 451257}
  889. {"func": "int to_pkcs8(char* in_path, char* out_path, char* file_pin)\n{\n\tFILE* file_pointer = NULL;\n\tchar line[MAX_LINE], data[MAX_LINE];\n\tchar* value_pointer = NULL;\n\tint lineno = 0, m, n, error = 0, found, algorithm = DNS_KEYALG_ERROR, data_length;\n\tuint32_t bitfield = 0;\n\tkey_material_t pkey[TAG_MAX];\n\n\tif (in_path == NULL)\n\t{\n\t\tfprintf(stderr, \"ERROR: A path to the input file must be supplied. Use --in <path>\\n\");\n\t\treturn 1;\n\t}\n\n\tif (out_path == NULL)\n\t{\n\t\tfprintf(stderr, \"ERROR: A path to the output file must be supplied. Use --out <path>\\n\");\n\t\treturn 1;\n\t}\n\n\tfile_pointer = fopen(in_path, \"r\");\n\tif (file_pointer == NULL)\n\t{\n\t\tfprintf(stderr, \"ERROR: Could not open input file %.100s for reading.\\n\", in_path);\n\t\treturn 1;\n\t}\n\n\t// Loop over all of the lines\n\twhile (fgets(line, MAX_LINE, file_pointer) != NULL)\n\t{\n\t\tlineno++;\n\n\t\t// Find the current text field in the BIND file.\n\t\tfor (m = 0, found = -1; found == -1 && file_tags[m]; m++)\n\t\t{\n\t\t\tif (strncasecmp(line, file_tags[m], strlen(file_tags[m])) == 0)\n\t\t\t{\n\t\t\t\tfound = m;\n\t\t\t}\n\t\t}\n\n\t\t// The text files is not recognized.\n\t\tif (found == -1)\n\t\t{\n\t\t\tfprintf(stderr, \"ERROR: Unrecognized input line %i\\n\", lineno);\n\t\t\tfprintf(stderr, \"ERROR: --> %s\", line);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Point to the data for this text field.\n\t\tvalue_pointer = line + strlen(file_tags[found]) + 1;\n\n\t\t// Continue if we are at the end of the string\n\t\tif (*value_pointer == 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check that we do not get duplicates.\n\t\tif (bitfield & (1 << found))\n\t\t{\n\t\t\tfprintf(stderr, \"ERROR: Duplicate \\\"%s\\\" field, line %i - ignored\\n\",\n\t\t\t\t\tfile_tags[found], lineno);\n\t\t\tcontinue;\n\t\t}\n\t\tbitfield |= (1 << found);\n\n\t\t// Handle the data for this text field.\n\t\tswitch (found)\n\t\t{\n\t\t\tcase TAG_VERSION:\n\t\t\t\tif (sscanf(value_pointer, \"v%i.%i\", &m, &n) != 2)\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr, \"ERROR: Invalid/unknown version string \"\n\t\t\t\t\t\t\t\"(%.100s).\\n\", value_pointer);\n\t\t\t\t\terror = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (m > FILE_MAJOR_VERSION || (m == FILE_MAJOR_VERSION && n > FILE_MINOR_VERSION))\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr, \"ERROR: Cannot parse this version of file format, \"\n\t\t\t\t\t\t\t\"v%i.%i.\\n\", m, n);\n\t\t\t\t\terror = 1;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TAG_ALGORITHM:\n\t\t\t\talgorithm = strtol(value_pointer, NULL, 10);\n\t\t\t\tbreak;\n\t\t\t// RSA\n\t\t\tcase TAG_MODULUS:\n\t\t\tcase TAG_PUBEXP:\n\t\t\tcase TAG_PRIVEXP:\n\t\t\tcase TAG_PRIME1:\n\t\t\tcase TAG_PRIME2:\n\t\t\tcase TAG_EXP1:\n\t\t\tcase TAG_EXP2:\n\t\t\tcase TAG_COEFF:\n\t\t\t// DSA\n\t\t\tcase TAG_PRIME:\n\t\t\tcase TAG_SUBPRIME:\n\t\t\tcase TAG_BASE:\n\t\t\tcase TAG_PRIVVAL:\n\t\t\tcase TAG_PUBVAL:\n\t\t\t\tdata_length = b64_pton(value_pointer, (unsigned char*)data, MAX_LINE);\n\t\t\t\tif (data_length == -1)\n\t\t\t\t{\n\t\t\t\t\terror = 1;\n\t\t\t\t\tfprintf(stderr, \"ERROR: Could not parse the base64 string on line %i.\\n\", lineno);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpkey[found].big = malloc(data_length);\n\t\t\t\t\tif (!pkey[found].big)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"ERROR: Could not allocate memory.\\n\");\n\t\t\t\t\t\terror = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tmemcpy(pkey[found].big, data, data_length);\n\t\t\t\t\tpkey[found].size = data_length;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Do not need these\n\t\t\tcase TAG_CREATED:\n\t\t\tcase TAG_PUBLISH:\n\t\t\tcase TAG_ACTIVATE:\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tfclose(file_pointer);\n\n\t// Something went wrong. Clean up and quit.\n\tif (error)\n\t{\n\t\tfree_key_material(pkey);\n\t\treturn error;\n\t}\n\n\tcrypto_init();\n\n\t// Save the the key to the disk\n\tswitch (algorithm)\n\t{\n\t\tcase DNS_KEYALG_ERROR:\n\t\t\tfprintf(stderr, \"ERROR: The algorithm %i was not given in the file.\\n\",\n\t\t\t\t\talgorithm);\n\t\t\terror = 1;\n\t\t\tbreak;\n\t\tcase DNS_KEYALG_RSAMD5:\n\t\tcase DNS_KEYALG_RSASHA1:\n\t\tcase DNS_KEYALG_RSASHA1_NSEC3_SHA1:\n\t\tcase DNS_KEYALG_RSASHA256:\n\t\tcase DNS_KEYALG_RSASHA512:\n\t\t\terror = save_rsa_pkcs8(out_path, file_pin, pkey);\n\t\t\tbreak;\n\t\tcase DNS_KEYALG_DSA:\n\t\tcase DNS_KEYALG_DSA_NSEC3_SHA1:\n\t\t\terror = save_dsa_pkcs8(out_path, file_pin, pkey);\n\t\t\tbreak;\n\t\tcase DNS_KEYALG_ECC:\n\t\tcase DNS_KEYALG_ECC_GOST:\n\t\tdefault:\n\t\t\tfprintf(stderr, \"ERROR: The algorithm %i is not supported.\\n\",\n\t\t\t\t\talgorithm);\n\t\t\terror = 1;\n\t\t\tbreak;\n\t}\n\n\tcrypto_final();\n\tfree_key_material(pkey);\n\n\treturn error;\n}", "project": "SoftHSMv2", "hash": 327232896342706582422940253312057636815, "size": 176, "commit_id": "492447cd4a2be449e99fb9ad2519ea3277aaad28", "message": "SUPPORT-136: softhsm2-keyconv creates files with sensitive material in insecure way.", "target": 1, "dataset": "other", "idx": 211835}
  890. {"func": "int to_pkcs8(char* in_path, char* out_path, char* file_pin)\n{\n\tFILE* file_pointer = NULL;\n\tchar line[MAX_LINE], data[MAX_LINE];\n\tchar* value_pointer = NULL;\n\tint lineno = 0, m, n, error = 0, found, algorithm = DNS_KEYALG_ERROR, data_length;\n\tuint32_t bitfield = 0;\n\tkey_material_t pkey[TAG_MAX];\n\n\tif (in_path == NULL)\n\t{\n\t\tfprintf(stderr, \"ERROR: A path to the input file must be supplied. Use --in <path>\\n\");\n\t\treturn 1;\n\t}\n\n\tif (out_path == NULL)\n\t{\n\t\tfprintf(stderr, \"ERROR: A path to the output file must be supplied. Use --out <path>\\n\");\n\t\treturn 1;\n\t}\n\n\tfile_pointer = fopen(in_path, \"r\");\n\tif (file_pointer == NULL)\n\t{\n\t\tfprintf(stderr, \"ERROR: Could not open input file %.100s for reading.\\n\", in_path);\n\t\treturn 1;\n\t}\n\n\t// Loop over all of the lines\n\twhile (fgets(line, MAX_LINE, file_pointer) != NULL)\n\t{\n\t\tlineno++;\n\n\t\t// Find the current text field in the BIND file.\n\t\tfor (m = 0, found = -1; found == -1 && file_tags[m]; m++)\n\t\t{\n\t\t\tif (strncasecmp(line, file_tags[m], strlen(file_tags[m])) == 0)\n\t\t\t{\n\t\t\t\tfound = m;\n\t\t\t}\n\t\t}\n\n\t\t// The text files is not recognized.\n\t\tif (found == -1)\n\t\t{\n\t\t\tfprintf(stderr, \"ERROR: Unrecognized input line %i\\n\", lineno);\n\t\t\tfprintf(stderr, \"ERROR: --> %s\", line);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Point to the data for this text field.\n\t\tvalue_pointer = line + strlen(file_tags[found]) + 1;\n\n\t\t// Continue if we are at the end of the string\n\t\tif (*value_pointer == 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check that we do not get duplicates.\n\t\tif (bitfield & (1 << found))\n\t\t{\n\t\t\tfprintf(stderr, \"ERROR: Duplicate \\\"%s\\\" field, line %i - ignored\\n\",\n\t\t\t\t\tfile_tags[found], lineno);\n\t\t\tcontinue;\n\t\t}\n\t\tbitfield |= (1 << found);\n\n\t\t// Handle the data for this text field.\n\t\tswitch (found)\n\t\t{\n\t\t\tcase TAG_VERSION:\n\t\t\t\tif (sscanf(value_pointer, \"v%i.%i\", &m, &n) != 2)\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr, \"ERROR: Invalid/unknown version string \"\n\t\t\t\t\t\t\t\"(%.100s).\\n\", value_pointer);\n\t\t\t\t\terror = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (m > FILE_MAJOR_VERSION || (m == FILE_MAJOR_VERSION && n > FILE_MINOR_VERSION))\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr, \"ERROR: Cannot parse this version of file format, \"\n\t\t\t\t\t\t\t\"v%i.%i.\\n\", m, n);\n\t\t\t\t\terror = 1;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TAG_ALGORITHM:\n\t\t\t\talgorithm = strtol(value_pointer, NULL, 10);\n\t\t\t\tbreak;\n\t\t\t// RSA\n\t\t\tcase TAG_MODULUS:\n\t\t\tcase TAG_PUBEXP:\n\t\t\tcase TAG_PRIVEXP:\n\t\t\tcase TAG_PRIME1:\n\t\t\tcase TAG_PRIME2:\n\t\t\tcase TAG_EXP1:\n\t\t\tcase TAG_EXP2:\n\t\t\tcase TAG_COEFF:\n\t\t\t// DSA\n\t\t\tcase TAG_PRIME:\n\t\t\tcase TAG_SUBPRIME:\n\t\t\tcase TAG_BASE:\n\t\t\tcase TAG_PRIVVAL:\n\t\t\tcase TAG_PUBVAL:\n\t\t\t\tdata_length = b64_pton(value_pointer, (unsigned char*)data, MAX_LINE);\n\t\t\t\tif (data_length == -1)\n\t\t\t\t{\n\t\t\t\t\terror = 1;\n\t\t\t\t\tfprintf(stderr, \"ERROR: Could not parse the base64 string on line %i.\\n\", lineno);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpkey[found].big = malloc(data_length);\n\t\t\t\t\tif (!pkey[found].big)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"ERROR: Could not allocate memory.\\n\");\n\t\t\t\t\t\terror = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tmemcpy(pkey[found].big, data, data_length);\n\t\t\t\t\tpkey[found].size = data_length;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Do not need these\n\t\t\tcase TAG_CREATED:\n\t\t\tcase TAG_PUBLISH:\n\t\t\tcase TAG_ACTIVATE:\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tfclose(file_pointer);\n\n\t// Something went wrong. Clean up and quit.\n\tif (error)\n\t{\n\t\tfree_key_material(pkey);\n\t\treturn error;\n\t}\n\n\t// Create and set file permissions if the file does not exist.\n\tint fd = open(out_path, O_CREAT, S_IRUSR | S_IWUSR);\n\tif (fd == -1)\n\t{\n\t\tfprintf(stderr, \"ERROR: Could not open the output file: %s (errno %i)\\n\",\n\t\t\tout_path, errno);\n\t\tfree_key_material(pkey);\n\t\treturn 1;\n\t}\n\t::close(fd);\n\n\tcrypto_init();\n\n\t// Save the the key to the disk\n\tswitch (algorithm)\n\t{\n\t\tcase DNS_KEYALG_ERROR:\n\t\t\tfprintf(stderr, \"ERROR: The algorithm %i was not given in the file.\\n\",\n\t\t\t\t\talgorithm);\n\t\t\terror = 1;\n\t\t\tbreak;\n\t\tcase DNS_KEYALG_RSAMD5:\n\t\tcase DNS_KEYALG_RSASHA1:\n\t\tcase DNS_KEYALG_RSASHA1_NSEC3_SHA1:\n\t\tcase DNS_KEYALG_RSASHA256:\n\t\tcase DNS_KEYALG_RSASHA512:\n\t\t\terror = save_rsa_pkcs8(out_path, file_pin, pkey);\n\t\t\tbreak;\n\t\tcase DNS_KEYALG_DSA:\n\t\tcase DNS_KEYALG_DSA_NSEC3_SHA1:\n\t\t\terror = save_dsa_pkcs8(out_path, file_pin, pkey);\n\t\t\tbreak;\n\t\tcase DNS_KEYALG_ECC:\n\t\tcase DNS_KEYALG_ECC_GOST:\n\t\tdefault:\n\t\t\tfprintf(stderr, \"ERROR: The algorithm %i is not supported.\\n\",\n\t\t\t\t\talgorithm);\n\t\t\terror = 1;\n\t\t\tbreak;\n\t}\n\n\tcrypto_final();\n\tfree_key_material(pkey);\n\n\treturn error;\n}", "project": "SoftHSMv2", "hash": 230438268535972040487908663022608902484, "size": 187, "commit_id": "492447cd4a2be449e99fb9ad2519ea3277aaad28", "message": "SUPPORT-136: softhsm2-keyconv creates files with sensitive material in insecure way.", "target": 0, "dataset": "other", "idx": 452351}
  891. {"func": "int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) {\n TIFFSTATE *clientstate = (TIFFSTATE *)state->context;\n char *filename = \"tempfile.tif\";\n char *mode = \"r\";\n TIFF *tiff;\n\n /* buffer is the encoded file, bytes is the length of the encoded file */\n /* it all ends up in state->buffer, which is a uint8* from Imaging.h */\n\n TRACE((\"in decoder: bytes %d\\n\", bytes));\n TRACE((\"State: count %d, state %d, x %d, y %d, ystep %d\\n\", state->count, state->state,\n state->x, state->y, state->ystep));\n TRACE((\"State: xsize %d, ysize %d, xoff %d, yoff %d \\n\", state->xsize, state->ysize,\n state->xoff, state->yoff));\n TRACE((\"State: bits %d, bytes %d \\n\", state->bits, state->bytes));\n TRACE((\"Buffer: %p: %c%c%c%c\\n\", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3]));\n TRACE((\"State->Buffer: %c%c%c%c\\n\", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3]));\n TRACE((\"Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \\n\",\n im->mode, im->type, im->bands, im->xsize, im->ysize));\n TRACE((\"Image: image8 %p, image32 %p, image %p, block %p \\n\",\n im->image8, im->image32, im->image, im->block));\n TRACE((\"Image: pixelsize: %d, linesize %d \\n\",\n im->pixelsize, im->linesize));\n\n dump_state(clientstate);\n clientstate->size = bytes;\n clientstate->eof = clientstate->size;\n clientstate->loc = 0;\n clientstate->data = (tdata_t)buffer;\n clientstate->flrealloc = 0;\n dump_state(clientstate);\n\n TIFFSetWarningHandler(NULL);\n TIFFSetWarningHandlerExt(NULL);\n\n if (clientstate->fp) {\n TRACE((\"Opening using fd: %d\\n\",clientstate->fp));\n lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end.\n tiff = TIFFFdOpen(clientstate->fp, filename, mode);\n } else {\n TRACE((\"Opening from string\\n\"));\n tiff = TIFFClientOpen(filename, mode,\n (thandle_t) clientstate,\n _tiffReadProc, _tiffWriteProc,\n _tiffSeekProc, _tiffCloseProc, _tiffSizeProc,\n _tiffMapProc, _tiffUnmapProc);\n }\n\n if (!tiff){\n TRACE((\"Error, didn't get the tiff\\n\"));\n state->errcode = IMAGING_CODEC_BROKEN;\n return -1;\n }\n\n if (clientstate->ifd){\n int rv;\n uint32 ifdoffset = clientstate->ifd;\n TRACE((\"reading tiff ifd %u\\n\", ifdoffset));\n rv = TIFFSetSubDirectory(tiff, ifdoffset);\n if (!rv){\n TRACE((\"error in TIFFSetSubDirectory\"));\n return -1;\n }\n }\n\n if (TIFFIsTiled(tiff)) {\n UINT32 x, y, tile_y, row_byte_size;\n UINT32 tile_width, tile_length, current_tile_width;\n UINT8 *new_data;\n\n TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width);\n TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length);\n\n // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size\n row_byte_size = (tile_width * state->bits + 7) / 8;\n state->bytes = row_byte_size * tile_length;\n\n /* overflow check for malloc */\n if (state->bytes > INT_MAX - 1) {\n state->errcode = IMAGING_CODEC_MEMORY;\n TIFFClose(tiff);\n return -1;\n }\n\n /* realloc to fit whole tile */\n new_data = realloc (state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n TIFFClose(tiff);\n return -1;\n }\n\n state->buffer = new_data;\n\n TRACE((\"TIFFTileSize: %d\\n\", state->bytes));\n\n for (y = state->yoff; y < state->ysize; y += tile_length) {\n for (x = state->xoff; x < state->xsize; x += tile_width) {\n if (ReadTile(tiff, x, y, (UINT32*) state->buffer) == -1) {\n TRACE((\"Decode Error, Tile at %dx%d\\n\", x, y));\n state->errcode = IMAGING_CODEC_BROKEN;\n TIFFClose(tiff);\n return -1;\n }\n\n TRACE((\"Read tile at %dx%d; \\n\\n\", x, y));\n\n current_tile_width = min(tile_width, state->xsize - x);\n\n // iterate over each line in the tile and stuff data into image\n for (tile_y = 0; tile_y < min(tile_length, state->ysize - y); tile_y++) {\n TRACE((\"Writing tile data at %dx%d using tile_width: %d; \\n\", tile_y + y, x, current_tile_width));\n\n // UINT8 * bbb = state->buffer + tile_y * row_byte_size;\n // TRACE((\"chars: %x%x%x%x\\n\", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize,\n state->buffer + tile_y * row_byte_size,\n current_tile_width\n );\n }\n }\n }\n } else {\n UINT32 strip_row, row_byte_size;\n UINT8 *new_data;\n UINT32 rows_per_strip;\n int ret;\n\n ret = TIFFGetField(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 // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size\n row_byte_size = (state->xsize * state->bits + 7) / 8;\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 new_data = realloc (state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n TIFFClose(tiff);\n return -1;\n }\n\n state->buffer = new_data;\n\n for (; state->y < state->ysize; state->y += rows_per_strip) {\n if (ReadStrip(tiff, state->y, (UINT32 *)state->buffer) == -1) {\n TRACE((\"Decode Error, strip %d\\n\", TIFFComputeStrip(tiff, state->y, 0)));\n state->errcode = IMAGING_CODEC_BROKEN;\n TIFFClose(tiff);\n return -1;\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; strip_row < min(rows_per_strip, state->ysize - state->y); strip_row++) {\n TRACE((\"Writing data into line %d ; \\n\", state->y + strip_row));\n\n // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip);\n // TRACE((\"chars: %x %x %x %x\\n\", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle((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 }\n\n TIFFClose(tiff);\n TRACE((\"Done Decoding, Returning \\n\"));\n // Returning -1 here to force ImageFile.load to break, rather than\n // even think about looping back around.\n return -1;\n}", "project": "Pillow", "hash": 270190227381984561901599925314913105490, "size": 182, "commit_id": "4e2def2539ec13e53a82e06c4b3daf00454100c4", "message": "Overflow checks for realloc for tiff decoding", "target": 1, "dataset": "other", "idx": 211908}
  892. {"func": "int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) {\n TIFFSTATE *clientstate = (TIFFSTATE *)state->context;\n char *filename = \"tempfile.tif\";\n char *mode = \"r\";\n TIFF *tiff;\n\n /* buffer is the encoded file, bytes is the length of the encoded file */\n /* it all ends up in state->buffer, which is a uint8* from Imaging.h */\n\n TRACE((\"in decoder: bytes %d\\n\", bytes));\n TRACE((\"State: count %d, state %d, x %d, y %d, ystep %d\\n\", state->count, state->state,\n state->x, state->y, state->ystep));\n TRACE((\"State: xsize %d, ysize %d, xoff %d, yoff %d \\n\", state->xsize, state->ysize,\n state->xoff, state->yoff));\n TRACE((\"State: bits %d, bytes %d \\n\", state->bits, state->bytes));\n TRACE((\"Buffer: %p: %c%c%c%c\\n\", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3]));\n TRACE((\"State->Buffer: %c%c%c%c\\n\", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3]));\n TRACE((\"Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \\n\",\n im->mode, im->type, im->bands, im->xsize, im->ysize));\n TRACE((\"Image: image8 %p, image32 %p, image %p, block %p \\n\",\n im->image8, im->image32, im->image, im->block));\n TRACE((\"Image: pixelsize: %d, linesize %d \\n\",\n im->pixelsize, im->linesize));\n\n dump_state(clientstate);\n clientstate->size = bytes;\n clientstate->eof = clientstate->size;\n clientstate->loc = 0;\n clientstate->data = (tdata_t)buffer;\n clientstate->flrealloc = 0;\n dump_state(clientstate);\n\n TIFFSetWarningHandler(NULL);\n TIFFSetWarningHandlerExt(NULL);\n\n if (clientstate->fp) {\n TRACE((\"Opening using fd: %d\\n\",clientstate->fp));\n lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end.\n tiff = TIFFFdOpen(clientstate->fp, filename, mode);\n } else {\n TRACE((\"Opening from string\\n\"));\n tiff = TIFFClientOpen(filename, mode,\n (thandle_t) clientstate,\n _tiffReadProc, _tiffWriteProc,\n _tiffSeekProc, _tiffCloseProc, _tiffSizeProc,\n _tiffMapProc, _tiffUnmapProc);\n }\n\n if (!tiff){\n TRACE((\"Error, didn't get the tiff\\n\"));\n state->errcode = IMAGING_CODEC_BROKEN;\n return -1;\n }\n\n if (clientstate->ifd){\n int rv;\n uint32 ifdoffset = clientstate->ifd;\n TRACE((\"reading tiff ifd %u\\n\", ifdoffset));\n rv = TIFFSetSubDirectory(tiff, ifdoffset);\n if (!rv){\n TRACE((\"error in TIFFSetSubDirectory\"));\n return -1;\n }\n }\n\n if (TIFFIsTiled(tiff)) {\n UINT32 x, y, tile_y, row_byte_size;\n UINT32 tile_width, tile_length, current_tile_width;\n UINT8 *new_data;\n\n TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width);\n TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length);\n\n // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size\n row_byte_size = (tile_width * state->bits + 7) / 8;\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < tile_length) {\n state->errcode = IMAGING_CODEC_MEMORY;\n TIFFClose(tiff);\n return -1;\n }\n \n state->bytes = row_byte_size * tile_length;\n\n /* realloc to fit whole tile */\n /* malloc check above */\n new_data = realloc (state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n TIFFClose(tiff);\n return -1;\n }\n\n state->buffer = new_data;\n\n TRACE((\"TIFFTileSize: %d\\n\", state->bytes));\n\n for (y = state->yoff; y < state->ysize; y += tile_length) {\n for (x = state->xoff; x < state->xsize; x += tile_width) {\n if (ReadTile(tiff, x, y, (UINT32*) state->buffer) == -1) {\n TRACE((\"Decode Error, Tile at %dx%d\\n\", x, y));\n state->errcode = IMAGING_CODEC_BROKEN;\n TIFFClose(tiff);\n return -1;\n }\n\n TRACE((\"Read tile at %dx%d; \\n\\n\", x, y));\n\n current_tile_width = min(tile_width, state->xsize - x);\n\n // iterate over each line in the tile and stuff data into image\n for (tile_y = 0; tile_y < min(tile_length, state->ysize - y); tile_y++) {\n TRACE((\"Writing tile data at %dx%d using tile_width: %d; \\n\", tile_y + y, x, current_tile_width));\n\n // UINT8 * bbb = state->buffer + tile_y * row_byte_size;\n // TRACE((\"chars: %x%x%x%x\\n\", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize,\n state->buffer + tile_y * row_byte_size,\n current_tile_width\n );\n }\n }\n }\n } else {\n UINT32 strip_row, row_byte_size;\n UINT8 *new_data;\n UINT32 rows_per_strip;\n int ret;\n\n ret = TIFFGetField(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 // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size\n row_byte_size = (state->xsize * state->bits + 7) / 8;\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < rows_per_strip) {\n state->errcode = IMAGING_CODEC_MEMORY;\n TIFFClose(tiff);\n return -1;\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 TIFFClose(tiff);\n return -1;\n }\n\n state->buffer = new_data;\n\n for (; state->y < state->ysize; state->y += rows_per_strip) {\n if (ReadStrip(tiff, state->y, (UINT32 *)state->buffer) == -1) {\n TRACE((\"Decode Error, strip %d\\n\", TIFFComputeStrip(tiff, state->y, 0)));\n state->errcode = IMAGING_CODEC_BROKEN;\n TIFFClose(tiff);\n return -1;\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; strip_row < min(rows_per_strip, state->ysize - state->y); strip_row++) {\n TRACE((\"Writing data into line %d ; \\n\", state->y + strip_row));\n\n // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip);\n // TRACE((\"chars: %x %x %x %x\\n\", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle((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 }\n\n TIFFClose(tiff);\n TRACE((\"Done Decoding, Returning \\n\"));\n // Returning -1 here to force ImageFile.load to break, rather than\n // even think about looping back around.\n return -1;\n}", "project": "Pillow", "hash": 88829763694371056964147542819562350572, "size": 193, "commit_id": "4e2def2539ec13e53a82e06c4b3daf00454100c4", "message": "Overflow checks for realloc for tiff decoding", "target": 0, "dataset": "other", "idx": 453246}
  893. {"func": "\nstatic void bfq_idle_slice_timer_body(struct bfq_queue *bfqq)\n{\n\tstruct bfq_data *bfqd = bfqq->bfqd;\n\tenum bfqq_expiration reason;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&bfqd->lock, flags);\n\tbfq_clear_bfqq_wait_request(bfqq);\n\n\tif (bfqq != bfqd->in_service_queue) {\n\t\tspin_unlock_irqrestore(&bfqd->lock, flags);\n\t\treturn;\n\t}\n\n\tif (bfq_bfqq_budget_timeout(bfqq))\n\t\t/*\n\t\t * Also here the queue can be safely expired\n\t\t * for budget timeout without wasting\n\t\t * guarantees\n\t\t */\n\t\treason = BFQQE_BUDGET_TIMEOUT;\n\telse if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)\n\t\t/*\n\t\t * The queue may not be empty upon timer expiration,\n\t\t * because we may not disable the timer when the\n\t\t * first request of the in-service queue arrives\n\t\t * during disk idling.\n\t\t */\n\t\treason = BFQQE_TOO_IDLE;\n\telse\n\t\tgoto schedule_dispatch;\n\n\tbfq_bfqq_expire(bfqd, bfqq, true, reason);\n\nschedule_dispatch:\n\tspin_unlock_irqrestore(&bfqd->lock, flags);\n\tbfq_schedule_dispatch(bfqd);", "project": "linux", "hash": 128858888171698182771172635480199449190, "size": 38, "commit_id": "2f95fa5c955d0a9987ffdc3a095e2f4e62c5f2a9", "message": "block, bfq: fix use-after-free in bfq_idle_slice_timer_body\n\nIn bfq_idle_slice_timer func, bfqq = bfqd->in_service_queue is\nnot in bfqd-lock critical section. The bfqq, which is not\nequal to NULL in bfq_idle_slice_timer, may be freed after passing\nto bfq_idle_slice_timer_body. So we will access the freed memory.\n\nIn addition, considering the bfqq may be in race, we should\nfirstly check whether bfqq is in service before doing something\non it in bfq_idle_slice_timer_body func. If the bfqq in race is\nnot in service, it means the bfqq has been expired through\n__bfq_bfqq_expire func, and wait_request flags has been cleared in\n__bfq_bfqd_reset_in_service func. So we do not need to re-clear the\nwait_request of bfqq which is not in service.\n\nKASAN log is given as follows:\n[13058.354613] ==================================================================\n[13058.354640] BUG: KASAN: use-after-free in bfq_idle_slice_timer+0xac/0x290\n[13058.354644] Read of size 8 at addr ffffa02cf3e63f78 by task fork13/19767\n[13058.354646]\n[13058.354655] CPU: 96 PID: 19767 Comm: fork13\n[13058.354661] Call trace:\n[13058.354667] dump_backtrace+0x0/0x310\n[13058.354672] show_stack+0x28/0x38\n[13058.354681] dump_stack+0xd8/0x108\n[13058.354687] print_address_description+0x68/0x2d0\n[13058.354690] kasan_report+0x124/0x2e0\n[13058.354697] __asan_load8+0x88/0xb0\n[13058.354702] bfq_idle_slice_timer+0xac/0x290\n[13058.354707] __hrtimer_run_queues+0x298/0x8b8\n[13058.354710] hrtimer_interrupt+0x1b8/0x678\n[13058.354716] arch_timer_handler_phys+0x4c/0x78\n[13058.354722] handle_percpu_devid_irq+0xf0/0x558\n[13058.354731] generic_handle_irq+0x50/0x70\n[13058.354735] __handle_domain_irq+0x94/0x110\n[13058.354739] gic_handle_irq+0x8c/0x1b0\n[13058.354742] el1_irq+0xb8/0x140\n[13058.354748] do_wp_page+0x260/0xe28\n[13058.354752] __handle_mm_fault+0x8ec/0x9b0\n[13058.354756] handle_mm_fault+0x280/0x460\n[13058.354762] do_page_fault+0x3ec/0x890\n[13058.354765] do_mem_abort+0xc0/0x1b0\n[13058.354768] el0_da+0x24/0x28\n[13058.354770]\n[13058.354773] Allocated by task 19731:\n[13058.354780] kasan_kmalloc+0xe0/0x190\n[13058.354784] kasan_slab_alloc+0x14/0x20\n[13058.354788] kmem_cache_alloc_node+0x130/0x440\n[13058.354793] bfq_get_queue+0x138/0x858\n[13058.354797] bfq_get_bfqq_handle_split+0xd4/0x328\n[13058.354801] bfq_init_rq+0x1f4/0x1180\n[13058.354806] bfq_insert_requests+0x264/0x1c98\n[13058.354811] blk_mq_sched_insert_requests+0x1c4/0x488\n[13058.354818] blk_mq_flush_plug_list+0x2d4/0x6e0\n[13058.354826] blk_flush_plug_list+0x230/0x548\n[13058.354830] blk_finish_plug+0x60/0x80\n[13058.354838] read_pages+0xec/0x2c0\n[13058.354842] __do_page_cache_readahead+0x374/0x438\n[13058.354846] ondemand_readahead+0x24c/0x6b0\n[13058.354851] page_cache_sync_readahead+0x17c/0x2f8\n[13058.354858] generic_file_buffered_read+0x588/0xc58\n[13058.354862] generic_file_read_iter+0x1b4/0x278\n[13058.354965] ext4_file_read_iter+0xa8/0x1d8 [ext4]\n[13058.354972] __vfs_read+0x238/0x320\n[13058.354976] vfs_read+0xbc/0x1c0\n[13058.354980] ksys_read+0xdc/0x1b8\n[13058.354984] __arm64_sys_read+0x50/0x60\n[13058.354990] el0_svc_common+0xb4/0x1d8\n[13058.354994] el0_svc_handler+0x50/0xa8\n[13058.354998] el0_svc+0x8/0xc\n[13058.354999]\n[13058.355001] Freed by task 19731:\n[13058.355007] __kasan_slab_free+0x120/0x228\n[13058.355010] kasan_slab_free+0x10/0x18\n[13058.355014] kmem_cache_free+0x288/0x3f0\n[13058.355018] bfq_put_queue+0x134/0x208\n[13058.355022] bfq_exit_icq_bfqq+0x164/0x348\n[13058.355026] bfq_exit_icq+0x28/0x40\n[13058.355030] ioc_exit_icq+0xa0/0x150\n[13058.355035] put_io_context_active+0x250/0x438\n[13058.355038] exit_io_context+0xd0/0x138\n[13058.355045] do_exit+0x734/0xc58\n[13058.355050] do_group_exit+0x78/0x220\n[13058.355054] __wake_up_parent+0x0/0x50\n[13058.355058] el0_svc_common+0xb4/0x1d8\n[13058.355062] el0_svc_handler+0x50/0xa8\n[13058.355066] el0_svc+0x8/0xc\n[13058.355067]\n[13058.355071] The buggy address belongs to the object at ffffa02cf3e63e70#012 which belongs to the cache bfq_queue of size 464\n[13058.355075] The buggy address is located 264 bytes inside of#012 464-byte region [ffffa02cf3e63e70, ffffa02cf3e64040)\n[13058.355077] The buggy address belongs to the page:\n[13058.355083] page:ffff7e80b3cf9800 count:1 mapcount:0 mapping:ffff802db5c90780 index:0xffffa02cf3e606f0 compound_mapcount: 0\n[13058.366175] flags: 0x2ffffe0000008100(slab|head)\n[13058.370781] raw: 2ffffe0000008100 ffff7e80b53b1408 ffffa02d730c1c90 ffff802db5c90780\n[13058.370787] raw: ffffa02cf3e606f0 0000000000370023 00000001ffffffff 0000000000000000\n[13058.370789] page dumped because: kasan: bad access detected\n[13058.370791]\n[13058.370792] Memory state around the buggy address:\n[13058.370797] ffffa02cf3e63e00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fb fb\n[13058.370801] ffffa02cf3e63e80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370805] >ffffa02cf3e63f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370808] ^\n[13058.370811] ffffa02cf3e63f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370815] ffffa02cf3e64000: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc\n[13058.370817] ==================================================================\n[13058.370820] Disabling lock debugging due to kernel taint\n\nHere, we directly pass the bfqd to bfq_idle_slice_timer_body func.\n--\nV2->V3: rewrite the comment as suggested by Paolo Valente\nV1->V2: add one comment, and add Fixes and Reported-by tag.\n\nFixes: aee69d78d (\"block, bfq: introduce the BFQ-v0 I/O scheduler as an extra scheduler\")\nAcked-by: Paolo Valente <paolo.valente@linaro.org>\nReported-by: Wang Wang <wangwang2@huawei.com>\nSigned-off-by: Zhiqiang Liu <liuzhiqiang26@huawei.com>\nSigned-off-by: Feilong Lin <linfeilong@huawei.com>\nSigned-off-by: Jens Axboe <axboe@kernel.dk>", "target": 1, "dataset": "other", "idx": 211918}
  894. {"func": "static void\nbfq_idle_slice_timer_body(struct bfq_data *bfqd, struct bfq_queue *bfqq)\n{\n\tenum bfqq_expiration reason;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&bfqd->lock, flags);\n\n\t/*\n\t * Considering that bfqq may be in race, we should firstly check\n\t * whether bfqq is in service before doing something on it. If\n\t * the bfqq in race is not in service, it has already been expired\n\t * through __bfq_bfqq_expire func and its wait_request flags has\n\t * been cleared in __bfq_bfqd_reset_in_service func.\n\t */\n\tif (bfqq != bfqd->in_service_queue) {\n\t\tspin_unlock_irqrestore(&bfqd->lock, flags);\n\t\treturn;\n\t}\n\n\tbfq_clear_bfqq_wait_request(bfqq);\n\n\tif (bfq_bfqq_budget_timeout(bfqq))\n\t\t/*\n\t\t * Also here the queue can be safely expired\n\t\t * for budget timeout without wasting\n\t\t * guarantees\n\t\t */\n\t\treason = BFQQE_BUDGET_TIMEOUT;\n\telse if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)\n\t\t/*\n\t\t * The queue may not be empty upon timer expiration,\n\t\t * because we may not disable the timer when the\n\t\t * first request of the in-service queue arrives\n\t\t * during disk idling.\n\t\t */\n\t\treason = BFQQE_TOO_IDLE;\n\telse\n\t\tgoto schedule_dispatch;\n\n\tbfq_bfqq_expire(bfqd, bfqq, true, reason);\n\nschedule_dispatch:\n\tspin_unlock_irqrestore(&bfqd->lock, flags);\n\tbfq_schedule_dispatch(bfqd);", "project": "linux", "hash": 316977131305739620723653491038112566062, "size": 45, "commit_id": "2f95fa5c955d0a9987ffdc3a095e2f4e62c5f2a9", "message": "block, bfq: fix use-after-free in bfq_idle_slice_timer_body\n\nIn bfq_idle_slice_timer func, bfqq = bfqd->in_service_queue is\nnot in bfqd-lock critical section. The bfqq, which is not\nequal to NULL in bfq_idle_slice_timer, may be freed after passing\nto bfq_idle_slice_timer_body. So we will access the freed memory.\n\nIn addition, considering the bfqq may be in race, we should\nfirstly check whether bfqq is in service before doing something\non it in bfq_idle_slice_timer_body func. If the bfqq in race is\nnot in service, it means the bfqq has been expired through\n__bfq_bfqq_expire func, and wait_request flags has been cleared in\n__bfq_bfqd_reset_in_service func. So we do not need to re-clear the\nwait_request of bfqq which is not in service.\n\nKASAN log is given as follows:\n[13058.354613] ==================================================================\n[13058.354640] BUG: KASAN: use-after-free in bfq_idle_slice_timer+0xac/0x290\n[13058.354644] Read of size 8 at addr ffffa02cf3e63f78 by task fork13/19767\n[13058.354646]\n[13058.354655] CPU: 96 PID: 19767 Comm: fork13\n[13058.354661] Call trace:\n[13058.354667] dump_backtrace+0x0/0x310\n[13058.354672] show_stack+0x28/0x38\n[13058.354681] dump_stack+0xd8/0x108\n[13058.354687] print_address_description+0x68/0x2d0\n[13058.354690] kasan_report+0x124/0x2e0\n[13058.354697] __asan_load8+0x88/0xb0\n[13058.354702] bfq_idle_slice_timer+0xac/0x290\n[13058.354707] __hrtimer_run_queues+0x298/0x8b8\n[13058.354710] hrtimer_interrupt+0x1b8/0x678\n[13058.354716] arch_timer_handler_phys+0x4c/0x78\n[13058.354722] handle_percpu_devid_irq+0xf0/0x558\n[13058.354731] generic_handle_irq+0x50/0x70\n[13058.354735] __handle_domain_irq+0x94/0x110\n[13058.354739] gic_handle_irq+0x8c/0x1b0\n[13058.354742] el1_irq+0xb8/0x140\n[13058.354748] do_wp_page+0x260/0xe28\n[13058.354752] __handle_mm_fault+0x8ec/0x9b0\n[13058.354756] handle_mm_fault+0x280/0x460\n[13058.354762] do_page_fault+0x3ec/0x890\n[13058.354765] do_mem_abort+0xc0/0x1b0\n[13058.354768] el0_da+0x24/0x28\n[13058.354770]\n[13058.354773] Allocated by task 19731:\n[13058.354780] kasan_kmalloc+0xe0/0x190\n[13058.354784] kasan_slab_alloc+0x14/0x20\n[13058.354788] kmem_cache_alloc_node+0x130/0x440\n[13058.354793] bfq_get_queue+0x138/0x858\n[13058.354797] bfq_get_bfqq_handle_split+0xd4/0x328\n[13058.354801] bfq_init_rq+0x1f4/0x1180\n[13058.354806] bfq_insert_requests+0x264/0x1c98\n[13058.354811] blk_mq_sched_insert_requests+0x1c4/0x488\n[13058.354818] blk_mq_flush_plug_list+0x2d4/0x6e0\n[13058.354826] blk_flush_plug_list+0x230/0x548\n[13058.354830] blk_finish_plug+0x60/0x80\n[13058.354838] read_pages+0xec/0x2c0\n[13058.354842] __do_page_cache_readahead+0x374/0x438\n[13058.354846] ondemand_readahead+0x24c/0x6b0\n[13058.354851] page_cache_sync_readahead+0x17c/0x2f8\n[13058.354858] generic_file_buffered_read+0x588/0xc58\n[13058.354862] generic_file_read_iter+0x1b4/0x278\n[13058.354965] ext4_file_read_iter+0xa8/0x1d8 [ext4]\n[13058.354972] __vfs_read+0x238/0x320\n[13058.354976] vfs_read+0xbc/0x1c0\n[13058.354980] ksys_read+0xdc/0x1b8\n[13058.354984] __arm64_sys_read+0x50/0x60\n[13058.354990] el0_svc_common+0xb4/0x1d8\n[13058.354994] el0_svc_handler+0x50/0xa8\n[13058.354998] el0_svc+0x8/0xc\n[13058.354999]\n[13058.355001] Freed by task 19731:\n[13058.355007] __kasan_slab_free+0x120/0x228\n[13058.355010] kasan_slab_free+0x10/0x18\n[13058.355014] kmem_cache_free+0x288/0x3f0\n[13058.355018] bfq_put_queue+0x134/0x208\n[13058.355022] bfq_exit_icq_bfqq+0x164/0x348\n[13058.355026] bfq_exit_icq+0x28/0x40\n[13058.355030] ioc_exit_icq+0xa0/0x150\n[13058.355035] put_io_context_active+0x250/0x438\n[13058.355038] exit_io_context+0xd0/0x138\n[13058.355045] do_exit+0x734/0xc58\n[13058.355050] do_group_exit+0x78/0x220\n[13058.355054] __wake_up_parent+0x0/0x50\n[13058.355058] el0_svc_common+0xb4/0x1d8\n[13058.355062] el0_svc_handler+0x50/0xa8\n[13058.355066] el0_svc+0x8/0xc\n[13058.355067]\n[13058.355071] The buggy address belongs to the object at ffffa02cf3e63e70#012 which belongs to the cache bfq_queue of size 464\n[13058.355075] The buggy address is located 264 bytes inside of#012 464-byte region [ffffa02cf3e63e70, ffffa02cf3e64040)\n[13058.355077] The buggy address belongs to the page:\n[13058.355083] page:ffff7e80b3cf9800 count:1 mapcount:0 mapping:ffff802db5c90780 index:0xffffa02cf3e606f0 compound_mapcount: 0\n[13058.366175] flags: 0x2ffffe0000008100(slab|head)\n[13058.370781] raw: 2ffffe0000008100 ffff7e80b53b1408 ffffa02d730c1c90 ffff802db5c90780\n[13058.370787] raw: ffffa02cf3e606f0 0000000000370023 00000001ffffffff 0000000000000000\n[13058.370789] page dumped because: kasan: bad access detected\n[13058.370791]\n[13058.370792] Memory state around the buggy address:\n[13058.370797] ffffa02cf3e63e00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fb fb\n[13058.370801] ffffa02cf3e63e80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370805] >ffffa02cf3e63f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370808] ^\n[13058.370811] ffffa02cf3e63f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370815] ffffa02cf3e64000: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc\n[13058.370817] ==================================================================\n[13058.370820] Disabling lock debugging due to kernel taint\n\nHere, we directly pass the bfqd to bfq_idle_slice_timer_body func.\n--\nV2->V3: rewrite the comment as suggested by Paolo Valente\nV1->V2: add one comment, and add Fixes and Reported-by tag.\n\nFixes: aee69d78d (\"block, bfq: introduce the BFQ-v0 I/O scheduler as an extra scheduler\")\nAcked-by: Paolo Valente <paolo.valente@linaro.org>\nReported-by: Wang Wang <wangwang2@huawei.com>\nSigned-off-by: Zhiqiang Liu <liuzhiqiang26@huawei.com>\nSigned-off-by: Feilong Lin <linfeilong@huawei.com>\nSigned-off-by: Jens Axboe <axboe@kernel.dk>", "target": 0, "dataset": "other", "idx": 453337}
  895. {"func": "crypt_pw_cmp(const char *userpwd, const char *dbpwd)\n{\n int rc;\n char *cp;\n struct crypt_data data;\n data.initialized = 0;\n\n /* we use salt (first 2 chars) of encoded password in call to crypt_r() */\n cp = crypt_r(userpwd, dbpwd, &data);\n if (cp) {\n rc = slapi_ct_memcmp(dbpwd, cp, strlen(dbpwd));\n } else {\n rc = -1;\n }\n return rc;\n}", "project": "389-ds-base", "hash": 170054486704662206130926786349165718712, "size": 16, "commit_id": "aeb90eb0c41fc48541d983f323c627b2e6c328c7", "message": "Issue 4817 - BUG - locked crypt accounts on import may allow all passwords (#4819)\n\nBug Description: Due to mishanding of short dbpwd hashes, the\r\ncrypt_r algorithm was misused and was only comparing salts\r\nin some cases, rather than checking the actual content\r\nof the password.\r\n\r\nFix Description: Stricter checks on dbpwd lengths to ensure\r\nthat content passed to crypt_r has at least 2 salt bytes and\r\n1 hash byte, as well as stricter checks on ct_memcmp to ensure\r\nthat compared values are the same length, rather than potentially\r\nallowing overruns/short comparisons.\r\n\r\nfixes: https://github.com/389ds/389-ds-base/issues/4817\r\n\r\nAuthor: William Brown <william@blackhats.net.au>\r\n\r\nReview by: @mreynolds389", "target": 1, "dataset": "other", "idx": 211936}
  896. {"func": "crypt_pw_cmp(const char *userpwd, const char *dbpwd)\n{\n int rc = -1;\n char *cp = NULL;\n size_t dbpwd_len = strlen(dbpwd);\n struct crypt_data data;\n data.initialized = 0;\n\n /*\n * there MUST be at least 2 chars of salt and some pw bytes, else this is INVALID and will\n * allow any password to bind as we then only compare SALTS.\n */\n if (dbpwd_len >= 3) {\n /* we use salt (first 2 chars) of encoded password in call to crypt_r() */\n cp = crypt_r(userpwd, dbpwd, &data);\n }\n /* If these are not the same length, we can not proceed safely with memcmp. */\n if (cp && dbpwd_len == strlen(cp)) {\n rc = slapi_ct_memcmp(dbpwd, cp, dbpwd_len);\n } else {\n rc = -1;\n }\n return rc;\n}", "project": "389-ds-base", "hash": 40922764562624925085830862501615542298, "size": 24, "commit_id": "aeb90eb0c41fc48541d983f323c627b2e6c328c7", "message": "Issue 4817 - BUG - locked crypt accounts on import may allow all passwords (#4819)\n\nBug Description: Due to mishanding of short dbpwd hashes, the\r\ncrypt_r algorithm was misused and was only comparing salts\r\nin some cases, rather than checking the actual content\r\nof the password.\r\n\r\nFix Description: Stricter checks on dbpwd lengths to ensure\r\nthat content passed to crypt_r has at least 2 salt bytes and\r\n1 hash byte, as well as stricter checks on ct_memcmp to ensure\r\nthat compared values are the same length, rather than potentially\r\nallowing overruns/short comparisons.\r\n\r\nfixes: https://github.com/389ds/389-ds-base/issues/4817\r\n\r\nAuthor: William Brown <william@blackhats.net.au>\r\n\r\nReview by: @mreynolds389", "target": 0, "dataset": "other", "idx": 453456}
  897. {"func": "static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)\n{\n\tsc_context_t *ctx;\n\tsc_apdu_t apdu;\n\tu8 rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tu8 sbuf[SC_MAX_APDU_BUFFER_SIZE];\n\ttcos_data *data;\n\tint tcos3, r;\n\n\tassert(card != NULL && crgram != NULL && out != NULL);\n\tctx = card->ctx;\n\ttcos3=(card->type==SC_CARD_TYPE_TCOS_V3);\n\tdata=(tcos_data *)card->drv_data;\n\n\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t\t\"TCOS3:%d PKCS1:%d\\n\",tcos3,\n\t\t!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));\n\n\tsc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = crgram_len;\n\n\tapdu.data = sbuf;\n\tapdu.lc = apdu.datalen = crgram_len+1;\n\tsbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);\n\tmemcpy(sbuf+1, crgram, crgram_len);\n\n\tr = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(card->ctx, r, \"APDU transmit failed\");\n\n\tif (apdu.sw1==0x90 && apdu.sw2==0x00) {\n\t\tsize_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;\n\t\tunsigned int offset=0;\n\t\tif(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) {\n\t\t\toffset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;\n\t\t\toffset=(offset<len-1) ? offset+1 : 0;\n\t\t}\n\t\tmemcpy(out, apdu.resp+offset, len-offset);\n\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));\n}", "project": "OpenSC", "hash": 35692446162590344930620836498368260919, "size": 44, "commit_id": "9d294de90d1cc66956389856e60b6944b27b4817", "message": "prevent out of bounds write\n\nfixes https://oss-fuzz.com/testcase-detail/5226571123392512", "target": 1, "dataset": "other", "idx": 211948}
  898. {"func": "static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)\n{\n\tsc_context_t *ctx;\n\tsc_apdu_t apdu;\n\tu8 rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tu8 sbuf[SC_MAX_APDU_BUFFER_SIZE];\n\ttcos_data *data;\n\tint tcos3, r;\n\n\tassert(card != NULL && crgram != NULL && out != NULL);\n\tctx = card->ctx;\n\ttcos3=(card->type==SC_CARD_TYPE_TCOS_V3);\n\tdata=(tcos_data *)card->drv_data;\n\n\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t\t\"TCOS3:%d PKCS1:%d\\n\",tcos3,\n\t\t!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));\n\n\tsc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = crgram_len;\n\n\tapdu.data = sbuf;\n\tapdu.lc = apdu.datalen = crgram_len+1;\n\tsbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);\n\tif (sizeof sbuf - 1 < crgram_len)\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\tmemcpy(sbuf+1, crgram, crgram_len);\n\n\tr = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(card->ctx, r, \"APDU transmit failed\");\n\n\tif (apdu.sw1==0x90 && apdu.sw2==0x00) {\n\t\tsize_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;\n\t\tunsigned int offset=0;\n\t\tif(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) {\n\t\t\toffset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;\n\t\t\toffset=(offset<len-1) ? offset+1 : 0;\n\t\t}\n\t\tmemcpy(out, apdu.resp+offset, len-offset);\n\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));\n}", "project": "OpenSC", "hash": 135428929269373710791680828572609443287, "size": 46, "commit_id": "9d294de90d1cc66956389856e60b6944b27b4817", "message": "prevent out of bounds write\n\nfixes https://oss-fuzz.com/testcase-detail/5226571123392512", "target": 0, "dataset": "other", "idx": 453691}
  899. {"func": "void luaD_callnoyield (lua_State *L, StkId func, int nResults) {\n incXCcalls(L);\n if (getCcalls(L) <= CSTACKERR) /* possible stack overflow? */\n luaE_freeCI(L);\n luaD_call(L, func, nResults);\n decXCcalls(L);\n}", "project": "lua", "hash": 156964113476265802309004545976693990252, "size": 7, "commit_id": "34affe7a63fc5d842580a9f23616d057e17dfe27", "message": "Fixed bug: 'luaD_callnoyield' called twice in a row\n\nIn luaD_callnoyield, when there is a possible stack overflow, it\nzeros the number of CallInfos to force a check when calling the\nfunction. However, if the \"function\" is not a function, the code will\nraise an error before checking the stack. Then, the error handling calls\nluaD_callnoyield again and nCcalls is decremented again, crossing the\nstack redzone without raising an error. (This loop can only happens\nonce, because the error handler must be a function. But once is enough\nto cross the redzone.)", "target": 1, "dataset": "other", "idx": 211977}
  900. {"func": "void luaD_callnoyield (lua_State *L, StkId func, int nResults) {\n incXCcalls(L);\n if (getCcalls(L) <= CSTACKERR) { /* possible C stack overflow? */\n luaE_exitCcall(L); /* to compensate decrement in next call */\n luaE_enterCcall(L); /* check properly */\n }\n luaD_call(L, func, nResults);\n decXCcalls(L);\n}", "project": "lua", "hash": 284813496960113122553300230525776419698, "size": 9, "commit_id": "34affe7a63fc5d842580a9f23616d057e17dfe27", "message": "Fixed bug: 'luaD_callnoyield' called twice in a row\n\nIn luaD_callnoyield, when there is a possible stack overflow, it\nzeros the number of CallInfos to force a check when calling the\nfunction. However, if the \"function\" is not a function, the code will\nraise an error before checking the stack. Then, the error handling calls\nluaD_callnoyield again and nCcalls is decremented again, crossing the\nstack redzone without raising an error. (This loop can only happens\nonce, because the error handler must be a function. But once is enough\nto cross the redzone.)", "target": 0, "dataset": "other", "idx": 454326}
  901. {"func": "static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,\n int prcno, int lyrno)\n{\n\tjpc_bitstream_t *inb;\n\tjpc_dec_tcomp_t *tcomp;\n\tjpc_dec_rlvl_t *rlvl;\n\tjpc_dec_band_t *band;\n\tjpc_dec_cblk_t *cblk;\n\tint n;\n\tint m;\n\tint i;\n\tjpc_tagtreenode_t *leaf;\n\tint included;\n\tint ret;\n\tint numnewpasses;\n\tjpc_dec_seg_t *seg;\n\tint len;\n\tint present;\n\tint savenumnewpasses;\n\tint mycounter;\n\tjpc_ms_t *ms;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_ccp_t *ccp;\n\tjpc_dec_cp_t *cp;\n\tint bandno;\n\tjpc_dec_prc_t *prc;\n\tint usedcblkcnt;\n\tint cblkno;\n\tuint_fast32_t bodylen;\n\tbool discard;\n\tint passno;\n\tint maxpasses;\n\tint hdrlen;\n\tint hdroffstart;\n\tint hdroffend;\n\n\t/* Avoid compiler warning about possible use of uninitialized\n\t variable. */\n\tbodylen = 0;\n\n\tdiscard = (lyrno >= dec->maxlyrs);\n\n\ttile = dec->curtile;\n\tcp = tile->cp;\n\tccp = &cp->ccps[compno];\n\n\t/*\n\t * Decode the packet header.\n\t */\n\n\t/* Decode the SOP marker segment if present. */\n\tif (cp->csty & JPC_COD_SOP) {\n\t\tif (jpc_dec_lookahead(in) == JPC_MS_SOP) {\n\t\t\tif (!(ms = jpc_getms(in, dec->cstate))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (jpc_ms_gettype(ms) != JPC_MS_SOP) {\n\t\t\t\tjpc_ms_destroy(ms);\n\t\t\t\tjas_eprintf(\"missing SOP marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tjpc_ms_destroy(ms);\n\t\t}\n\t}\n\nhdroffstart = jas_stream_getrwcount(pkthdrstream);\n\n\tif (!(inb = jpc_bitstream_sopen(pkthdrstream, \"r\"))) {\n\t\treturn -1;\n\t}\n\n\tif ((present = jpc_bitstream_getbit(inb)) < 0) {\n\t\tjpc_bitstream_close(inb);\n\t\treturn 1;\n\t}\n\tJAS_DBGLOG(10, (\"\\n\", present));\n\tJAS_DBGLOG(10, (\"present=%d \", present));\n\n\t/* Is the packet non-empty? */\n\tif (present) {\n\t\t/* The packet is non-empty. */\n\t\ttcomp = &tile->tcomps[compno];\n\t\trlvl = &tcomp->rlvls[rlvlno];\n\t\tbodylen = 0;\n\t\tfor (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;\n\t\t ++bandno, ++band) {\n\t\t\tif (!band->data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprc = &band->prcs[prcno];\n\t\t\tif (!prc->cblks) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tusedcblkcnt = 0;\n\t\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t\t ++cblkno, ++cblk) {\n\t\t\t\t++usedcblkcnt;\n\t\t\t\tif (!cblk->numpasses) {\n\t\t\t\t\tleaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);\n\t\t\t\t\tif ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif ((included = jpc_bitstream_getbit(inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tJAS_DBGLOG(10, (\"\\n\"));\n\t\t\t\tJAS_DBGLOG(10, (\"included=%d \", included));\n\t\t\t\tif (!included) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!cblk->numpasses) {\n\t\t\t\t\ti = 1;\n\t\t\t\t\tleaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tif ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {\n\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (ret) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t++i;\n\t\t\t\t\t}\n\t\t\t\t\tcblk->numimsbs = i - 1;\n\t\t\t\t\tcblk->firstpassno = cblk->numimsbs * 3;\n\t\t\t\t}\n\t\t\t\tif ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {\n\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tJAS_DBGLOG(10, (\"numnewpasses=%d \", numnewpasses));\n\t\t\t\tseg = cblk->curseg;\n\t\t\t\tsavenumnewpasses = numnewpasses;\n\t\t\t\tmycounter = 0;\n\t\t\t\tif (numnewpasses > 0) {\n\t\t\t\t\tif ((m = jpc_getcommacode(inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t\tcblk->numlenbits += m;\n\t\t\t\t\tJAS_DBGLOG(10, (\"increment=%d \", m));\n\t\t\t\t\twhile (numnewpasses > 0) {\n\t\t\t\t\t\tpassno = cblk->firstpassno + cblk->numpasses + mycounter;\n\t/* XXX - the maxpasses is not set precisely but this doesn't matter... */\n\t\t\t\t\t\tmaxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0);\n\t\t\t\t\t\tif (!discard && !seg) {\n\t\t\t\t\t\t\tif (!(seg = jpc_seg_alloc())) {\n\t\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);\n\t\t\t\t\t\t\tif (!cblk->curseg) {\n\t\t\t\t\t\t\t\tcblk->curseg = seg;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tseg->passno = passno;\n\t\t\t\t\t\t\tseg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);\n\t\t\t\t\t\t\tseg->maxpasses = maxpasses;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tn = JAS_MIN(numnewpasses, maxpasses);\n\t\t\t\t\t\tmycounter += n;\n\t\t\t\t\t\tnumnewpasses -= n;\n\t\t\t\t\t\tif ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {\n\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tJAS_DBGLOG(10, (\"len=%d \", len));\n\t\t\t\t\t\tif (!discard) {\n\t\t\t\t\t\t\tseg->lyrno = lyrno;\n\t\t\t\t\t\t\tseg->numpasses += n;\n\t\t\t\t\t\t\tseg->cnt = len;\n\t\t\t\t\t\t\tseg = seg->next;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbodylen += len;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcblk->numpasses += savenumnewpasses;\n\t\t\t}\n\t\t}\n\n\t\tjpc_bitstream_inalign(inb, 0, 0);\n\n\t} else {\n\t\tif (jpc_bitstream_inalign(inb, 0x7f, 0)) {\n\t\t\tjas_eprintf(\"alignment failed\\n\");\n\t\t\tjpc_bitstream_close(inb);\n\t\t\treturn -1;\n\t\t}\n\t}\n\tjpc_bitstream_close(inb);\n\n\thdroffend = jas_stream_getrwcount(pkthdrstream);\n\thdrlen = hdroffend - hdroffstart;\n\tif (jas_getdbglevel() >= 5) {\n\t\tjas_eprintf(\"hdrlen=%lu bodylen=%lu \\n\", (unsigned long) hdrlen,\n\t\t (unsigned long) bodylen);\n\t}\n\n\tif (cp->csty & JPC_COD_EPH) {\n\t\tif (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) {\n\t\t\tif (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {\n\t\t\t\tjas_eprintf(\"cannot get (EPH) marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (jpc_ms_gettype(ms) != JPC_MS_EPH) {\n\t\t\t\tjpc_ms_destroy(ms);\n\t\t\t\tjas_eprintf(\"missing EPH marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tjpc_ms_destroy(ms);\n\t\t}\n\t}\n\n\t/* decode the packet body. */\n\n\tif (jas_getdbglevel() >= 1) {\n\t\tjas_eprintf(\"packet body offset=%06ld\\n\", (long) jas_stream_getrwcount(in));\n\t}\n\n\tif (!discard) {\n\t\ttcomp = &tile->tcomps[compno];\n\t\trlvl = &tcomp->rlvls[rlvlno];\n\t\tfor (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;\n\t\t ++bandno, ++band) {\n\t\t\tif (!band->data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprc = &band->prcs[prcno];\n\t\t\tif (!prc->cblks) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t\t ++cblkno, ++cblk) {\n\t\t\t\tseg = cblk->curseg;\n\t\t\t\twhile (seg) {\n\t\t\t\t\tif (!seg->stream) {\n\t\t\t\t\t\tif (!(seg->stream = jas_stream_memopen(0, 0))) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#if 0\njas_eprintf(\"lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\\n\", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);\n#endif\n\t\t\t\t\tif (seg->cnt > 0) {\n\t\t\t\t\t\tif (jpc_getdata(in, seg->stream, seg->cnt) < 0) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tseg->cnt = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (seg->numpasses >= seg->maxpasses) {\n\t\t\t\t\t\tcblk->curseg = seg->next;\n\t\t\t\t\t}\n\t\t\t\t\tseg = seg->next;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\treturn 0;\n}", "project": "jasper", "hash": 116389874333112461743846737970773253172, "size": 266, "commit_id": "c6f9fb6ec7fc97a5c4213f9077faf8622685d160", "message": "jpc_t2dec: work around CVE-2016-9398 by limiting cblk->firstpassno\n\nThis replaces my commit 910c351ff5a80a373c5f0ec19f012e8d52b8b4c9 which\nwas reverted by fc03b57384225055847ec92659e50f95d9ea63f2\n\nCloses https://github.com/jasper-maint/jasper/issues/10", "target": 1, "dataset": "other", "idx": 212027}
  902. {"func": "static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,\n int prcno, int lyrno)\n{\n\tjpc_bitstream_t *inb;\n\tjpc_dec_tcomp_t *tcomp;\n\tjpc_dec_rlvl_t *rlvl;\n\tjpc_dec_band_t *band;\n\tjpc_dec_cblk_t *cblk;\n\tint n;\n\tint m;\n\tint i;\n\tjpc_tagtreenode_t *leaf;\n\tint included;\n\tint ret;\n\tint numnewpasses;\n\tjpc_dec_seg_t *seg;\n\tint len;\n\tint present;\n\tint savenumnewpasses;\n\tint mycounter;\n\tjpc_ms_t *ms;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_ccp_t *ccp;\n\tjpc_dec_cp_t *cp;\n\tint bandno;\n\tjpc_dec_prc_t *prc;\n\tint usedcblkcnt;\n\tint cblkno;\n\tuint_fast32_t bodylen;\n\tbool discard;\n\tint passno;\n\tint maxpasses;\n\tint hdrlen;\n\tint hdroffstart;\n\tint hdroffend;\n\n\t/* Avoid compiler warning about possible use of uninitialized\n\t variable. */\n\tbodylen = 0;\n\n\tdiscard = (lyrno >= dec->maxlyrs);\n\n\ttile = dec->curtile;\n\tcp = tile->cp;\n\tccp = &cp->ccps[compno];\n\n\t/*\n\t * Decode the packet header.\n\t */\n\n\t/* Decode the SOP marker segment if present. */\n\tif (cp->csty & JPC_COD_SOP) {\n\t\tif (jpc_dec_lookahead(in) == JPC_MS_SOP) {\n\t\t\tif (!(ms = jpc_getms(in, dec->cstate))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (jpc_ms_gettype(ms) != JPC_MS_SOP) {\n\t\t\t\tjpc_ms_destroy(ms);\n\t\t\t\tjas_eprintf(\"missing SOP marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tjpc_ms_destroy(ms);\n\t\t}\n\t}\n\nhdroffstart = jas_stream_getrwcount(pkthdrstream);\n\n\tif (!(inb = jpc_bitstream_sopen(pkthdrstream, \"r\"))) {\n\t\treturn -1;\n\t}\n\n\tif ((present = jpc_bitstream_getbit(inb)) < 0) {\n\t\tjpc_bitstream_close(inb);\n\t\treturn 1;\n\t}\n\tJAS_DBGLOG(10, (\"\\n\", present));\n\tJAS_DBGLOG(10, (\"present=%d \", present));\n\n\t/* Is the packet non-empty? */\n\tif (present) {\n\t\t/* The packet is non-empty. */\n\t\ttcomp = &tile->tcomps[compno];\n\t\trlvl = &tcomp->rlvls[rlvlno];\n\t\tbodylen = 0;\n\t\tfor (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;\n\t\t ++bandno, ++band) {\n\t\t\tif (!band->data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprc = &band->prcs[prcno];\n\t\t\tif (!prc->cblks) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tusedcblkcnt = 0;\n\t\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t\t ++cblkno, ++cblk) {\n\t\t\t\t++usedcblkcnt;\n\t\t\t\tif (!cblk->numpasses) {\n\t\t\t\t\tleaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);\n\t\t\t\t\tif ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif ((included = jpc_bitstream_getbit(inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tJAS_DBGLOG(10, (\"\\n\"));\n\t\t\t\tJAS_DBGLOG(10, (\"included=%d \", included));\n\t\t\t\tif (!included) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!cblk->numpasses) {\n\t\t\t\t\ti = 1;\n\t\t\t\t\tleaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tif ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {\n\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (ret) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t++i;\n\t\t\t\t\t}\n\t\t\t\t\tcblk->numimsbs = i - 1;\n\t\t\t\t\tcblk->firstpassno = cblk->numimsbs * 3;\n\t\t\t\t}\n\t\t\t\tif ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {\n\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tJAS_DBGLOG(10, (\"numnewpasses=%d \", numnewpasses));\n\t\t\t\tseg = cblk->curseg;\n\t\t\t\tsavenumnewpasses = numnewpasses;\n\t\t\t\tmycounter = 0;\n\t\t\t\tif (numnewpasses > 0) {\n\t\t\t\t\tif (cblk->firstpassno > 10000) {\n\t\t\t\t\t\t/* workaround for\n\t\t\t\t\t\t CVE-2016-9398: this\n\t\t\t\t\t\t large value would\n\t\t\t\t\t\t make\n\t\t\t\t\t\t JPC_SEGPASSCNT()\n\t\t\t\t\t\t return a negative\n\t\t\t\t\t\t value, causing an\n\t\t\t\t\t\t assertion failure\n\t\t\t\t\t\t in\n\t\t\t\t\t\t jpc_floorlog2() */\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t\tif ((m = jpc_getcommacode(inb)) < 0) {\n\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t\tcblk->numlenbits += m;\n\t\t\t\t\tJAS_DBGLOG(10, (\"increment=%d \", m));\n\t\t\t\t\twhile (numnewpasses > 0) {\n\t\t\t\t\t\tpassno = cblk->firstpassno + cblk->numpasses + mycounter;\n\t/* XXX - the maxpasses is not set precisely but this doesn't matter... */\n\t\t\t\t\t\tmaxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0);\n\t\t\t\t\t\tif (!discard && !seg) {\n\t\t\t\t\t\t\tif (!(seg = jpc_seg_alloc())) {\n\t\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);\n\t\t\t\t\t\t\tif (!cblk->curseg) {\n\t\t\t\t\t\t\t\tcblk->curseg = seg;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tseg->passno = passno;\n\t\t\t\t\t\t\tseg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);\n\t\t\t\t\t\t\tseg->maxpasses = maxpasses;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tn = JAS_MIN(numnewpasses, maxpasses);\n\t\t\t\t\t\tmycounter += n;\n\t\t\t\t\t\tnumnewpasses -= n;\n\t\t\t\t\t\tif ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {\n\t\t\t\t\t\t\tjpc_bitstream_close(inb);\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tJAS_DBGLOG(10, (\"len=%d \", len));\n\t\t\t\t\t\tif (!discard) {\n\t\t\t\t\t\t\tseg->lyrno = lyrno;\n\t\t\t\t\t\t\tseg->numpasses += n;\n\t\t\t\t\t\t\tseg->cnt = len;\n\t\t\t\t\t\t\tseg = seg->next;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbodylen += len;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcblk->numpasses += savenumnewpasses;\n\t\t\t}\n\t\t}\n\n\t\tjpc_bitstream_inalign(inb, 0, 0);\n\n\t} else {\n\t\tif (jpc_bitstream_inalign(inb, 0x7f, 0)) {\n\t\t\tjas_eprintf(\"alignment failed\\n\");\n\t\t\tjpc_bitstream_close(inb);\n\t\t\treturn -1;\n\t\t}\n\t}\n\tjpc_bitstream_close(inb);\n\n\thdroffend = jas_stream_getrwcount(pkthdrstream);\n\thdrlen = hdroffend - hdroffstart;\n\tif (jas_getdbglevel() >= 5) {\n\t\tjas_eprintf(\"hdrlen=%lu bodylen=%lu \\n\", (unsigned long) hdrlen,\n\t\t (unsigned long) bodylen);\n\t}\n\n\tif (cp->csty & JPC_COD_EPH) {\n\t\tif (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) {\n\t\t\tif (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {\n\t\t\t\tjas_eprintf(\"cannot get (EPH) marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (jpc_ms_gettype(ms) != JPC_MS_EPH) {\n\t\t\t\tjpc_ms_destroy(ms);\n\t\t\t\tjas_eprintf(\"missing EPH marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tjpc_ms_destroy(ms);\n\t\t}\n\t}\n\n\t/* decode the packet body. */\n\n\tif (jas_getdbglevel() >= 1) {\n\t\tjas_eprintf(\"packet body offset=%06ld\\n\", (long) jas_stream_getrwcount(in));\n\t}\n\n\tif (!discard) {\n\t\ttcomp = &tile->tcomps[compno];\n\t\trlvl = &tcomp->rlvls[rlvlno];\n\t\tfor (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;\n\t\t ++bandno, ++band) {\n\t\t\tif (!band->data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprc = &band->prcs[prcno];\n\t\t\tif (!prc->cblks) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t\t ++cblkno, ++cblk) {\n\t\t\t\tseg = cblk->curseg;\n\t\t\t\twhile (seg) {\n\t\t\t\t\tif (!seg->stream) {\n\t\t\t\t\t\tif (!(seg->stream = jas_stream_memopen(0, 0))) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#if 0\njas_eprintf(\"lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\\n\", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);\n#endif\n\t\t\t\t\tif (seg->cnt > 0) {\n\t\t\t\t\t\tif (jpc_getdata(in, seg->stream, seg->cnt) < 0) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tseg->cnt = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (seg->numpasses >= seg->maxpasses) {\n\t\t\t\t\t\tcblk->curseg = seg->next;\n\t\t\t\t\t}\n\t\t\t\t\tseg = seg->next;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\treturn 0;\n}", "project": "jasper", "hash": 29552345775717961382863408064126086670, "size": 280, "commit_id": "c6f9fb6ec7fc97a5c4213f9077faf8622685d160", "message": "jpc_t2dec: work around CVE-2016-9398 by limiting cblk->firstpassno\n\nThis replaces my commit 910c351ff5a80a373c5f0ec19f012e8d52b8b4c9 which\nwas reverted by fc03b57384225055847ec92659e50f95d9ea63f2\n\nCloses https://github.com/jasper-maint/jasper/issues/10", "target": 0, "dataset": "other", "idx": 454553}
  903. {"func": "wsrep_cb_status_t wsrep_sst_donate_cb (void* app_ctx, void* recv_ctx,\n const void* msg, size_t msg_len,\n const wsrep_gtid_t* current_gtid,\n const char* state, size_t state_len,\n bool bypass)\n{\n /* This will be reset when sync callback is called.\n * Should we set wsrep_ready to FALSE here too? */\n local_status.set(WSREP_MEMBER_DONOR);\n\n const char* method = (char*)msg;\n size_t method_len = strlen (method);\n const char* data = method + method_len + 1;\n\n char uuid_str[37];\n wsrep_uuid_print (&current_gtid->uuid, uuid_str, sizeof(uuid_str));\n\n wsp::env env(NULL);\n if (env.error())\n {\n WSREP_ERROR(\"wsrep_sst_donate_cb(): env var ctor failed: %d\", -env.error());\n return WSREP_CB_FAILURE;\n }\n\n int ret;\n if ((ret= sst_append_auth_env(env, sst_auth_real)))\n {\n WSREP_ERROR(\"wsrep_sst_donate_cb(): appending auth env failed: %d\", ret);\n return WSREP_CB_FAILURE;\n }\n\n if (!strcmp (WSREP_SST_MYSQLDUMP, method))\n {\n ret = sst_donate_mysqldump(data, &current_gtid->uuid, uuid_str,\n current_gtid->seqno, bypass, env());\n }\n else\n {\n ret = sst_donate_other(method, data, uuid_str,\n current_gtid->seqno, bypass, env());\n }\n\n return (ret >= 0 ? WSREP_CB_SUCCESS : WSREP_CB_FAILURE);\n}", "project": "mysql-wsrep", "hash": 340163712951592193597010920393388964257, "size": 44, "commit_id": "4ea4b0c6a318209ac09b15aaa906c7b4a13b988c", "message": "codership/mysql-wsrep-bugs#758 Donor uses invalid SST methods", "target": 1, "dataset": "other", "idx": 212088}
  904. {"func": "wsrep_cb_status_t wsrep_sst_donate_cb (void* app_ctx, void* recv_ctx,\n const void* msg, size_t msg_len,\n const wsrep_gtid_t* current_gtid,\n const char* state, size_t state_len,\n bool bypass)\n{\n const char* method = (char*)msg;\n size_t method_len = strlen (method);\n\n if (check_request_str(method, filename_char))\n {\n WSREP_ERROR(\"Bad SST method name. SST canceled.\");\n return WSREP_CB_FAILURE;\n }\n\n const char* data = method + method_len + 1;\n\n if (check_request_str(data, address_char))\n {\n WSREP_ERROR(\"Bad SST address string. SST canceled.\");\n return WSREP_CB_FAILURE;\n }\n\n char uuid_str[37];\n wsrep_uuid_print (&current_gtid->uuid, uuid_str, sizeof(uuid_str));\n\n /* This will be reset when sync callback is called.\n * Should we set wsrep_ready to FALSE here too? */\n local_status.set(WSREP_MEMBER_DONOR);\n\n wsp::env env(NULL);\n if (env.error())\n {\n WSREP_ERROR(\"wsrep_sst_donate_cb(): env var ctor failed: %d\", -env.error());\n return WSREP_CB_FAILURE;\n }\n\n int ret;\n if ((ret= sst_append_auth_env(env, sst_auth_real)))\n {\n WSREP_ERROR(\"wsrep_sst_donate_cb(): appending auth env failed: %d\", ret);\n return WSREP_CB_FAILURE;\n }\n\n if (!strcmp (WSREP_SST_MYSQLDUMP, method))\n {\n ret = sst_donate_mysqldump(data, &current_gtid->uuid, uuid_str,\n current_gtid->seqno, bypass, env());\n }\n else\n {\n ret = sst_donate_other(method, data, uuid_str,\n current_gtid->seqno, bypass, env());\n }\n\n return (ret >= 0 ? WSREP_CB_SUCCESS : WSREP_CB_FAILURE);\n}", "project": "mysql-wsrep", "hash": 250096512772440836164701665139796929193, "size": 57, "commit_id": "4ea4b0c6a318209ac09b15aaa906c7b4a13b988c", "message": "codership/mysql-wsrep-bugs#758 Donor uses invalid SST methods", "target": 0, "dataset": "other", "idx": 454781}
  905. {"func": "FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], uint32_t nvals, uint32_t parameter)\n{\n\t/* try and get br->consumed_words and br->consumed_bits into register;\n\t * must remember to flush them back to *br before calling other\n\t * bitreader functions that use them, and before returning */\n\tuint32_t cwords, words, lsbs, msbs, x, y;\n\tuint32_t ucbits; /* keep track of the number of unconsumed bits in word */\n\tbrword b;\n\tint *val, *end;\n\n\tFLAC__ASSERT(0 != br);\n\tFLAC__ASSERT(0 != br->buffer);\n\t/* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */\n\tFLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);\n\tFLAC__ASSERT(parameter < 32);\n\t/* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */\n\n\tval = vals;\n\tend = vals + nvals;\n\n\tif(parameter == 0) {\n\t\twhile(val < end) {\n\t\t\t/* read the unary MSBs and end bit */\n\t\t\tif(!FLAC__bitreader_read_unary_unsigned(br, &msbs))\n\t\t\t\treturn false;\n\n\t\t\t*val++ = (int)(msbs >> 1) ^ -(int)(msbs & 1);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tFLAC__ASSERT(parameter > 0);\n\n\tcwords = br->consumed_words;\n\twords = br->words;\n\n\t/* if we've not consumed up to a partial tail word... */\n\tif(cwords >= words) {\n\t\tx = 0;\n\t\tgoto process_tail;\n\t}\n\n\tucbits = FLAC__BITS_PER_WORD - br->consumed_bits;\n\tb = br->buffer[cwords] << br->consumed_bits; /* keep unconsumed bits aligned to left */\n\n\twhile(val < end) {\n\t\t/* read the unary MSBs and end bit */\n\t\tx = y = COUNT_ZERO_MSBS2(b);\n\t\tif(x == FLAC__BITS_PER_WORD) {\n\t\t\tx = ucbits;\n\t\t\tdo {\n\t\t\t\t/* didn't find stop bit yet, have to keep going... */\n\t\t\t\tcwords++;\n\t\t\t\tif (cwords >= words)\n\t\t\t\t\tgoto incomplete_msbs;\n\t\t\t\tb = br->buffer[cwords];\n\t\t\t\ty = COUNT_ZERO_MSBS2(b);\n\t\t\t\tx += y;\n\t\t\t} while(y == FLAC__BITS_PER_WORD);\n\t\t}\n\t\tb <<= y;\n\t\tb <<= 1; /* account for stop bit */\n\t\tucbits = (ucbits - x - 1) % FLAC__BITS_PER_WORD;\n\t\tmsbs = x;\n\n\t\t/* read the binary LSBs */\n\t\tx = (FLAC__uint32)(b >> (FLAC__BITS_PER_WORD - parameter)); /* parameter < 32, so we can cast to 32-bit uint32_t */\n\t\tif(parameter <= ucbits) {\n\t\t\tucbits -= parameter;\n\t\t\tb <<= parameter;\n\t\t} else {\n\t\t\t/* there are still bits left to read, they will all be in the next word */\n\t\t\tcwords++;\n\t\t\tif (cwords >= words)\n\t\t\t\tgoto incomplete_lsbs;\n\t\t\tb = br->buffer[cwords];\n\t\t\tucbits += FLAC__BITS_PER_WORD - parameter;\n\t\t\tx |= (FLAC__uint32)(b >> ucbits);\n\t\t\tb <<= FLAC__BITS_PER_WORD - ucbits;\n\t\t}\n\t\tlsbs = x;\n\n\t\t/* compose the value */\n\t\tx = (msbs << parameter) | lsbs;\n\t\t*val++ = (int)(x >> 1) ^ -(int)(x & 1);\n\n\t\tcontinue;\n\n\t\t/* at this point we've eaten up all the whole words */\nprocess_tail:\n\t\tdo {\n\t\t\tif(0) {\nincomplete_msbs:\n\t\t\t\tbr->consumed_bits = 0;\n\t\t\t\tbr->consumed_words = cwords;\n\t\t\t}\n\n\t\t\t/* read the unary MSBs and end bit */\n\t\t\tif(!FLAC__bitreader_read_unary_unsigned(br, &msbs))\n\t\t\t\treturn false;\n\t\t\tmsbs += x;\n\t\t\tx = ucbits = 0;\n\n\t\t\tif(0) {\nincomplete_lsbs:\n\t\t\t\tbr->consumed_bits = 0;\n\t\t\t\tbr->consumed_words = cwords;\n\t\t\t}\n\n\t\t\t/* read the binary LSBs */\n\t\t\tif(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter - ucbits))\n\t\t\t\treturn false;\n\t\t\tlsbs = x | lsbs;\n\n\t\t\t/* compose the value */\n\t\t\tx = (msbs << parameter) | lsbs;\n\t\t\t*val++ = (int)(x >> 1) ^ -(int)(x & 1);\n\t\t\tx = 0;\n\n\t\t\tcwords = br->consumed_words;\n\t\t\twords = br->words;\n\t\t\tucbits = FLAC__BITS_PER_WORD - br->consumed_bits;\n\t\t\tb = br->buffer[cwords] << br->consumed_bits;\n\t\t} while(cwords >= words && val < end);\n\t}\n\n\tif(ucbits == 0 && cwords < words) {\n\t\t/* don't leave the head word with no unconsumed bits */\n\t\tcwords++;\n\t\tucbits = FLAC__BITS_PER_WORD;\n\t}\n\n\tbr->consumed_bits = FLAC__BITS_PER_WORD - ucbits;\n\tbr->consumed_words = cwords;\n\n\treturn true;\n}", "project": "flac", "hash": 173788847374942133534558930292688196794, "size": 138, "commit_id": "2e7931c27eb15e387da440a37f12437e35b22dd4", "message": "libFLAC/bitreader.c: Fix out-of-bounds read\n\nCredit: Oss-Fuzz\nIssue: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=17069\nTestcase: fuzzer_decoder-5670265022840832", "target": 1, "dataset": "other", "idx": 212139}
  906. {"func": "FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], uint32_t nvals, uint32_t parameter)\n{\n\t/* try and get br->consumed_words and br->consumed_bits into register;\n\t * must remember to flush them back to *br before calling other\n\t * bitreader functions that use them, and before returning */\n\tuint32_t cwords, words, lsbs, msbs, x, y;\n\tuint32_t ucbits; /* keep track of the number of unconsumed bits in word */\n\tbrword b;\n\tint *val, *end;\n\n\tFLAC__ASSERT(0 != br);\n\tFLAC__ASSERT(0 != br->buffer);\n\t/* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */\n\tFLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);\n\tFLAC__ASSERT(parameter < 32);\n\t/* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */\n\n\tval = vals;\n\tend = vals + nvals;\n\n\tif(parameter == 0) {\n\t\twhile(val < end) {\n\t\t\t/* read the unary MSBs and end bit */\n\t\t\tif(!FLAC__bitreader_read_unary_unsigned(br, &msbs))\n\t\t\t\treturn false;\n\n\t\t\t*val++ = (int)(msbs >> 1) ^ -(int)(msbs & 1);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tFLAC__ASSERT(parameter > 0);\n\n\tcwords = br->consumed_words;\n\twords = br->words;\n\n\t/* if we've not consumed up to a partial tail word... */\n\tif(cwords >= words) {\n\t\tx = 0;\n\t\tgoto process_tail;\n\t}\n\n\tucbits = FLAC__BITS_PER_WORD - br->consumed_bits;\n\tb = br->buffer[cwords] << br->consumed_bits; /* keep unconsumed bits aligned to left */\n\n\twhile(val < end) {\n\t\t/* read the unary MSBs and end bit */\n\t\tx = y = COUNT_ZERO_MSBS2(b);\n\t\tif(x == FLAC__BITS_PER_WORD) {\n\t\t\tx = ucbits;\n\t\t\tdo {\n\t\t\t\t/* didn't find stop bit yet, have to keep going... */\n\t\t\t\tcwords++;\n\t\t\t\tif (cwords >= words)\n\t\t\t\t\tgoto incomplete_msbs;\n\t\t\t\tb = br->buffer[cwords];\n\t\t\t\ty = COUNT_ZERO_MSBS2(b);\n\t\t\t\tx += y;\n\t\t\t} while(y == FLAC__BITS_PER_WORD);\n\t\t}\n\t\tb <<= y;\n\t\tb <<= 1; /* account for stop bit */\n\t\tucbits = (ucbits - x - 1) % FLAC__BITS_PER_WORD;\n\t\tmsbs = x;\n\n\t\t/* read the binary LSBs */\n\t\tx = (FLAC__uint32)(b >> (FLAC__BITS_PER_WORD - parameter)); /* parameter < 32, so we can cast to 32-bit uint32_t */\n\t\tif(parameter <= ucbits) {\n\t\t\tucbits -= parameter;\n\t\t\tb <<= parameter;\n\t\t} else {\n\t\t\t/* there are still bits left to read, they will all be in the next word */\n\t\t\tcwords++;\n\t\t\tif (cwords >= words)\n\t\t\t\tgoto incomplete_lsbs;\n\t\t\tb = br->buffer[cwords];\n\t\t\tucbits += FLAC__BITS_PER_WORD - parameter;\n\t\t\tx |= (FLAC__uint32)(b >> ucbits);\n\t\t\tb <<= FLAC__BITS_PER_WORD - ucbits;\n\t\t}\n\t\tlsbs = x;\n\n\t\t/* compose the value */\n\t\tx = (msbs << parameter) | lsbs;\n\t\t*val++ = (int)(x >> 1) ^ -(int)(x & 1);\n\n\t\tcontinue;\n\n\t\t/* at this point we've eaten up all the whole words */\nprocess_tail:\n\t\tdo {\n\t\t\tif(0) {\nincomplete_msbs:\n\t\t\t\tbr->consumed_bits = 0;\n\t\t\t\tbr->consumed_words = cwords;\n\t\t\t}\n\n\t\t\t/* read the unary MSBs and end bit */\n\t\t\tif(!FLAC__bitreader_read_unary_unsigned(br, &msbs))\n\t\t\t\treturn false;\n\t\t\tmsbs += x;\n\t\t\tx = ucbits = 0;\n\n\t\t\tif(0) {\nincomplete_lsbs:\n\t\t\t\tbr->consumed_bits = 0;\n\t\t\t\tbr->consumed_words = cwords;\n\t\t\t}\n\n\t\t\t/* read the binary LSBs */\n\t\t\tif(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter - ucbits))\n\t\t\t\treturn false;\n\t\t\tlsbs = x | lsbs;\n\n\t\t\t/* compose the value */\n\t\t\tx = (msbs << parameter) | lsbs;\n\t\t\t*val++ = (int)(x >> 1) ^ -(int)(x & 1);\n\t\t\tx = 0;\n\n\t\t\tcwords = br->consumed_words;\n\t\t\twords = br->words;\n\t\t\tucbits = FLAC__BITS_PER_WORD - br->consumed_bits;\n\t\t\tb = cwords < br->capacity ? br->buffer[cwords] << br->consumed_bits : 0;\n\t\t} while(cwords >= words && val < end);\n\t}\n\n\tif(ucbits == 0 && cwords < words) {\n\t\t/* don't leave the head word with no unconsumed bits */\n\t\tcwords++;\n\t\tucbits = FLAC__BITS_PER_WORD;\n\t}\n\n\tbr->consumed_bits = FLAC__BITS_PER_WORD - ucbits;\n\tbr->consumed_words = cwords;\n\n\treturn true;\n}", "project": "flac", "hash": 72624132530208831275896369357681622282, "size": 138, "commit_id": "2e7931c27eb15e387da440a37f12437e35b22dd4", "message": "libFLAC/bitreader.c: Fix out-of-bounds read\n\nCredit: Oss-Fuzz\nIssue: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=17069\nTestcase: fuzzer_decoder-5670265022840832", "target": 0, "dataset": "other", "idx": 455064}
  907. {"func": "PasswordProcess (\r\n IN UI_MENU_OPTION *MenuOption\r\n )\r\n{\r\n CHAR16 *StringPtr;\r\n CHAR16 *TempString;\r\n UINTN Maximum;\r\n EFI_STATUS Status;\r\n EFI_IFR_PASSWORD *PasswordInfo;\r\n FORM_DISPLAY_ENGINE_STATEMENT *Question;\r\n EFI_INPUT_KEY Key;\r\n\r\n Question = MenuOption->ThisTag;\r\n PasswordInfo = (EFI_IFR_PASSWORD *) Question->OpCode;\r\n Maximum = PasswordInfo->MaxSize;\r\n Status = EFI_SUCCESS;\r\n\r\n StringPtr = AllocateZeroPool ((Maximum + 1) * sizeof (CHAR16));\r\n ASSERT (StringPtr);\r\n\r\n //\r\n // Use a NULL password to test whether old password is required\r\n //\r\n *StringPtr = 0;\r\n Status = Question->PasswordCheck (gFormData, Question, StringPtr);\r\n if (Status == EFI_NOT_AVAILABLE_YET || Status == EFI_UNSUPPORTED) {\r\n //\r\n // Password can't be set now.\r\n //\r\n if (Status == EFI_UNSUPPORTED) {\r\n do {\r\n CreateDialog (&Key, gEmptyString, gPasswordUnsupported, gPressEnter, gEmptyString, NULL);\r\n } while (Key.UnicodeChar != CHAR_CARRIAGE_RETURN);\r\n }\r\n FreePool (StringPtr);\r\n return EFI_SUCCESS;\r\n }\r\n\r\n if (EFI_ERROR (Status)) {\r\n //\r\n // Old password exist, ask user for the old password\r\n //\r\n Status = ReadString (MenuOption, gPromptForPassword, StringPtr);\r\n if (EFI_ERROR (Status)) {\r\n FreePool (StringPtr);\r\n return Status;\r\n }\r\n\r\n //\r\n // Check user input old password\r\n //\r\n Status = Question->PasswordCheck (gFormData, Question, StringPtr);\r\n if (EFI_ERROR (Status)) {\r\n if (Status == EFI_NOT_READY) {\r\n //\r\n // Typed in old password incorrect\r\n //\r\n PasswordInvalid ();\r\n } else {\r\n Status = EFI_SUCCESS;\r\n }\r\n\r\n FreePool (StringPtr);\r\n return Status;\r\n }\r\n }\r\n\r\n //\r\n // Ask for new password\r\n //\r\n ZeroMem (StringPtr, (Maximum + 1) * sizeof (CHAR16));\r\n Status = ReadString (MenuOption, gPromptForNewPassword, StringPtr);\r\n if (EFI_ERROR (Status)) {\r\n //\r\n // Reset state machine for password\r\n //\r\n Question->PasswordCheck (gFormData, Question, NULL);\r\n FreePool (StringPtr);\r\n return Status;\r\n }\r\n\r\n //\r\n // Confirm new password\r\n //\r\n TempString = AllocateZeroPool ((Maximum + 1) * sizeof (CHAR16));\r\n ASSERT (TempString);\r\n Status = ReadString (MenuOption, gConfirmPassword, TempString);\r\n if (EFI_ERROR (Status)) {\r\n //\r\n // Reset state machine for password\r\n //\r\n Question->PasswordCheck (gFormData, Question, NULL);\r\n FreePool (StringPtr);\r\n FreePool (TempString);\r\n return Status;\r\n }\r\n\r\n //\r\n // Compare two typed-in new passwords\r\n //\r\n if (StrCmp (StringPtr, TempString) == 0) {\r\n gUserInput->InputValue.Buffer = AllocateCopyPool (Question->CurrentValue.BufferLen, StringPtr);\r\n gUserInput->InputValue.BufferLen = Question->CurrentValue.BufferLen;\r\n gUserInput->InputValue.Type = Question->CurrentValue.Type;\r\n gUserInput->InputValue.Value.string = HiiSetString(gFormData->HiiHandle, gUserInput->InputValue.Value.string, StringPtr, NULL);\r\n\r\n Status = EFI_SUCCESS;\r\n } else {\r\n //\r\n // Reset state machine for password\r\n //\r\n Question->PasswordCheck (gFormData, Question, NULL);\r\n\r\n //\r\n // Two password mismatch, prompt error message\r\n //\r\n do {\r\n CreateDialog (&Key, gEmptyString, gConfirmError, gPressEnter, gEmptyString, NULL);\r\n } while (Key.UnicodeChar != CHAR_CARRIAGE_RETURN);\r\n\r\n Status = EFI_INVALID_PARAMETER;\r\n }\r\n ZeroMem (TempString, (Maximum + 1) * sizeof (CHAR16));\r\n ZeroMem (StringPtr, (Maximum + 1) * sizeof (CHAR16));\r\n FreePool (TempString);\r\n FreePool (StringPtr);\r\n\r\n return Status;\r\n}\r", "project": "edk2", "hash": 165118359344339716147785903103604284716, "size": 129, "commit_id": "f1d78c489a39971b5aac5d2fc8a39bfa925c3c5d", "message": "MdeModulePkg/DisplayEngine: Zero memory before free (CVE-2019-14558)\n\nREF: https://bugzilla.tianocore.org/show_bug.cgi?id=1611\n\nCc: Liming Gao <liming.gao@intel.com>\nCc: Eric Dong <eric.dong@intel.com>\nCc: Jian J Wang <jian.j.wang@intel.com>\nSigned-off-by: Dandan Bi <dandan.bi@intel.com>\nReviewed-by: Eric Dong <eric.dong@intel.com>\nReviewed-by: Jian J Wang <jian.j.wang@intel.com>", "target": 1, "dataset": "other", "idx": 212150}
  908. {"func": "PasswordProcess (\r\n IN UI_MENU_OPTION *MenuOption\r\n )\r\n{\r\n CHAR16 *StringPtr;\r\n CHAR16 *TempString;\r\n UINTN Maximum;\r\n EFI_STATUS Status;\r\n EFI_IFR_PASSWORD *PasswordInfo;\r\n FORM_DISPLAY_ENGINE_STATEMENT *Question;\r\n EFI_INPUT_KEY Key;\r\n\r\n Question = MenuOption->ThisTag;\r\n PasswordInfo = (EFI_IFR_PASSWORD *) Question->OpCode;\r\n Maximum = PasswordInfo->MaxSize;\r\n Status = EFI_SUCCESS;\r\n\r\n StringPtr = AllocateZeroPool ((Maximum + 1) * sizeof (CHAR16));\r\n ASSERT (StringPtr);\r\n\r\n //\r\n // Use a NULL password to test whether old password is required\r\n //\r\n *StringPtr = 0;\r\n Status = Question->PasswordCheck (gFormData, Question, StringPtr);\r\n if (Status == EFI_NOT_AVAILABLE_YET || Status == EFI_UNSUPPORTED) {\r\n //\r\n // Password can't be set now.\r\n //\r\n if (Status == EFI_UNSUPPORTED) {\r\n do {\r\n CreateDialog (&Key, gEmptyString, gPasswordUnsupported, gPressEnter, gEmptyString, NULL);\r\n } while (Key.UnicodeChar != CHAR_CARRIAGE_RETURN);\r\n }\r\n FreePool (StringPtr);\r\n return EFI_SUCCESS;\r\n }\r\n\r\n if (EFI_ERROR (Status)) {\r\n //\r\n // Old password exist, ask user for the old password\r\n //\r\n Status = ReadString (MenuOption, gPromptForPassword, StringPtr);\r\n if (EFI_ERROR (Status)) {\r\n ZeroMem (StringPtr, (Maximum + 1) * sizeof (CHAR16));\r\n FreePool (StringPtr);\r\n return Status;\r\n }\r\n\r\n //\r\n // Check user input old password\r\n //\r\n Status = Question->PasswordCheck (gFormData, Question, StringPtr);\r\n if (EFI_ERROR (Status)) {\r\n if (Status == EFI_NOT_READY) {\r\n //\r\n // Typed in old password incorrect\r\n //\r\n PasswordInvalid ();\r\n } else {\r\n Status = EFI_SUCCESS;\r\n }\r\n ZeroMem (StringPtr, (Maximum + 1) * sizeof (CHAR16));\r\n FreePool (StringPtr);\r\n return Status;\r\n }\r\n }\r\n\r\n //\r\n // Ask for new password\r\n //\r\n ZeroMem (StringPtr, (Maximum + 1) * sizeof (CHAR16));\r\n Status = ReadString (MenuOption, gPromptForNewPassword, StringPtr);\r\n if (EFI_ERROR (Status)) {\r\n //\r\n // Reset state machine for password\r\n //\r\n Question->PasswordCheck (gFormData, Question, NULL);\r\n ZeroMem (StringPtr, (Maximum + 1) * sizeof (CHAR16));\r\n FreePool (StringPtr);\r\n return Status;\r\n }\r\n\r\n //\r\n // Confirm new password\r\n //\r\n TempString = AllocateZeroPool ((Maximum + 1) * sizeof (CHAR16));\r\n ASSERT (TempString);\r\n Status = ReadString (MenuOption, gConfirmPassword, TempString);\r\n if (EFI_ERROR (Status)) {\r\n //\r\n // Reset state machine for password\r\n //\r\n Question->PasswordCheck (gFormData, Question, NULL);\r\n ZeroMem (StringPtr, (Maximum + 1) * sizeof (CHAR16));\r\n ZeroMem (TempString, (Maximum + 1) * sizeof (CHAR16));\r\n FreePool (StringPtr);\r\n FreePool (TempString);\r\n return Status;\r\n }\r\n\r\n //\r\n // Compare two typed-in new passwords\r\n //\r\n if (StrCmp (StringPtr, TempString) == 0) {\r\n gUserInput->InputValue.Buffer = AllocateCopyPool (Question->CurrentValue.BufferLen, StringPtr);\r\n gUserInput->InputValue.BufferLen = Question->CurrentValue.BufferLen;\r\n gUserInput->InputValue.Type = Question->CurrentValue.Type;\r\n gUserInput->InputValue.Value.string = HiiSetString(gFormData->HiiHandle, gUserInput->InputValue.Value.string, StringPtr, NULL);\r\n\r\n Status = EFI_SUCCESS;\r\n } else {\r\n //\r\n // Reset state machine for password\r\n //\r\n Question->PasswordCheck (gFormData, Question, NULL);\r\n\r\n //\r\n // Two password mismatch, prompt error message\r\n //\r\n do {\r\n CreateDialog (&Key, gEmptyString, gConfirmError, gPressEnter, gEmptyString, NULL);\r\n } while (Key.UnicodeChar != CHAR_CARRIAGE_RETURN);\r\n\r\n Status = EFI_INVALID_PARAMETER;\r\n }\r\n ZeroMem (TempString, (Maximum + 1) * sizeof (CHAR16));\r\n ZeroMem (StringPtr, (Maximum + 1) * sizeof (CHAR16));\r\n FreePool (TempString);\r\n FreePool (StringPtr);\r\n\r\n return Status;\r\n}\r", "project": "edk2", "hash": 248666332326382694389399302001879066678, "size": 133, "commit_id": "f1d78c489a39971b5aac5d2fc8a39bfa925c3c5d", "message": "MdeModulePkg/DisplayEngine: Zero memory before free (CVE-2019-14558)\n\nREF: https://bugzilla.tianocore.org/show_bug.cgi?id=1611\n\nCc: Liming Gao <liming.gao@intel.com>\nCc: Eric Dong <eric.dong@intel.com>\nCc: Jian J Wang <jian.j.wang@intel.com>\nSigned-off-by: Dandan Bi <dandan.bi@intel.com>\nReviewed-by: Eric Dong <eric.dong@intel.com>\nReviewed-by: Jian J Wang <jian.j.wang@intel.com>", "target": 0, "dataset": "other", "idx": 455272}
  909. {"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 calling 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 addReplyErrorObject(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": 176537741763154451900906839244155850569, "size": 211, "commit_id": "92e3b1802f72ca0c5b0bde97f01d9b57a758d85c", "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": 212155}
  910. {"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 calling 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 addReplyErrorObject(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": 315646448376140942479893639791006565820, "size": 211, "commit_id": "92e3b1802f72ca0c5b0bde97f01d9b57a758d85c", "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": 455379}
  911. {"func": "int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs,\n\t\t\t\t\t off_t bl_len)\n{\n const char *content_type = NULL;\n string content_type_str;\n map<string, string> response_attrs;\n map<string, string>::iterator riter;\n bufferlist metadata_bl;\n\n if (sent_header)\n goto send_data;\n\n if (custom_http_ret) {\n set_req_state_err(s, 0);\n dump_errno(s, custom_http_ret);\n } else {\n set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT\n : op_ret);\n dump_errno(s);\n }\n\n if (op_ret)\n goto done;\n\n if (range_str)\n dump_range(s, start, end, s->obj_size);\n\n if (s->system_request &&\n s->info.args.exists(RGW_SYS_PARAM_PREFIX \"prepend-metadata\")) {\n\n dump_header(s, \"Rgwx-Object-Size\", (long long)total_len);\n\n if (rgwx_stat) {\n /*\n * in this case, we're not returning the object's content, only the prepended\n * extra metadata\n */\n total_len = 0;\n }\n\n /* JSON encode object metadata */\n JSONFormatter jf;\n jf.open_object_section(\"obj_metadata\");\n encode_json(\"attrs\", attrs, &jf);\n utime_t ut(lastmod);\n encode_json(\"mtime\", ut, &jf);\n jf.close_section();\n stringstream ss;\n jf.flush(ss);\n metadata_bl.append(ss.str());\n dump_header(s, \"Rgwx-Embedded-Metadata-Len\", metadata_bl.length());\n total_len += metadata_bl.length();\n }\n\n if (s->system_request && !real_clock::is_zero(lastmod)) {\n /* we end up dumping mtime in two different methods, a bit redundant */\n dump_epoch_header(s, \"Rgwx-Mtime\", lastmod);\n uint64_t pg_ver = 0;\n int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n dump_header(s, \"Rgwx-Obj-PG-Ver\", pg_ver);\n\n uint32_t source_zone_short_id = 0;\n r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n if (source_zone_short_id != 0) {\n dump_header(s, \"Rgwx-Source-Zone-Short-Id\", source_zone_short_id);\n }\n }\n\n for (auto &it : crypt_http_responses)\n dump_header(s, it.first, it.second);\n\n dump_content_length(s, total_len);\n dump_last_modified(s, lastmod);\n dump_header_if_nonempty(s, \"x-amz-version-id\", version_id);\n if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) {\n dump_header(s, \"x-rgw-object-type\", \"Appendable\");\n dump_header(s, \"x-rgw-next-append-position\", s->obj_size);\n } else {\n dump_header(s, \"x-rgw-object-type\", \"Normal\");\n }\n\n if (! op_ret) {\n if (! lo_etag.empty()) {\n /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly\n * legit to perform GET on them through S3 API. In such situation,\n * a client should receive the composited content with corresponding\n * etag value. */\n dump_etag(s, lo_etag);\n } else {\n auto iter = attrs.find(RGW_ATTR_ETAG);\n if (iter != attrs.end()) {\n dump_etag(s, iter->second.to_str());\n }\n }\n\n for (struct response_attr_param *p = resp_attr_params; p->param; p++) {\n bool exists;\n string val = s->info.args.get(p->param, &exists);\n if (exists) {\n\t/* reject unauthenticated response header manipulation, see\n\t * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */\n\tif (s->auth.identity->is_anonymous()) {\n\t return -ERR_INVALID_REQUEST;\n\t}\n\tif (strcmp(p->param, \"response-content-type\") != 0) {\n\t response_attrs[p->http_attr] = val;\n\t} else {\n\t content_type_str = val;\n\t content_type = content_type_str.c_str();\n\t}\n }\n }\n\n for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) {\n const char *name = iter->first.c_str();\n map<string, string>::iterator aiter = rgw_to_http_attrs.find(name);\n if (aiter != rgw_to_http_attrs.end()) {\n if (response_attrs.count(aiter->second) == 0) {\n /* Was not already overridden by a response param. */\n\n size_t len = iter->second.length();\n string s(iter->second.c_str(), len);\n while (len && !s[len - 1]) {\n --len;\n s.resize(len);\n }\n response_attrs[aiter->second] = s;\n }\n } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) {\n /* Special handling for content_type. */\n if (!content_type) {\n content_type_str = rgw_bl_str(iter->second);\n content_type = content_type_str.c_str();\n }\n } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {\n // this attr has an extra length prefix from encode() in prior versions\n dump_header(s, \"X-Object-Meta-Static-Large-Object\", \"True\");\n } else if (strncmp(name, RGW_ATTR_META_PREFIX,\n\t\t\t sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {\n /* User custom metadata. */\n name += sizeof(RGW_ATTR_PREFIX) - 1;\n dump_header(s, name, iter->second);\n } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) {\n RGWObjTags obj_tags;\n try{\n auto it = iter->second.cbegin();\n obj_tags.decode(it);\n } catch (buffer::error &err) {\n ldout(s->cct,0) << \"Error caught buffer::error couldn't decode TagSet \" << dendl;\n }\n dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count());\n } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){\n RGWObjectRetention retention;\n try {\n decode(retention, iter->second);\n dump_header(s, \"x-amz-object-lock-mode\", retention.get_mode());\n dump_time_header(s, \"x-amz-object-lock-retain-until-date\", retention.get_retain_until_date());\n } catch (buffer::error& err) {\n ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectRetention\" << dendl;\n }\n } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) {\n RGWObjectLegalHold legal_hold;\n try {\n decode(legal_hold, iter->second);\n dump_header(s, \"x-amz-object-lock-legal-hold\",legal_hold.get_status());\n } catch (buffer::error& err) {\n ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectLegalHold\" << dendl;\n }\n }\n }\n }\n\ndone:\n for (riter = response_attrs.begin(); riter != response_attrs.end();\n ++riter) {\n dump_header(s, riter->first, riter->second);\n }\n\n if (op_ret == -ERR_NOT_MODIFIED) {\n end_header(s, this);\n } else {\n if (!content_type)\n content_type = \"binary/octet-stream\";\n\n end_header(s, this, content_type);\n }\n\n if (metadata_bl.length()) {\n dump_body(s, metadata_bl);\n }\n sent_header = true;\n\nsend_data:\n if (get_data && !op_ret) {\n int r = dump_body(s, bl.c_str() + bl_ofs, bl_len);\n if (r < 0)\n return r;\n }\n\n return 0;\n}", "project": "ceph", "hash": 107958417671493336880373196615590270707, "size": 207, "commit_id": "c7da604cb101cbe78a257a29498a98c69964e0a6", "message": "rgw: reject control characters in response-header actions\n\nS3 GetObject permits overriding response header values, but those inputs\nneed to be validated to insure only characters that are valid in an HTTP\nheader value are present.\n\nCredit: Initial vulnerability discovery by William Bowling (@wcbowling)\nCredit: Further vulnerability discovery by Robin H. Johnson <rjohnson@digitalocean.com>\nSigned-off-by: Robin H. Johnson <rjohnson@digitalocean.com>", "target": 1, "dataset": "other", "idx": 212167}
  912. {"func": "int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs,\n\t\t\t\t\t off_t bl_len)\n{\n const char *content_type = NULL;\n string content_type_str;\n map<string, string> response_attrs;\n map<string, string>::iterator riter;\n bufferlist metadata_bl;\n\n if (sent_header)\n goto send_data;\n\n if (custom_http_ret) {\n set_req_state_err(s, 0);\n dump_errno(s, custom_http_ret);\n } else {\n set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT\n : op_ret);\n dump_errno(s);\n }\n\n if (op_ret)\n goto done;\n\n if (range_str)\n dump_range(s, start, end, s->obj_size);\n\n if (s->system_request &&\n s->info.args.exists(RGW_SYS_PARAM_PREFIX \"prepend-metadata\")) {\n\n dump_header(s, \"Rgwx-Object-Size\", (long long)total_len);\n\n if (rgwx_stat) {\n /*\n * in this case, we're not returning the object's content, only the prepended\n * extra metadata\n */\n total_len = 0;\n }\n\n /* JSON encode object metadata */\n JSONFormatter jf;\n jf.open_object_section(\"obj_metadata\");\n encode_json(\"attrs\", attrs, &jf);\n utime_t ut(lastmod);\n encode_json(\"mtime\", ut, &jf);\n jf.close_section();\n stringstream ss;\n jf.flush(ss);\n metadata_bl.append(ss.str());\n dump_header(s, \"Rgwx-Embedded-Metadata-Len\", metadata_bl.length());\n total_len += metadata_bl.length();\n }\n\n if (s->system_request && !real_clock::is_zero(lastmod)) {\n /* we end up dumping mtime in two different methods, a bit redundant */\n dump_epoch_header(s, \"Rgwx-Mtime\", lastmod);\n uint64_t pg_ver = 0;\n int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n dump_header(s, \"Rgwx-Obj-PG-Ver\", pg_ver);\n\n uint32_t source_zone_short_id = 0;\n r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n if (source_zone_short_id != 0) {\n dump_header(s, \"Rgwx-Source-Zone-Short-Id\", source_zone_short_id);\n }\n }\n\n for (auto &it : crypt_http_responses)\n dump_header(s, it.first, it.second);\n\n dump_content_length(s, total_len);\n dump_last_modified(s, lastmod);\n dump_header_if_nonempty(s, \"x-amz-version-id\", version_id);\n if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) {\n dump_header(s, \"x-rgw-object-type\", \"Appendable\");\n dump_header(s, \"x-rgw-next-append-position\", s->obj_size);\n } else {\n dump_header(s, \"x-rgw-object-type\", \"Normal\");\n }\n\n if (! op_ret) {\n if (! lo_etag.empty()) {\n /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly\n * legit to perform GET on them through S3 API. In such situation,\n * a client should receive the composited content with corresponding\n * etag value. */\n dump_etag(s, lo_etag);\n } else {\n auto iter = attrs.find(RGW_ATTR_ETAG);\n if (iter != attrs.end()) {\n dump_etag(s, iter->second.to_str());\n }\n }\n\n for (struct response_attr_param *p = resp_attr_params; p->param; p++) {\n bool exists;\n string val = s->info.args.get(p->param, &exists);\n if (exists) {\n\t/* reject unauthenticated response header manipulation, see\n\t * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */\n\tif (s->auth.identity->is_anonymous()) {\n\t return -ERR_INVALID_REQUEST;\n\t}\n /* HTTP specification says no control characters should be present in\n * header values: https://tools.ietf.org/html/rfc7230#section-3.2\n * field-vchar = VCHAR / obs-text\n *\n * Failure to validate this permits a CRLF injection in HTTP headers,\n * whereas S3 GetObject only permits specific headers.\n */\n if(str_has_cntrl(val)) {\n /* TODO: return a more distinct error in future;\n * stating what the problem is */\n return -ERR_INVALID_REQUEST;\n }\n\n\tif (strcmp(p->param, \"response-content-type\") != 0) {\n\t response_attrs[p->http_attr] = val;\n\t} else {\n\t content_type_str = val;\n\t content_type = content_type_str.c_str();\n\t}\n }\n }\n\n for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) {\n const char *name = iter->first.c_str();\n map<string, string>::iterator aiter = rgw_to_http_attrs.find(name);\n if (aiter != rgw_to_http_attrs.end()) {\n if (response_attrs.count(aiter->second) == 0) {\n /* Was not already overridden by a response param. */\n\n size_t len = iter->second.length();\n string s(iter->second.c_str(), len);\n while (len && !s[len - 1]) {\n --len;\n s.resize(len);\n }\n response_attrs[aiter->second] = s;\n }\n } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) {\n /* Special handling for content_type. */\n if (!content_type) {\n content_type_str = rgw_bl_str(iter->second);\n content_type = content_type_str.c_str();\n }\n } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {\n // this attr has an extra length prefix from encode() in prior versions\n dump_header(s, \"X-Object-Meta-Static-Large-Object\", \"True\");\n } else if (strncmp(name, RGW_ATTR_META_PREFIX,\n\t\t\t sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {\n /* User custom metadata. */\n name += sizeof(RGW_ATTR_PREFIX) - 1;\n dump_header(s, name, iter->second);\n } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) {\n RGWObjTags obj_tags;\n try{\n auto it = iter->second.cbegin();\n obj_tags.decode(it);\n } catch (buffer::error &err) {\n ldout(s->cct,0) << \"Error caught buffer::error couldn't decode TagSet \" << dendl;\n }\n dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count());\n } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){\n RGWObjectRetention retention;\n try {\n decode(retention, iter->second);\n dump_header(s, \"x-amz-object-lock-mode\", retention.get_mode());\n dump_time_header(s, \"x-amz-object-lock-retain-until-date\", retention.get_retain_until_date());\n } catch (buffer::error& err) {\n ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectRetention\" << dendl;\n }\n } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) {\n RGWObjectLegalHold legal_hold;\n try {\n decode(legal_hold, iter->second);\n dump_header(s, \"x-amz-object-lock-legal-hold\",legal_hold.get_status());\n } catch (buffer::error& err) {\n ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectLegalHold\" << dendl;\n }\n }\n }\n }\n\ndone:\n for (riter = response_attrs.begin(); riter != response_attrs.end();\n ++riter) {\n dump_header(s, riter->first, riter->second);\n }\n\n if (op_ret == -ERR_NOT_MODIFIED) {\n end_header(s, this);\n } else {\n if (!content_type)\n content_type = \"binary/octet-stream\";\n\n end_header(s, this, content_type);\n }\n\n if (metadata_bl.length()) {\n dump_body(s, metadata_bl);\n }\n sent_header = true;\n\nsend_data:\n if (get_data && !op_ret) {\n int r = dump_body(s, bl.c_str() + bl_ofs, bl_len);\n if (r < 0)\n return r;\n }\n\n return 0;\n}", "project": "ceph", "hash": 201752665573529785548111322973661860146, "size": 220, "commit_id": "c7da604cb101cbe78a257a29498a98c69964e0a6", "message": "rgw: reject control characters in response-header actions\n\nS3 GetObject permits overriding response header values, but those inputs\nneed to be validated to insure only characters that are valid in an HTTP\nheader value are present.\n\nCredit: Initial vulnerability discovery by William Bowling (@wcbowling)\nCredit: Further vulnerability discovery by Robin H. Johnson <rjohnson@digitalocean.com>\nSigned-off-by: Robin H. Johnson <rjohnson@digitalocean.com>", "target": 0, "dataset": "other", "idx": 455531}
  913. {"func": "gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)\n{\n TIFF* tif = img->tif;\n tileContigRoutine put = img->put.contig;\n uint32 col, row, y, rowstoread;\n tmsize_t pos;\n uint32 tw, th;\n unsigned char* buf = NULL;\n int32 fromskew, toskew;\n uint32 nrow;\n int ret = 1, flip;\n uint32 this_tw, tocol;\n int32 this_toskew, leftmost_toskew;\n int32 leftmost_fromskew;\n uint32 leftmost_tw;\n tmsize_t bufsize;\n\n bufsize = TIFFTileSize(tif);\n if (bufsize == 0) {\n TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), \"%s\", \"No space for tile buffer\");\n return (0);\n }\n\n TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);\n TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);\n\n flip = setorientation(img);\n if (flip & FLIP_VERTICALLY) {\n\t y = h - 1;\n\t toskew = -(int32)(tw + w);\n }\n else {\n\t y = 0;\n\t toskew = -(int32)(tw - w);\n }\n \n /*\n *\tLeftmost tile is clipped on left side if col_offset > 0.\n */\n leftmost_fromskew = img->col_offset % tw;\n leftmost_tw = tw - leftmost_fromskew;\n leftmost_toskew = toskew + leftmost_fromskew;\n for (row = 0; ret != 0 && row < h; row += nrow)\n {\n rowstoread = th - (row + img->row_offset) % th;\n \tnrow = (row + rowstoread > h ? h - row : rowstoread);\n\tfromskew = leftmost_fromskew;\n\tthis_tw = leftmost_tw;\n\tthis_toskew = leftmost_toskew;\n\ttocol = 0;\n\tcol = img->col_offset;\n\twhile (tocol < w)\n {\n\t if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col,\n\t\t\t row+img->row_offset, 0, 0)==(tmsize_t)(-1) &&\n (buf == NULL || img->stoponerr))\n {\n ret = 0;\n break;\n }\n pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \\\n\t\t ((tmsize_t) fromskew * img->samplesperpixel);\n\t if (tocol + this_tw > w) \n\t {\n\t\t/*\n\t\t * Rightmost tile is clipped on right side.\n\t\t */\n\t\tfromskew = tw - (w - tocol);\n\t\tthis_tw = tw - fromskew;\n\t\tthis_toskew = toskew + fromskew;\n\t }\n\t (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos);\n\t tocol += this_tw;\n\t col += this_tw;\n\t /*\n\t * After the leftmost tile, tiles are no longer clipped on left side.\n\t */\n\t fromskew = 0;\n\t this_tw = tw;\n\t this_toskew = toskew;\n\t}\n\n y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow);\n }\n _TIFFfree(buf);\n\n if (flip & FLIP_HORIZONTALLY) {\n\t uint32 line;\n\n\t for (line = 0; line < h; line++) {\n\t\t uint32 *left = raster + (line * w);\n\t\t uint32 *right = left + w - 1;\n\t\t \n\t\t while ( left < right ) {\n\t\t\t uint32 temp = *left;\n\t\t\t *left = *right;\n\t\t\t *right = temp;\n\t\t\t left++;\n\t\t\t\tright--;\n\t\t }\n\t }\n }\n\n return (ret);\n}", "project": "libtiff", "hash": 969528565132778716942049224777711470, "size": 105, "commit_id": "c8d613ef497058fe653c467fc84c70a62a4a71b2", "message": "gtTileContig(): check Tile width for overflow\n\nfixes #211", "target": 1, "dataset": "other", "idx": 212214}
  914. {"func": "gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)\n{\n TIFF* tif = img->tif;\n tileContigRoutine put = img->put.contig;\n uint32 col, row, y, rowstoread;\n tmsize_t pos;\n uint32 tw, th;\n unsigned char* buf = NULL;\n int32 fromskew, toskew;\n uint32 nrow;\n int ret = 1, flip;\n uint32 this_tw, tocol;\n int32 this_toskew, leftmost_toskew;\n int32 leftmost_fromskew;\n uint32 leftmost_tw;\n tmsize_t bufsize;\n\n bufsize = TIFFTileSize(tif);\n if (bufsize == 0) {\n TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), \"%s\", \"No space for tile buffer\");\n return (0);\n }\n\n TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);\n TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);\n\n flip = setorientation(img);\n if (flip & FLIP_VERTICALLY) {\n if ((tw + w) > INT_MAX) {\n TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), \"%s\", \"unsupported tile size (too wide)\");\n return (0);\n }\n y = h - 1;\n toskew = -(int32)(tw + w);\n }\n else {\n if (tw > (INT_MAX + w)) {\n TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), \"%s\", \"unsupported tile size (too wide)\");\n return (0);\n }\n y = 0;\n toskew = -(int32)(tw - w);\n }\n \n /*\n *\tLeftmost tile is clipped on left side if col_offset > 0.\n */\n leftmost_fromskew = img->col_offset % tw;\n leftmost_tw = tw - leftmost_fromskew;\n leftmost_toskew = toskew + leftmost_fromskew;\n for (row = 0; ret != 0 && row < h; row += nrow)\n {\n rowstoread = th - (row + img->row_offset) % th;\n \tnrow = (row + rowstoread > h ? h - row : rowstoread);\n\tfromskew = leftmost_fromskew;\n\tthis_tw = leftmost_tw;\n\tthis_toskew = leftmost_toskew;\n\ttocol = 0;\n\tcol = img->col_offset;\n\twhile (tocol < w)\n {\n\t if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col,\n\t\t\t row+img->row_offset, 0, 0)==(tmsize_t)(-1) &&\n (buf == NULL || img->stoponerr))\n {\n ret = 0;\n break;\n }\n pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \\\n\t\t ((tmsize_t) fromskew * img->samplesperpixel);\n\t if (tocol + this_tw > w) \n\t {\n\t\t/*\n\t\t * Rightmost tile is clipped on right side.\n\t\t */\n\t\tfromskew = tw - (w - tocol);\n\t\tthis_tw = tw - fromskew;\n\t\tthis_toskew = toskew + fromskew;\n\t }\n\t (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos);\n\t tocol += this_tw;\n\t col += this_tw;\n\t /*\n\t * After the leftmost tile, tiles are no longer clipped on left side.\n\t */\n\t fromskew = 0;\n\t this_tw = tw;\n\t this_toskew = toskew;\n\t}\n\n y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow);\n }\n _TIFFfree(buf);\n\n if (flip & FLIP_HORIZONTALLY) {\n\t uint32 line;\n\n\t for (line = 0; line < h; line++) {\n\t\t uint32 *left = raster + (line * w);\n\t\t uint32 *right = left + w - 1;\n\t\t \n\t\t while ( left < right ) {\n\t\t\t uint32 temp = *left;\n\t\t\t *left = *right;\n\t\t\t *right = temp;\n\t\t\t left++;\n\t\t\t\tright--;\n\t\t }\n\t }\n }\n\n return (ret);\n}", "project": "libtiff", "hash": 105544395782509597916020347204964946551, "size": 113, "commit_id": "c8d613ef497058fe653c467fc84c70a62a4a71b2", "message": "gtTileContig(): check Tile width for overflow\n\nfixes #211", "target": 0, "dataset": "other", "idx": 456508}
  915. {"func": "static void io_async_task_func(struct callback_head *cb)\n{\n\tstruct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);\n\tstruct async_poll *apoll = req->apoll;\n\tstruct io_ring_ctx *ctx = req->ctx;\n\n\ttrace_io_uring_task_run(req->ctx, req->opcode, req->user_data);\n\n\tif (io_poll_rewait(req, &apoll->poll)) {\n\t\tspin_unlock_irq(&ctx->completion_lock);\n\t\treturn;\n\t}\n\n\t/* If req is still hashed, it cannot have been canceled. Don't check. */\n\tif (hash_hashed(&req->hash_node))\n\t\thash_del(&req->hash_node);\n\n\tio_poll_remove_double(req, apoll->double_poll);\n\tspin_unlock_irq(&ctx->completion_lock);\n\n\tif (!READ_ONCE(apoll->poll.canceled))\n\t\t__io_req_task_submit(req);\n\telse\n\t\t__io_req_task_cancel(req, -ECANCELED);\n\n\tkfree(apoll->double_poll);\n\tkfree(apoll);\n}", "project": "linux", "hash": 73404555622332263956206411713115350167, "size": 28, "commit_id": "6d816e088c359866f9867057e04f244c608c42fe", "message": "io_uring: hold 'ctx' reference around task_work queue + execute\n\nWe're holding the request reference, but we need to go one higher\nto ensure that the ctx remains valid after the request has finished.\nIf the ring is closed with pending task_work inflight, and the\ngiven io_kiocb finishes sync during issue, then we need a reference\nto the ring itself around the task_work execution cycle.\n\nCc: stable@vger.kernel.org # v5.7+\nReported-by: syzbot+9b260fc33297966f5a8e@syzkaller.appspotmail.com\nSigned-off-by: Jens Axboe <axboe@kernel.dk>", "target": 1, "dataset": "other", "idx": 212266}
  916. {"func": "static void io_async_task_func(struct callback_head *cb)\n{\n\tstruct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);\n\tstruct async_poll *apoll = req->apoll;\n\tstruct io_ring_ctx *ctx = req->ctx;\n\n\ttrace_io_uring_task_run(req->ctx, req->opcode, req->user_data);\n\n\tif (io_poll_rewait(req, &apoll->poll)) {\n\t\tspin_unlock_irq(&ctx->completion_lock);\n\t\tpercpu_ref_put(&ctx->refs);\n\t\treturn;\n\t}\n\n\t/* If req is still hashed, it cannot have been canceled. Don't check. */\n\tif (hash_hashed(&req->hash_node))\n\t\thash_del(&req->hash_node);\n\n\tio_poll_remove_double(req, apoll->double_poll);\n\tspin_unlock_irq(&ctx->completion_lock);\n\n\tif (!READ_ONCE(apoll->poll.canceled))\n\t\t__io_req_task_submit(req);\n\telse\n\t\t__io_req_task_cancel(req, -ECANCELED);\n\n\tpercpu_ref_put(&ctx->refs);\n\tkfree(apoll->double_poll);\n\tkfree(apoll);\n}", "project": "linux", "hash": 269241368234990870928581246061985683801, "size": 30, "commit_id": "6d816e088c359866f9867057e04f244c608c42fe", "message": "io_uring: hold 'ctx' reference around task_work queue + execute\n\nWe're holding the request reference, but we need to go one higher\nto ensure that the ctx remains valid after the request has finished.\nIf the ring is closed with pending task_work inflight, and the\ngiven io_kiocb finishes sync during issue, then we need a reference\nto the ring itself around the task_work execution cycle.\n\nCc: stable@vger.kernel.org # v5.7+\nReported-by: syzbot+9b260fc33297966f5a8e@syzkaller.appspotmail.com\nSigned-off-by: Jens Axboe <axboe@kernel.dk>", "target": 0, "dataset": "other", "idx": 456954}
  917. {"func": "\nprivate int\nmget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,\n int flip, int recursion_level, int *printed_something,\n int *need_separator, int *returnval)\n{\n\tuint32_t soffset, offset = ms->offset;\n\tuint32_t count = m->str_range;\n\tint rv, oneed_separator;\n\tchar *sbuf, *rbuf;\n\tunion VALUETYPE *p = &ms->ms_value;\n\tstruct mlist ml;\n\n\tif (recursion_level >= 20) {\n\t\tfile_error(ms, 0, \"recursion nesting exceeded\");\n\t\treturn -1;\n\t}\n\n\tif (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),\n\t (uint32_t)nbytes, count) == -1)\n\t\treturn -1;\n\n\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\tfprintf(stderr, \"mget(type=%d, flag=%x, offset=%u, o=%zu, \"\n\t\t \"nbytes=%zu, count=%u)\\n\", m->type, m->flag, offset, o,\n\t\t nbytes, count);\n\t\tmdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));\n\t}\n\n\tif (m->flag & INDIR) {\n\t\tint off = m->in_offset;\n\t\tif (m->in_op & FILE_OPINDIRECT) {\n\t\t\tconst union VALUETYPE *q = CAST(const union VALUETYPE *,\n\t\t\t ((const void *)(s + offset + off)));\n\t\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\t\tcase FILE_BYTE:\n\t\t\t\toff = q->b;\n\t\t\t\tbreak;\n\t\t\tcase FILE_SHORT:\n\t\t\t\toff = q->h;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BESHORT:\n\t\t\t\toff = (short)((q->hs[0]<<8)|(q->hs[1]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LESHORT:\n\t\t\t\toff = (short)((q->hs[1]<<8)|(q->hs[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LONG:\n\t\t\t\toff = q->l;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BELONG:\n\t\t\tcase FILE_BEID3:\n\t\t\t\toff = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|\n\t\t\t\t\t\t (q->hl[2]<<8)|(q->hl[3]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LEID3:\n\t\t\tcase FILE_LELONG:\n\t\t\t\toff = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|\n\t\t\t\t\t\t (q->hl[1]<<8)|(q->hl[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_MELONG:\n\t\t\t\toff = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|\n\t\t\t\t\t\t (q->hl[3]<<8)|(q->hl[2]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect offs=%u\\n\", off);\n\t\t}\n\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_BYTE:\n\t\t\tif (nbytes < (offset + 1))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->b & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->b | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->b ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->b + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->b - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->b * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->b / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->b % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = p->b;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_BESHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t (p->hs[1]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LESHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t (p->hs[0]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_SHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->h & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->h | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->h ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->h + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->h - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->h * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->h / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->h % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\toffset = p->h;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_BELONG:\n\t\tcase FILE_BEID3:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t (p->hl[3]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LELONG:\n\t\tcase FILE_LEID3:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t (p->hl[0]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_MELONG:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t (p->hl[2]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LONG:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->l & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->l | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->l ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->l + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->l - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->l * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->l / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->l % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = p->l;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_LEID3:\n\t\tcase FILE_BEID3:\n\t\t\toffset = ((((offset >> 0) & 0x7f) << 0) |\n\t\t\t\t (((offset >> 8) & 0x7f) << 7) |\n\t\t\t\t (((offset >> 16) & 0x7f) << 14) |\n\t\t\t\t (((offset >> 24) & 0x7f) << 21)) + 10;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tif (m->flag & INDIROFFADD) {\n\t\t\toffset += ms->c.li[cont_level-1].off;\n\t\t\tif (offset == 0) {\n\t\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t \"indirect *zero* offset\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect +offs=%u\\n\", offset);\n\t\t}\n\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)\n\t\t\treturn -1;\n\t\tms->offset = offset;\n\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\t\tmdebug(offset, (char *)(void *)p,\n\t\t\t sizeof(union VALUETYPE));\n\t\t}\n\t}\n\n\t/* Verify we have enough data to match magic type */\n\tswitch (m->type) {\n\tcase FILE_BYTE:\n\t\tif (nbytes < (offset + 1)) /* should alway be true */\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_SHORT:\n\tcase FILE_BESHORT:\n\tcase FILE_LESHORT:\n\t\tif (nbytes < (offset + 2))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_LONG:\n\tcase FILE_BELONG:\n\tcase FILE_LELONG:\n\tcase FILE_MELONG:\n\tcase FILE_DATE:\n\tcase FILE_BEDATE:\n\tcase FILE_LEDATE:\n\tcase FILE_MEDATE:\n\tcase FILE_LDATE:\n\tcase FILE_BELDATE:\n\tcase FILE_LELDATE:\n\tcase FILE_MELDATE:\n\tcase FILE_FLOAT:\n\tcase FILE_BEFLOAT:\n\tcase FILE_LEFLOAT:\n\t\tif (nbytes < (offset + 4))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_DOUBLE:\n\tcase FILE_BEDOUBLE:\n\tcase FILE_LEDOUBLE:\n\t\tif (nbytes < (offset + 8))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_STRING:\n\tcase FILE_PSTRING:\n\tcase FILE_SEARCH:\n\t\tif (nbytes < (offset + m->vallen))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_REGEX:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_INDIRECT:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = ms->o.buf;\n\t\tsoffset = ms->offset;\n\t\tms->o.buf = NULL;\n\t\tms->offset = 0;\n\t\trv = file_softmagic(ms, s + offset, nbytes - offset,\n\t\t BINTEST, text);\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\tfprintf(stderr, \"indirect @offs=%u[%d]\\n\", offset, rv);\n\t\trbuf = ms->o.buf;\n\t\tms->o.buf = sbuf;\n\t\tms->offset = soffset;\n\t\tif (rv == 1) {\n\t \tif ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&\n\t\t\t file_printf(ms, m->desc, offset) == -1)\n\t\t\treturn -1;\n\t\t\tif (file_printf(ms, \"%s\", rbuf) == -1)\n\t\t\t\treturn -1;\n\t\t\tfree(rbuf);\n\t\t}\n\t\treturn rv;\n\n\tcase FILE_USE:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = m->value.s;\n\t\tif (*sbuf == '^') {\n\t\t\tsbuf++;\n\t\t\tflip = !flip;\n\t\t}\n\t\tif (file_magicfind(ms, sbuf, &ml) == -1) {\n\t\t\tfile_error(ms, 0, \"cannot find entry `%s'\", sbuf);\n\t\t\treturn -1;\n\t\t}\n\n\t\toneed_separator = *need_separator;\n\t\tif (m->flag & NOSPACE)\n\t\t\t*need_separator = 0;\n\t\trv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,\n\t\t mode, text, flip, recursion_level, printed_something,\n\t\t need_separator, returnval);\n\t\tif (rv != 1)\n\t\t *need_separator = oneed_separator;\n\t\treturn rv;\n\n\tcase FILE_NAME:\n\t\tif (file_printf(ms, \"%s\", m->desc) == -1)\n\t\t\treturn -1;\n\t\treturn 1;\n\tcase FILE_DEFAULT:\t/* nothing to check */\n\tdefault:\n\t\tbreak;\n\t}\n\tif (!mconvert(ms, m, flip))\n\t\treturn 0;", "project": "php-src", "hash": 20949309710087477528406375704484824069, "size": 636, "commit_id": "74555e7c26b2c61bb8e67b7d6a6f4d2b8eb3a5f3", "message": "Fixed bug #64830 mimetype detection segfaults on mp3 file", "target": 1, "dataset": "other", "idx": 212275}
  918. {"func": "\nprivate int\nmget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,\n int flip, int recursion_level, int *printed_something,\n int *need_separator, int *returnval)\n{\n\tuint32_t soffset, offset = ms->offset;\n\tuint32_t count = m->str_range;\n\tint rv, oneed_separator;\n\tchar *sbuf, *rbuf;\n\tunion VALUETYPE *p = &ms->ms_value;\n\tstruct mlist ml;\n\n\tif (recursion_level >= 20) {\n\t\tfile_error(ms, 0, \"recursion nesting exceeded\");\n\t\treturn -1;\n\t}\n\n\tif (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),\n\t (uint32_t)nbytes, count) == -1)\n\t\treturn -1;\n\n\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\tfprintf(stderr, \"mget(type=%d, flag=%x, offset=%u, o=%zu, \"\n\t\t \"nbytes=%zu, count=%u)\\n\", m->type, m->flag, offset, o,\n\t\t nbytes, count);\n\t\tmdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));\n\t}\n\n\tif (m->flag & INDIR) {\n\t\tint off = m->in_offset;\n\t\tif (m->in_op & FILE_OPINDIRECT) {\n\t\t\tconst union VALUETYPE *q = CAST(const union VALUETYPE *,\n\t\t\t ((const void *)(s + offset + off)));\n\t\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\t\tcase FILE_BYTE:\n\t\t\t\toff = q->b;\n\t\t\t\tbreak;\n\t\t\tcase FILE_SHORT:\n\t\t\t\toff = q->h;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BESHORT:\n\t\t\t\toff = (short)((q->hs[0]<<8)|(q->hs[1]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LESHORT:\n\t\t\t\toff = (short)((q->hs[1]<<8)|(q->hs[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LONG:\n\t\t\t\toff = q->l;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BELONG:\n\t\t\tcase FILE_BEID3:\n\t\t\t\toff = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|\n\t\t\t\t\t\t (q->hl[2]<<8)|(q->hl[3]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LEID3:\n\t\t\tcase FILE_LELONG:\n\t\t\t\toff = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|\n\t\t\t\t\t\t (q->hl[1]<<8)|(q->hl[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_MELONG:\n\t\t\t\toff = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|\n\t\t\t\t\t\t (q->hl[3]<<8)|(q->hl[2]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect offs=%u\\n\", off);\n\t\t}\n\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_BYTE:\n\t\t\tif (nbytes < (offset + 1))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->b & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->b | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->b ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->b + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->b - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->b * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->b / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->b % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = p->b;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_BESHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t (p->hs[1]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LESHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t (p->hs[0]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_SHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->h & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->h | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->h ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->h + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->h - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->h * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->h / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->h % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\toffset = p->h;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_BELONG:\n\t\tcase FILE_BEID3:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t (p->hl[3]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LELONG:\n\t\tcase FILE_LEID3:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t (p->hl[0]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_MELONG:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t (p->hl[2]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LONG:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->l & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->l | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->l ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->l + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->l - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->l * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->l / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->l % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = p->l;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_LEID3:\n\t\tcase FILE_BEID3:\n\t\t\toffset = ((((offset >> 0) & 0x7f) << 0) |\n\t\t\t\t (((offset >> 8) & 0x7f) << 7) |\n\t\t\t\t (((offset >> 16) & 0x7f) << 14) |\n\t\t\t\t (((offset >> 24) & 0x7f) << 21)) + 10;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tif (m->flag & INDIROFFADD) {\n\t\t\toffset += ms->c.li[cont_level-1].off;\n\t\t\tif (offset == 0) {\n\t\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t \"indirect *zero* offset\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect +offs=%u\\n\", offset);\n\t\t}\n\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)\n\t\t\treturn -1;\n\t\tms->offset = offset;\n\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\t\tmdebug(offset, (char *)(void *)p,\n\t\t\t sizeof(union VALUETYPE));\n\t\t}\n\t}\n\n\t/* Verify we have enough data to match magic type */\n\tswitch (m->type) {\n\tcase FILE_BYTE:\n\t\tif (nbytes < (offset + 1)) /* should alway be true */\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_SHORT:\n\tcase FILE_BESHORT:\n\tcase FILE_LESHORT:\n\t\tif (nbytes < (offset + 2))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_LONG:\n\tcase FILE_BELONG:\n\tcase FILE_LELONG:\n\tcase FILE_MELONG:\n\tcase FILE_DATE:\n\tcase FILE_BEDATE:\n\tcase FILE_LEDATE:\n\tcase FILE_MEDATE:\n\tcase FILE_LDATE:\n\tcase FILE_BELDATE:\n\tcase FILE_LELDATE:\n\tcase FILE_MELDATE:\n\tcase FILE_FLOAT:\n\tcase FILE_BEFLOAT:\n\tcase FILE_LEFLOAT:\n\t\tif (nbytes < (offset + 4))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_DOUBLE:\n\tcase FILE_BEDOUBLE:\n\tcase FILE_LEDOUBLE:\n\t\tif (nbytes < (offset + 8))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_STRING:\n\tcase FILE_PSTRING:\n\tcase FILE_SEARCH:\n\t\tif (nbytes < (offset + m->vallen))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_REGEX:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_INDIRECT:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = ms->o.buf;\n\t\tsoffset = ms->offset;\n\t\tms->o.buf = NULL;\n\t\tms->offset = 0;\n\t\trv = file_softmagic(ms, s + offset, nbytes - offset,\n\t\t BINTEST, text);\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\tfprintf(stderr, \"indirect @offs=%u[%d]\\n\", offset, rv);\n\t\trbuf = ms->o.buf;\n\t\tms->o.buf = sbuf;\n\t\tms->offset = soffset;\n\t\tif (rv == 1) {\n\t \tif ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&\n\t\t\t file_printf(ms, m->desc, offset) == -1)\n\t\t\treturn -1;\n\t\t\tif (file_printf(ms, \"%s\", rbuf) == -1)\n\t\t\t\treturn -1;\n\t\t\tefree(rbuf);\n\t\t}\n\t\treturn rv;\n\n\tcase FILE_USE:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = m->value.s;\n\t\tif (*sbuf == '^') {\n\t\t\tsbuf++;\n\t\t\tflip = !flip;\n\t\t}\n\t\tif (file_magicfind(ms, sbuf, &ml) == -1) {\n\t\t\tfile_error(ms, 0, \"cannot find entry `%s'\", sbuf);\n\t\t\treturn -1;\n\t\t}\n\n\t\toneed_separator = *need_separator;\n\t\tif (m->flag & NOSPACE)\n\t\t\t*need_separator = 0;\n\t\trv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,\n\t\t mode, text, flip, recursion_level, printed_something,\n\t\t need_separator, returnval);\n\t\tif (rv != 1)\n\t\t *need_separator = oneed_separator;\n\t\treturn rv;\n\n\tcase FILE_NAME:\n\t\tif (file_printf(ms, \"%s\", m->desc) == -1)\n\t\t\treturn -1;\n\t\treturn 1;\n\tcase FILE_DEFAULT:\t/* nothing to check */\n\tdefault:\n\t\tbreak;\n\t}\n\tif (!mconvert(ms, m, flip))\n\t\treturn 0;", "project": "php-src", "hash": 244766288179399097818062065157958913189, "size": 636, "commit_id": "74555e7c26b2c61bb8e67b7d6a6f4d2b8eb3a5f3", "message": "Fixed bug #64830 mimetype detection segfaults on mp3 file", "target": 0, "dataset": "other", "idx": 456966}
  919. {"func": "ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) {\n UINT8 *ptr;\n int framesize;\n int c, chunks, advance;\n int l, lines;\n int i, j, x = 0, y, ymax;\n\n /* If not even the chunk size is present, we'd better leave */\n\n if (bytes < 4) {\n return 0;\n }\n\n /* We don't decode anything unless we have a full chunk in the\n input buffer */\n\n ptr = buf;\n\n framesize = I32(ptr);\n if (framesize < I32(ptr)) {\n return 0;\n }\n\n /* Make sure this is a frame chunk. The Python driver takes\n case of other chunk types. */\n\n if (bytes < 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n if (I16(ptr + 4) != 0xF1FA) {\n state->errcode = IMAGING_CODEC_UNKNOWN;\n return -1;\n }\n\n chunks = I16(ptr + 6);\n ptr += 16;\n bytes -= 16;\n\n /* Process subchunks */\n for (c = 0; c < chunks; c++) {\n UINT8 *data;\n if (bytes < 10) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n data = ptr + 6;\n switch (I16(ptr + 4)) {\n case 4:\n case 11:\n /* FLI COLOR chunk */\n break; /* ignored; handled by Python code */\n case 7:\n /* FLI SS2 chunk (word delta) */\n /* OOB ok, we've got 4 bytes min on entry */\n lines = I16(data);\n data += 2;\n for (l = y = 0; l < lines && y < state->ysize; l++, y++) {\n UINT8 *local_buf = (UINT8 *)im->image[y];\n int p, packets;\n ERR_IF_DATA_OOB(2)\n packets = I16(data);\n data += 2;\n while (packets & 0x8000) {\n /* flag word */\n if (packets & 0x4000) {\n y += 65536 - packets; /* skip lines */\n if (y >= state->ysize) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n local_buf = (UINT8 *)im->image[y];\n } else {\n /* store last byte (used if line width is odd) */\n local_buf[state->xsize - 1] = (UINT8)packets;\n }\n ERR_IF_DATA_OOB(2)\n packets = I16(data);\n data += 2;\n }\n for (p = x = 0; p < packets; p++) {\n ERR_IF_DATA_OOB(2)\n x += data[0]; /* pixel skip */\n if (data[1] >= 128) {\n ERR_IF_DATA_OOB(4)\n i = 256 - data[1]; /* run */\n if (x + i + i > state->xsize) {\n break;\n }\n for (j = 0; j < i; j++) {\n local_buf[x++] = data[2];\n local_buf[x++] = data[3];\n }\n data += 2 + 2;\n } else {\n i = 2 * (int)data[1]; /* chunk */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(2 + i)\n memcpy(local_buf + x, data + 2, i);\n data += 2 + i;\n x += i;\n }\n }\n if (p < packets) {\n break; /* didn't process all packets */\n }\n }\n if (l < lines) {\n /* didn't process all lines */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n break;\n case 12:\n /* FLI LC chunk (byte delta) */\n /* OOB Check ok, we have 4 bytes min here */\n y = I16(data);\n ymax = y + I16(data + 2);\n data += 4;\n for (; y < ymax && y < state->ysize; y++) {\n UINT8 *out = (UINT8 *)im->image[y];\n ERR_IF_DATA_OOB(1)\n int p, packets = *data++;\n for (p = x = 0; p < packets; p++, x += i) {\n ERR_IF_DATA_OOB(2)\n x += data[0]; /* skip pixels */\n if (data[1] & 0x80) {\n i = 256 - data[1]; /* run */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(3)\n memset(out + x, data[2], i);\n data += 3;\n } else {\n i = data[1]; /* chunk */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(2 + i)\n memcpy(out + x, data + 2, i);\n data += i + 2;\n }\n }\n if (p < packets) {\n break; /* didn't process all packets */\n }\n }\n if (y < ymax) {\n /* didn't process all lines */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n break;\n case 13:\n /* FLI BLACK chunk */\n for (y = 0; y < state->ysize; y++) {\n memset(im->image[y], 0, state->xsize);\n }\n break;\n case 15:\n /* FLI BRUN chunk */\n /* OOB, ok, we've got 4 bytes min on entry */\n for (y = 0; y < state->ysize; y++) {\n UINT8 *out = (UINT8 *)im->image[y];\n data += 1; /* ignore packetcount byte */\n for (x = 0; x < state->xsize; x += i) {\n ERR_IF_DATA_OOB(2)\n if (data[0] & 0x80) {\n i = 256 - data[0];\n if (x + i > state->xsize) {\n break; /* safety first */\n }\n ERR_IF_DATA_OOB(i + 1)\n memcpy(out + x, data + 1, i);\n data += i + 1;\n } else {\n i = data[0];\n if (x + i > state->xsize) {\n break; /* safety first */\n }\n memset(out + x, data[1], i);\n data += 2;\n }\n }\n if (x != state->xsize) {\n /* didn't unpack whole line */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n }\n break;\n case 16:\n /* COPY chunk */\n if (state->xsize > bytes / state->ysize) {\n /* not enough data for frame */\n return ptr - buf; /* bytes consumed */\n }\n for (y = 0; y < state->ysize; y++) {\n UINT8 *local_buf = (UINT8 *)im->image[y];\n memcpy(local_buf, data, state->xsize);\n data += state->xsize;\n }\n break;\n case 18:\n /* PSTAMP chunk */\n break; /* ignored */\n default:\n /* unknown chunk */\n /* printf(\"unknown FLI/FLC chunk: %d\\n\", I16(ptr+4)); */\n state->errcode = IMAGING_CODEC_UNKNOWN;\n return -1;\n }\n advance = I32(ptr);\n if (advance < 0 || advance > bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n ptr += advance;\n bytes -= advance;\n }\n\n return -1; /* end of frame */\n}", "project": "Pillow", "hash": 69735535805743995070076240386771278068, "size": 226, "commit_id": "bb6c11fb889e6c11b0ee122b828132ee763b5856", "message": "Fix FLI DOS -- CVE-2021-28676\n\n* FliDecode did not properly check that the block advance was\n non-zero, potentally leading to an infinite loop on load.\n* This dates to the PIL Fork\n* Found with oss-fuzz", "target": 1, "dataset": "other", "idx": 212350}
  920. {"func": "ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) {\n UINT8 *ptr;\n int framesize;\n int c, chunks, advance;\n int l, lines;\n int i, j, x = 0, y, ymax;\n\n /* If not even the chunk size is present, we'd better leave */\n\n if (bytes < 4) {\n return 0;\n }\n\n /* We don't decode anything unless we have a full chunk in the\n input buffer */\n\n ptr = buf;\n\n framesize = I32(ptr);\n if (framesize < I32(ptr)) {\n return 0;\n }\n\n /* Make sure this is a frame chunk. The Python driver takes\n case of other chunk types. */\n\n if (bytes < 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n if (I16(ptr + 4) != 0xF1FA) {\n state->errcode = IMAGING_CODEC_UNKNOWN;\n return -1;\n }\n\n chunks = I16(ptr + 6);\n ptr += 16;\n bytes -= 16;\n\n /* Process subchunks */\n for (c = 0; c < chunks; c++) {\n UINT8 *data;\n if (bytes < 10) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n data = ptr + 6;\n switch (I16(ptr + 4)) {\n case 4:\n case 11:\n /* FLI COLOR chunk */\n break; /* ignored; handled by Python code */\n case 7:\n /* FLI SS2 chunk (word delta) */\n /* OOB ok, we've got 4 bytes min on entry */\n lines = I16(data);\n data += 2;\n for (l = y = 0; l < lines && y < state->ysize; l++, y++) {\n UINT8 *local_buf = (UINT8 *)im->image[y];\n int p, packets;\n ERR_IF_DATA_OOB(2)\n packets = I16(data);\n data += 2;\n while (packets & 0x8000) {\n /* flag word */\n if (packets & 0x4000) {\n y += 65536 - packets; /* skip lines */\n if (y >= state->ysize) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n local_buf = (UINT8 *)im->image[y];\n } else {\n /* store last byte (used if line width is odd) */\n local_buf[state->xsize - 1] = (UINT8)packets;\n }\n ERR_IF_DATA_OOB(2)\n packets = I16(data);\n data += 2;\n }\n for (p = x = 0; p < packets; p++) {\n ERR_IF_DATA_OOB(2)\n x += data[0]; /* pixel skip */\n if (data[1] >= 128) {\n ERR_IF_DATA_OOB(4)\n i = 256 - data[1]; /* run */\n if (x + i + i > state->xsize) {\n break;\n }\n for (j = 0; j < i; j++) {\n local_buf[x++] = data[2];\n local_buf[x++] = data[3];\n }\n data += 2 + 2;\n } else {\n i = 2 * (int)data[1]; /* chunk */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(2 + i)\n memcpy(local_buf + x, data + 2, i);\n data += 2 + i;\n x += i;\n }\n }\n if (p < packets) {\n break; /* didn't process all packets */\n }\n }\n if (l < lines) {\n /* didn't process all lines */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n break;\n case 12:\n /* FLI LC chunk (byte delta) */\n /* OOB Check ok, we have 4 bytes min here */\n y = I16(data);\n ymax = y + I16(data + 2);\n data += 4;\n for (; y < ymax && y < state->ysize; y++) {\n UINT8 *out = (UINT8 *)im->image[y];\n ERR_IF_DATA_OOB(1)\n int p, packets = *data++;\n for (p = x = 0; p < packets; p++, x += i) {\n ERR_IF_DATA_OOB(2)\n x += data[0]; /* skip pixels */\n if (data[1] & 0x80) {\n i = 256 - data[1]; /* run */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(3)\n memset(out + x, data[2], i);\n data += 3;\n } else {\n i = data[1]; /* chunk */\n if (x + i > state->xsize) {\n break;\n }\n ERR_IF_DATA_OOB(2 + i)\n memcpy(out + x, data + 2, i);\n data += i + 2;\n }\n }\n if (p < packets) {\n break; /* didn't process all packets */\n }\n }\n if (y < ymax) {\n /* didn't process all lines */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n break;\n case 13:\n /* FLI BLACK chunk */\n for (y = 0; y < state->ysize; y++) {\n memset(im->image[y], 0, state->xsize);\n }\n break;\n case 15:\n /* FLI BRUN chunk */\n /* OOB, ok, we've got 4 bytes min on entry */\n for (y = 0; y < state->ysize; y++) {\n UINT8 *out = (UINT8 *)im->image[y];\n data += 1; /* ignore packetcount byte */\n for (x = 0; x < state->xsize; x += i) {\n ERR_IF_DATA_OOB(2)\n if (data[0] & 0x80) {\n i = 256 - data[0];\n if (x + i > state->xsize) {\n break; /* safety first */\n }\n ERR_IF_DATA_OOB(i + 1)\n memcpy(out + x, data + 1, i);\n data += i + 1;\n } else {\n i = data[0];\n if (x + i > state->xsize) {\n break; /* safety first */\n }\n memset(out + x, data[1], i);\n data += 2;\n }\n }\n if (x != state->xsize) {\n /* didn't unpack whole line */\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n }\n break;\n case 16:\n /* COPY chunk */\n if (state->xsize > bytes / state->ysize) {\n /* not enough data for frame */\n return ptr - buf; /* bytes consumed */\n }\n for (y = 0; y < state->ysize; y++) {\n UINT8 *local_buf = (UINT8 *)im->image[y];\n memcpy(local_buf, data, state->xsize);\n data += state->xsize;\n }\n break;\n case 18:\n /* PSTAMP chunk */\n break; /* ignored */\n default:\n /* unknown chunk */\n /* printf(\"unknown FLI/FLC chunk: %d\\n\", I16(ptr+4)); */\n state->errcode = IMAGING_CODEC_UNKNOWN;\n return -1;\n }\n advance = I32(ptr);\n if (advance == 0 ) {\n // If there's no advance, we're in in infinite loop\n state->errcode = IMAGING_CODEC_BROKEN;\n return -1;\n }\n if (advance < 0 || advance > bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n ptr += advance;\n bytes -= advance;\n }\n\n return -1; /* end of frame */\n}", "project": "Pillow", "hash": 182488442401888661255544724253647090404, "size": 231, "commit_id": "bb6c11fb889e6c11b0ee122b828132ee763b5856", "message": "Fix FLI DOS -- CVE-2021-28676\n\n* FliDecode did not properly check that the block advance was\n non-zero, potentally leading to an infinite loop on load.\n* This dates to the PIL Fork\n* Found with oss-fuzz", "target": 0, "dataset": "other", "idx": 458011}
  921. {"func": "int vt_ioctl(struct tty_struct *tty,\n\t unsigned int cmd, unsigned long arg)\n{\n\tstruct vc_data *vc = tty->driver_data;\n\tstruct console_font_op op;\t/* used in multiple places here */\n\tunsigned int console;\n\tunsigned char ucval;\n\tunsigned int uival;\n\tvoid __user *up = (void __user *)arg;\n\tint i, perm;\n\tint ret = 0;\n\n\tconsole = vc->vc_num;\n\n\n\tif (!vc_cons_allocated(console)) { \t/* impossible? */\n\t\tret = -ENOIOCTLCMD;\n\t\tgoto out;\n\t}\n\n\n\t/*\n\t * To have permissions to do most of the vt ioctls, we either have\n\t * to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.\n\t */\n\tperm = 0;\n\tif (current->signal->tty == tty || capable(CAP_SYS_TTY_CONFIG))\n\t\tperm = 1;\n \n\tswitch (cmd) {\n\tcase TIOCLINUX:\n\t\tret = tioclinux(tty, arg);\n\t\tbreak;\n\tcase KIOCSOUND:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\t/*\n\t\t * The use of PIT_TICK_RATE is historic, it used to be\n\t\t * the platform-dependent CLOCK_TICK_RATE between 2.6.12\n\t\t * and 2.6.36, which was a minor but unfortunate ABI\n\t\t * change. kd_mksound is locked by the input layer.\n\t\t */\n\t\tif (arg)\n\t\t\targ = PIT_TICK_RATE / arg;\n\t\tkd_mksound(arg, 0);\n\t\tbreak;\n\n\tcase KDMKTONE:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t{\n\t\tunsigned int ticks, count;\n\t\t\n\t\t/*\n\t\t * Generate the tone for the appropriate number of ticks.\n\t\t * If the time is zero, turn off sound ourselves.\n\t\t */\n\t\tticks = msecs_to_jiffies((arg >> 16) & 0xffff);\n\t\tcount = ticks ? (arg & 0xffff) : 0;\n\t\tif (count)\n\t\t\tcount = PIT_TICK_RATE / count;\n\t\tkd_mksound(count, ticks);\n\t\tbreak;\n\t}\n\n\tcase KDGKBTYPE:\n\t\t/*\n\t\t * this is na\u00efve.\n\t\t */\n\t\tucval = KB_101;\n\t\tret = put_user(ucval, (char __user *)arg);\n\t\tbreak;\n\n\t\t/*\n\t\t * These cannot be implemented on any machine that implements\n\t\t * ioperm() in user level (such as Alpha PCs) or not at all.\n\t\t *\n\t\t * XXX: you should never use these, just call ioperm directly..\n\t\t */\n#ifdef CONFIG_X86\n\tcase KDADDIO:\n\tcase KDDELIO:\n\t\t/*\n\t\t * KDADDIO and KDDELIO may be able to add ports beyond what\n\t\t * we reject here, but to be safe...\n\t\t *\n\t\t * These are locked internally via sys_ioperm\n\t\t */\n\t\tif (arg < GPFIRST || arg > GPLAST) {\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tret = ksys_ioperm(arg, 1, (cmd == KDADDIO)) ? -ENXIO : 0;\n\t\tbreak;\n\n\tcase KDENABIO:\n\tcase KDDISABIO:\n\t\tret = ksys_ioperm(GPFIRST, GPNUM,\n\t\t\t\t (cmd == KDENABIO)) ? -ENXIO : 0;\n\t\tbreak;\n#endif\n\n\t/* Linux m68k/i386 interface for setting the keyboard delay/repeat rate */\n\t\t\n\tcase KDKBDREP:\n\t{\n\t\tstruct kbd_repeat kbrep;\n\t\t\n\t\tif (!capable(CAP_SYS_TTY_CONFIG))\n\t\t\treturn -EPERM;\n\n\t\tif (copy_from_user(&kbrep, up, sizeof(struct kbd_repeat))) {\n\t\t\tret = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\tret = kbd_rate(&kbrep);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tif (copy_to_user(up, &kbrep, sizeof(struct kbd_repeat)))\n\t\t\tret = -EFAULT;\n\t\tbreak;\n\t}\n\n\tcase KDSETMODE:\n\t\t/*\n\t\t * currently, setting the mode from KD_TEXT to KD_GRAPHICS\n\t\t * doesn't do a whole lot. i'm not sure if it should do any\n\t\t * restoration of modes or what...\n\t\t *\n\t\t * XXX It should at least call into the driver, fbdev's definitely\n\t\t * need to restore their engine state. --BenH\n\t\t */\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tswitch (arg) {\n\t\tcase KD_GRAPHICS:\n\t\t\tbreak;\n\t\tcase KD_TEXT0:\n\t\tcase KD_TEXT1:\n\t\t\targ = KD_TEXT;\n\t\tcase KD_TEXT:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tret = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t\t/* FIXME: this needs the console lock extending */\n\t\tif (vc->vc_mode == (unsigned char) arg)\n\t\t\tbreak;\n\t\tvc->vc_mode = (unsigned char) arg;\n\t\tif (console != fg_console)\n\t\t\tbreak;\n\t\t/*\n\t\t * explicitly blank/unblank the screen if switching modes\n\t\t */\n\t\tconsole_lock();\n\t\tif (arg == KD_TEXT)\n\t\t\tdo_unblank_screen(1);\n\t\telse\n\t\t\tdo_blank_screen(1);\n\t\tconsole_unlock();\n\t\tbreak;\n\n\tcase KDGETMODE:\n\t\tuival = vc->vc_mode;\n\t\tgoto setint;\n\n\tcase KDMAPDISP:\n\tcase KDUNMAPDISP:\n\t\t/*\n\t\t * these work like a combination of mmap and KDENABIO.\n\t\t * this could be easily finished.\n\t\t */\n\t\tret = -EINVAL;\n\t\tbreak;\n\n\tcase KDSKBMODE:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tret = vt_do_kdskbmode(console, arg);\n\t\tif (ret == 0)\n\t\t\ttty_ldisc_flush(tty);\n\t\tbreak;\n\n\tcase KDGKBMODE:\n\t\tuival = vt_do_kdgkbmode(console);\n\t\tret = put_user(uival, (int __user *)arg);\n\t\tbreak;\n\n\t/* this could be folded into KDSKBMODE, but for compatibility\n\t reasons it is not so easy to fold KDGKBMETA into KDGKBMODE */\n\tcase KDSKBMETA:\n\t\tret = vt_do_kdskbmeta(console, arg);\n\t\tbreak;\n\n\tcase KDGKBMETA:\n\t\t/* FIXME: should review whether this is worth locking */\n\t\tuival = vt_do_kdgkbmeta(console);\n\tsetint:\n\t\tret = put_user(uival, (int __user *)arg);\n\t\tbreak;\n\n\tcase KDGETKEYCODE:\n\tcase KDSETKEYCODE:\n\t\tif(!capable(CAP_SYS_TTY_CONFIG))\n\t\t\tperm = 0;\n\t\tret = vt_do_kbkeycode_ioctl(cmd, up, perm);\n\t\tbreak;\n\n\tcase KDGKBENT:\n\tcase KDSKBENT:\n\t\tret = vt_do_kdsk_ioctl(cmd, up, perm, console);\n\t\tbreak;\n\n\tcase KDGKBSENT:\n\tcase KDSKBSENT:\n\t\tret = vt_do_kdgkb_ioctl(cmd, up, perm);\n\t\tbreak;\n\n\t/* Diacritical processing. Handled in keyboard.c as it has\n\t to operate on the keyboard locks and structures */\n\tcase KDGKBDIACR:\n\tcase KDGKBDIACRUC:\n\tcase KDSKBDIACR:\n\tcase KDSKBDIACRUC:\n\t\tret = vt_do_diacrit(cmd, up, perm);\n\t\tbreak;\n\n\t/* the ioctls below read/set the flags usually shown in the leds */\n\t/* don't use them - they will go away without warning */\n\tcase KDGKBLED:\n\tcase KDSKBLED:\n\tcase KDGETLED:\n\tcase KDSETLED:\n\t\tret = vt_do_kdskled(console, cmd, arg, perm);\n\t\tbreak;\n\n\t/*\n\t * A process can indicate its willingness to accept signals\n\t * generated by pressing an appropriate key combination.\n\t * Thus, one can have a daemon that e.g. spawns a new console\n\t * upon a keypress and then changes to it.\n\t * See also the kbrequest field of inittab(5).\n\t */\n\tcase KDSIGACCEPT:\n\t{\n\t\tif (!perm || !capable(CAP_KILL))\n\t\t\treturn -EPERM;\n\t\tif (!valid_signal(arg) || arg < 1 || arg == SIGKILL)\n\t\t\tret = -EINVAL;\n\t\telse {\n\t\t\tspin_lock_irq(&vt_spawn_con.lock);\n\t\t\tput_pid(vt_spawn_con.pid);\n\t\t\tvt_spawn_con.pid = get_pid(task_pid(current));\n\t\t\tvt_spawn_con.sig = arg;\n\t\t\tspin_unlock_irq(&vt_spawn_con.lock);\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase VT_SETMODE:\n\t{\n\t\tstruct vt_mode tmp;\n\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (copy_from_user(&tmp, up, sizeof(struct vt_mode))) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto out;\n\t\t}\n\t\tif (tmp.mode != VT_AUTO && tmp.mode != VT_PROCESS) {\n\t\t\tret = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t\tconsole_lock();\n\t\tvc->vt_mode = tmp;\n\t\t/* the frsig is ignored, so we set it to 0 */\n\t\tvc->vt_mode.frsig = 0;\n\t\tput_pid(vc->vt_pid);\n\t\tvc->vt_pid = get_pid(task_pid(current));\n\t\t/* no switch is required -- saw@shade.msu.ru */\n\t\tvc->vt_newvt = -1;\n\t\tconsole_unlock();\n\t\tbreak;\n\t}\n\n\tcase VT_GETMODE:\n\t{\n\t\tstruct vt_mode tmp;\n\t\tint rc;\n\n\t\tconsole_lock();\n\t\tmemcpy(&tmp, &vc->vt_mode, sizeof(struct vt_mode));\n\t\tconsole_unlock();\n\n\t\trc = copy_to_user(up, &tmp, sizeof(struct vt_mode));\n\t\tif (rc)\n\t\t\tret = -EFAULT;\n\t\tbreak;\n\t}\n\n\t/*\n\t * Returns global vt state. Note that VT 0 is always open, since\n\t * it's an alias for the current VT, and people can't use it here.\n\t * We cannot return state for more than 16 VTs, since v_state is short.\n\t */\n\tcase VT_GETSTATE:\n\t{\n\t\tstruct vt_stat __user *vtstat = up;\n\t\tunsigned short state, mask;\n\n\t\t/* Review: FIXME: Console lock ? */\n\t\tif (put_user(fg_console + 1, &vtstat->v_active))\n\t\t\tret = -EFAULT;\n\t\telse {\n\t\t\tstate = 1;\t/* /dev/tty0 is always open */\n\t\t\tfor (i = 0, mask = 2; i < MAX_NR_CONSOLES && mask;\n\t\t\t\t\t\t\t++i, mask <<= 1)\n\t\t\t\tif (VT_IS_IN_USE(i))\n\t\t\t\t\tstate |= mask;\n\t\t\tret = put_user(state, &vtstat->v_state);\n\t\t}\n\t\tbreak;\n\t}\n\n\t/*\n\t * Returns the first available (non-opened) console.\n\t */\n\tcase VT_OPENQRY:\n\t\t/* FIXME: locking ? - but then this is a stupid API */\n\t\tfor (i = 0; i < MAX_NR_CONSOLES; ++i)\n\t\t\tif (! VT_IS_IN_USE(i))\n\t\t\t\tbreak;\n\t\tuival = i < MAX_NR_CONSOLES ? (i+1) : -1;\n\t\tgoto setint;\t\t \n\n\t/*\n\t * ioctl(fd, VT_ACTIVATE, num) will cause us to switch to vt # num,\n\t * with num >= 1 (switches to vt 0, our console, are not allowed, just\n\t * to preserve sanity).\n\t */\n\tcase VT_ACTIVATE:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (arg == 0 || arg > MAX_NR_CONSOLES)\n\t\t\tret = -ENXIO;\n\t\telse {\n\t\t\targ--;\n\t\t\tconsole_lock();\n\t\t\tret = vc_allocate(arg);\n\t\t\tconsole_unlock();\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\t\t\tset_console(arg);\n\t\t}\n\t\tbreak;\n\n\tcase VT_SETACTIVATE:\n\t{\n\t\tstruct vt_setactivate vsa;\n\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\n\t\tif (copy_from_user(&vsa, (struct vt_setactivate __user *)arg,\n\t\t\t\t\tsizeof(struct vt_setactivate))) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto out;\n\t\t}\n\t\tif (vsa.console == 0 || vsa.console > MAX_NR_CONSOLES)\n\t\t\tret = -ENXIO;\n\t\telse {\n\t\t\tvsa.console = array_index_nospec(vsa.console,\n\t\t\t\t\t\t\t MAX_NR_CONSOLES + 1);\n\t\t\tvsa.console--;\n\t\t\tconsole_lock();\n\t\t\tret = vc_allocate(vsa.console);\n\t\t\tif (ret == 0) {\n\t\t\t\tstruct vc_data *nvc;\n\t\t\t\t/* This is safe providing we don't drop the\n\t\t\t\t console sem between vc_allocate and\n\t\t\t\t finishing referencing nvc */\n\t\t\t\tnvc = vc_cons[vsa.console].d;\n\t\t\t\tnvc->vt_mode = vsa.mode;\n\t\t\t\tnvc->vt_mode.frsig = 0;\n\t\t\t\tput_pid(nvc->vt_pid);\n\t\t\t\tnvc->vt_pid = get_pid(task_pid(current));\n\t\t\t}\n\t\t\tconsole_unlock();\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\t\t\t/* Commence switch and lock */\n\t\t\t/* Review set_console locks */\n\t\t\tset_console(vsa.console);\n\t\t}\n\t\tbreak;\n\t}\n\n\t/*\n\t * wait until the specified VT has been activated\n\t */\n\tcase VT_WAITACTIVE:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (arg == 0 || arg > MAX_NR_CONSOLES)\n\t\t\tret = -ENXIO;\n\t\telse\n\t\t\tret = vt_waitactive(arg);\n\t\tbreak;\n\n\t/*\n\t * If a vt is under process control, the kernel will not switch to it\n\t * immediately, but postpone the operation until the process calls this\n\t * ioctl, allowing the switch to complete.\n\t *\n\t * According to the X sources this is the behavior:\n\t *\t0:\tpending switch-from not OK\n\t *\t1:\tpending switch-from OK\n\t *\t2:\tcompleted switch-to OK\n\t */\n\tcase VT_RELDISP:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\n\t\tconsole_lock();\n\t\tif (vc->vt_mode.mode != VT_PROCESS) {\n\t\t\tconsole_unlock();\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\t/*\n\t\t * Switching-from response\n\t\t */\n\t\tif (vc->vt_newvt >= 0) {\n\t\t\tif (arg == 0)\n\t\t\t\t/*\n\t\t\t\t * Switch disallowed, so forget we were trying\n\t\t\t\t * to do it.\n\t\t\t\t */\n\t\t\t\tvc->vt_newvt = -1;\n\n\t\t\telse {\n\t\t\t\t/*\n\t\t\t\t * The current vt has been released, so\n\t\t\t\t * complete the switch.\n\t\t\t\t */\n\t\t\t\tint newvt;\n\t\t\t\tnewvt = vc->vt_newvt;\n\t\t\t\tvc->vt_newvt = -1;\n\t\t\t\tret = vc_allocate(newvt);\n\t\t\t\tif (ret) {\n\t\t\t\t\tconsole_unlock();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * When we actually do the console switch,\n\t\t\t\t * make sure we are atomic with respect to\n\t\t\t\t * other console switches..\n\t\t\t\t */\n\t\t\t\tcomplete_change_console(vc_cons[newvt].d);\n\t\t\t}\n\t\t} else {\n\t\t\t/*\n\t\t\t * Switched-to response\n\t\t\t */\n\t\t\t/*\n\t\t\t * If it's just an ACK, ignore it\n\t\t\t */\n\t\t\tif (arg != VT_ACKACQ)\n\t\t\t\tret = -EINVAL;\n\t\t}\n\t\tconsole_unlock();\n\t\tbreak;\n\n\t /*\n\t * Disallocate memory associated to VT (but leave VT1)\n\t */\n\t case VT_DISALLOCATE:\n\t\tif (arg > MAX_NR_CONSOLES) {\n\t\t\tret = -ENXIO;\n\t\t\tbreak;\n\t\t}\n\t\tif (arg == 0)\n\t\t\tvt_disallocate_all();\n\t\telse\n\t\t\tret = vt_disallocate(--arg);\n\t\tbreak;\n\n\tcase VT_RESIZE:\n\t{\n\t\tstruct vt_sizes __user *vtsizes = up;\n\t\tstruct vc_data *vc;\n\n\t\tushort ll,cc;\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (get_user(ll, &vtsizes->v_rows) ||\n\t\t get_user(cc, &vtsizes->v_cols))\n\t\t\tret = -EFAULT;\n\t\telse {\n\t\t\tconsole_lock();\n\t\t\tfor (i = 0; i < MAX_NR_CONSOLES; i++) {\n\t\t\t\tvc = vc_cons[i].d;\n\n\t\t\t\tif (vc) {\n\t\t\t\t\tvc->vc_resize_user = 1;\n\t\t\t\t\t/* FIXME: review v tty lock */\n\t\t\t\t\tvc_resize(vc_cons[i].d, cc, ll);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconsole_unlock();\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase VT_RESIZEX:\n\t{\n\t\tstruct vt_consize v;\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (copy_from_user(&v, up, sizeof(struct vt_consize)))\n\t\t\treturn -EFAULT;\n\t\t/* FIXME: Should check the copies properly */\n\t\tif (!v.v_vlin)\n\t\t\tv.v_vlin = vc->vc_scan_lines;\n\t\tif (v.v_clin) {\n\t\t\tint rows = v.v_vlin/v.v_clin;\n\t\t\tif (v.v_rows != rows) {\n\t\t\t\tif (v.v_rows) /* Parameters don't add up */\n\t\t\t\t\treturn -EINVAL;\n\t\t\t\tv.v_rows = rows;\n\t\t\t}\n\t\t}\n\t\tif (v.v_vcol && v.v_ccol) {\n\t\t\tint cols = v.v_vcol/v.v_ccol;\n\t\t\tif (v.v_cols != cols) {\n\t\t\t\tif (v.v_cols)\n\t\t\t\t\treturn -EINVAL;\n\t\t\t\tv.v_cols = cols;\n\t\t\t}\n\t\t}\n\n\t\tif (v.v_clin > 32)\n\t\t\treturn -EINVAL;\n\n\t\tfor (i = 0; i < MAX_NR_CONSOLES; i++) {\n\t\t\tif (!vc_cons[i].d)\n\t\t\t\tcontinue;\n\t\t\tconsole_lock();\n\t\t\tif (v.v_vlin)\n\t\t\t\tvc_cons[i].d->vc_scan_lines = v.v_vlin;\n\t\t\tif (v.v_clin)\n\t\t\t\tvc_cons[i].d->vc_font.height = v.v_clin;\n\t\t\tvc_cons[i].d->vc_resize_user = 1;\n\t\t\tvc_resize(vc_cons[i].d, v.v_cols, v.v_rows);\n\t\t\tconsole_unlock();\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase PIO_FONT: {\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\top.op = KD_FONT_OP_SET;\n\t\top.flags = KD_FONT_FLAG_OLD | KD_FONT_FLAG_DONT_RECALC;\t/* Compatibility */\n\t\top.width = 8;\n\t\top.height = 0;\n\t\top.charcount = 256;\n\t\top.data = up;\n\t\tret = con_font_op(vc_cons[fg_console].d, &op);\n\t\tbreak;\n\t}\n\n\tcase GIO_FONT: {\n\t\top.op = KD_FONT_OP_GET;\n\t\top.flags = KD_FONT_FLAG_OLD;\n\t\top.width = 8;\n\t\top.height = 32;\n\t\top.charcount = 256;\n\t\top.data = up;\n\t\tret = con_font_op(vc_cons[fg_console].d, &op);\n\t\tbreak;\n\t}\n\n\tcase PIO_CMAP:\n if (!perm)\n\t\t\tret = -EPERM;\n\t\telse\n\t ret = con_set_cmap(up);\n\t\tbreak;\n\n\tcase GIO_CMAP:\n ret = con_get_cmap(up);\n\t\tbreak;\n\n\tcase PIO_FONTX:\n\tcase GIO_FONTX:\n\t\tret = do_fontx_ioctl(cmd, up, perm, &op);\n\t\tbreak;\n\n\tcase PIO_FONTRESET:\n\t{\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\n#ifdef BROKEN_GRAPHICS_PROGRAMS\n\t\t/* With BROKEN_GRAPHICS_PROGRAMS defined, the default\n\t\t font is not saved. */\n\t\tret = -ENOSYS;\n\t\tbreak;\n#else\n\t\t{\n\t\top.op = KD_FONT_OP_SET_DEFAULT;\n\t\top.data = NULL;\n\t\tret = con_font_op(vc_cons[fg_console].d, &op);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tconsole_lock();\n\t\tcon_set_default_unimap(vc_cons[fg_console].d);\n\t\tconsole_unlock();\n\t\tbreak;\n\t\t}\n#endif\n\t}\n\n\tcase KDFONTOP: {\n\t\tif (copy_from_user(&op, up, sizeof(op))) {\n\t\t\tret = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\tif (!perm && op.op != KD_FONT_OP_GET)\n\t\t\treturn -EPERM;\n\t\tret = con_font_op(vc, &op);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tif (copy_to_user(up, &op, sizeof(op)))\n\t\t\tret = -EFAULT;\n\t\tbreak;\n\t}\n\n\tcase PIO_SCRNMAP:\n\t\tif (!perm)\n\t\t\tret = -EPERM;\n\t\telse\n\t\t\tret = con_set_trans_old(up);\n\t\tbreak;\n\n\tcase GIO_SCRNMAP:\n\t\tret = con_get_trans_old(up);\n\t\tbreak;\n\n\tcase PIO_UNISCRNMAP:\n\t\tif (!perm)\n\t\t\tret = -EPERM;\n\t\telse\n\t\t\tret = con_set_trans_new(up);\n\t\tbreak;\n\n\tcase GIO_UNISCRNMAP:\n\t\tret = con_get_trans_new(up);\n\t\tbreak;\n\n\tcase PIO_UNIMAPCLR:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tcon_clear_unimap(vc);\n\t\tbreak;\n\n\tcase PIO_UNIMAP:\n\tcase GIO_UNIMAP:\n\t\tret = do_unimap_ioctl(cmd, up, perm, vc);\n\t\tbreak;\n\n\tcase VT_LOCKSWITCH:\n\t\tif (!capable(CAP_SYS_TTY_CONFIG))\n\t\t\treturn -EPERM;\n\t\tvt_dont_switch = 1;\n\t\tbreak;\n\tcase VT_UNLOCKSWITCH:\n\t\tif (!capable(CAP_SYS_TTY_CONFIG))\n\t\t\treturn -EPERM;\n\t\tvt_dont_switch = 0;\n\t\tbreak;\n\tcase VT_GETHIFONTMASK:\n\t\tret = put_user(vc->vc_hi_font_mask,\n\t\t\t\t\t(unsigned short __user *)arg);\n\t\tbreak;\n\tcase VT_WAITEVENT:\n\t\tret = vt_event_wait_ioctl((struct vt_event __user *)arg);\n\t\tbreak;\n\tdefault:\n\t\tret = -ENOIOCTLCMD;\n\t}\nout:\n\treturn ret;\n}", "project": "linux", "hash": 215976747485693149279929143438303006406, "size": 696, "commit_id": "6cd1ed50efd88261298577cd92a14f2768eddeeb", "message": "vt: vt_ioctl: fix race in VT_RESIZEX\n\nWe need to make sure vc_cons[i].d is not NULL after grabbing\nconsole_lock(), or risk a crash.\n\ngeneral protection fault, probably for non-canonical address 0xdffffc0000000068: 0000 [#1] PREEMPT SMP KASAN\nKASAN: null-ptr-deref in range [0x0000000000000340-0x0000000000000347]\nCPU: 1 PID: 19462 Comm: syz-executor.5 Not tainted 5.5.0-syzkaller #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\nRIP: 0010:vt_ioctl+0x1f96/0x26d0 drivers/tty/vt/vt_ioctl.c:883\nCode: 74 41 e8 bd a6 84 fd 48 89 d8 48 c1 e8 03 42 80 3c 28 00 0f 85 e4 04 00 00 48 8b 03 48 8d b8 40 03 00 00 48 89 fa 48 c1 ea 03 <42> 0f b6 14 2a 84 d2 74 09 80 fa 03 0f 8e b1 05 00 00 44 89 b8 40\nRSP: 0018:ffffc900086d7bb0 EFLAGS: 00010202\nRAX: 0000000000000000 RBX: ffffffff8c34ee88 RCX: ffffc9001415c000\nRDX: 0000000000000068 RSI: ffffffff83f0e6e3 RDI: 0000000000000340\nRBP: ffffc900086d7cd0 R08: ffff888054ce0100 R09: fffffbfff16a2f6d\nR10: ffff888054ce0998 R11: ffff888054ce0100 R12: 000000000000001d\nR13: dffffc0000000000 R14: 1ffff920010daf79 R15: 000000000000ff7f\nFS: 00007f7d13c12700(0000) GS:ffff8880ae900000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 00007ffd477e3c38 CR3: 0000000095d0a000 CR4: 00000000001406e0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\nCall Trace:\n tty_ioctl+0xa37/0x14f0 drivers/tty/tty_io.c:2660\n vfs_ioctl fs/ioctl.c:47 [inline]\n ksys_ioctl+0x123/0x180 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+0xfa/0x790 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x45b399\nCode: ad b6 fb ff c3 66 2e 0f 1f 84 00 00 00 00 00 66 90 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 0f 83 7b b6 fb ff c3 66 2e 0f 1f 84 00 00 00 00\nRSP: 002b:00007f7d13c11c78 EFLAGS: 00000246 ORIG_RAX: 0000000000000010\nRAX: ffffffffffffffda RBX: 00007f7d13c126d4 RCX: 000000000045b399\nRDX: 0000000020000080 RSI: 000000000000560a RDI: 0000000000000003\nRBP: 000000000075bf20 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00000000ffffffff\nR13: 0000000000000666 R14: 00000000004c7f04 R15: 000000000075bf2c\nModules linked in:\n---[ end trace 80970faf7a67eb77 ]---\nRIP: 0010:vt_ioctl+0x1f96/0x26d0 drivers/tty/vt/vt_ioctl.c:883\nCode: 74 41 e8 bd a6 84 fd 48 89 d8 48 c1 e8 03 42 80 3c 28 00 0f 85 e4 04 00 00 48 8b 03 48 8d b8 40 03 00 00 48 89 fa 48 c1 ea 03 <42> 0f b6 14 2a 84 d2 74 09 80 fa 03 0f 8e b1 05 00 00 44 89 b8 40\nRSP: 0018:ffffc900086d7bb0 EFLAGS: 00010202\nRAX: 0000000000000000 RBX: ffffffff8c34ee88 RCX: ffffc9001415c000\nRDX: 0000000000000068 RSI: ffffffff83f0e6e3 RDI: 0000000000000340\nRBP: ffffc900086d7cd0 R08: ffff888054ce0100 R09: fffffbfff16a2f6d\nR10: ffff888054ce0998 R11: ffff888054ce0100 R12: 000000000000001d\nR13: dffffc0000000000 R14: 1ffff920010daf79 R15: 000000000000ff7f\nFS: 00007f7d13c12700(0000) GS:ffff8880ae900000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 00007ffd477e3c38 CR3: 0000000095d0a000 CR4: 00000000001406e0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Eric Dumazet <edumazet@google.com>\nCc: stable <stable@vger.kernel.org>\nReported-by: syzbot <syzkaller@googlegroups.com>\nLink: https://lore.kernel.org/r/20200210190721.200418-1-edumazet@google.com\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 1, "dataset": "other", "idx": 212365}
  922. {"func": "int vt_ioctl(struct tty_struct *tty,\n\t unsigned int cmd, unsigned long arg)\n{\n\tstruct vc_data *vc = tty->driver_data;\n\tstruct console_font_op op;\t/* used in multiple places here */\n\tunsigned int console;\n\tunsigned char ucval;\n\tunsigned int uival;\n\tvoid __user *up = (void __user *)arg;\n\tint i, perm;\n\tint ret = 0;\n\n\tconsole = vc->vc_num;\n\n\n\tif (!vc_cons_allocated(console)) { \t/* impossible? */\n\t\tret = -ENOIOCTLCMD;\n\t\tgoto out;\n\t}\n\n\n\t/*\n\t * To have permissions to do most of the vt ioctls, we either have\n\t * to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.\n\t */\n\tperm = 0;\n\tif (current->signal->tty == tty || capable(CAP_SYS_TTY_CONFIG))\n\t\tperm = 1;\n \n\tswitch (cmd) {\n\tcase TIOCLINUX:\n\t\tret = tioclinux(tty, arg);\n\t\tbreak;\n\tcase KIOCSOUND:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\t/*\n\t\t * The use of PIT_TICK_RATE is historic, it used to be\n\t\t * the platform-dependent CLOCK_TICK_RATE between 2.6.12\n\t\t * and 2.6.36, which was a minor but unfortunate ABI\n\t\t * change. kd_mksound is locked by the input layer.\n\t\t */\n\t\tif (arg)\n\t\t\targ = PIT_TICK_RATE / arg;\n\t\tkd_mksound(arg, 0);\n\t\tbreak;\n\n\tcase KDMKTONE:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t{\n\t\tunsigned int ticks, count;\n\t\t\n\t\t/*\n\t\t * Generate the tone for the appropriate number of ticks.\n\t\t * If the time is zero, turn off sound ourselves.\n\t\t */\n\t\tticks = msecs_to_jiffies((arg >> 16) & 0xffff);\n\t\tcount = ticks ? (arg & 0xffff) : 0;\n\t\tif (count)\n\t\t\tcount = PIT_TICK_RATE / count;\n\t\tkd_mksound(count, ticks);\n\t\tbreak;\n\t}\n\n\tcase KDGKBTYPE:\n\t\t/*\n\t\t * this is na\u00efve.\n\t\t */\n\t\tucval = KB_101;\n\t\tret = put_user(ucval, (char __user *)arg);\n\t\tbreak;\n\n\t\t/*\n\t\t * These cannot be implemented on any machine that implements\n\t\t * ioperm() in user level (such as Alpha PCs) or not at all.\n\t\t *\n\t\t * XXX: you should never use these, just call ioperm directly..\n\t\t */\n#ifdef CONFIG_X86\n\tcase KDADDIO:\n\tcase KDDELIO:\n\t\t/*\n\t\t * KDADDIO and KDDELIO may be able to add ports beyond what\n\t\t * we reject here, but to be safe...\n\t\t *\n\t\t * These are locked internally via sys_ioperm\n\t\t */\n\t\tif (arg < GPFIRST || arg > GPLAST) {\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tret = ksys_ioperm(arg, 1, (cmd == KDADDIO)) ? -ENXIO : 0;\n\t\tbreak;\n\n\tcase KDENABIO:\n\tcase KDDISABIO:\n\t\tret = ksys_ioperm(GPFIRST, GPNUM,\n\t\t\t\t (cmd == KDENABIO)) ? -ENXIO : 0;\n\t\tbreak;\n#endif\n\n\t/* Linux m68k/i386 interface for setting the keyboard delay/repeat rate */\n\t\t\n\tcase KDKBDREP:\n\t{\n\t\tstruct kbd_repeat kbrep;\n\t\t\n\t\tif (!capable(CAP_SYS_TTY_CONFIG))\n\t\t\treturn -EPERM;\n\n\t\tif (copy_from_user(&kbrep, up, sizeof(struct kbd_repeat))) {\n\t\t\tret = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\tret = kbd_rate(&kbrep);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tif (copy_to_user(up, &kbrep, sizeof(struct kbd_repeat)))\n\t\t\tret = -EFAULT;\n\t\tbreak;\n\t}\n\n\tcase KDSETMODE:\n\t\t/*\n\t\t * currently, setting the mode from KD_TEXT to KD_GRAPHICS\n\t\t * doesn't do a whole lot. i'm not sure if it should do any\n\t\t * restoration of modes or what...\n\t\t *\n\t\t * XXX It should at least call into the driver, fbdev's definitely\n\t\t * need to restore their engine state. --BenH\n\t\t */\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tswitch (arg) {\n\t\tcase KD_GRAPHICS:\n\t\t\tbreak;\n\t\tcase KD_TEXT0:\n\t\tcase KD_TEXT1:\n\t\t\targ = KD_TEXT;\n\t\tcase KD_TEXT:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tret = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t\t/* FIXME: this needs the console lock extending */\n\t\tif (vc->vc_mode == (unsigned char) arg)\n\t\t\tbreak;\n\t\tvc->vc_mode = (unsigned char) arg;\n\t\tif (console != fg_console)\n\t\t\tbreak;\n\t\t/*\n\t\t * explicitly blank/unblank the screen if switching modes\n\t\t */\n\t\tconsole_lock();\n\t\tif (arg == KD_TEXT)\n\t\t\tdo_unblank_screen(1);\n\t\telse\n\t\t\tdo_blank_screen(1);\n\t\tconsole_unlock();\n\t\tbreak;\n\n\tcase KDGETMODE:\n\t\tuival = vc->vc_mode;\n\t\tgoto setint;\n\n\tcase KDMAPDISP:\n\tcase KDUNMAPDISP:\n\t\t/*\n\t\t * these work like a combination of mmap and KDENABIO.\n\t\t * this could be easily finished.\n\t\t */\n\t\tret = -EINVAL;\n\t\tbreak;\n\n\tcase KDSKBMODE:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tret = vt_do_kdskbmode(console, arg);\n\t\tif (ret == 0)\n\t\t\ttty_ldisc_flush(tty);\n\t\tbreak;\n\n\tcase KDGKBMODE:\n\t\tuival = vt_do_kdgkbmode(console);\n\t\tret = put_user(uival, (int __user *)arg);\n\t\tbreak;\n\n\t/* this could be folded into KDSKBMODE, but for compatibility\n\t reasons it is not so easy to fold KDGKBMETA into KDGKBMODE */\n\tcase KDSKBMETA:\n\t\tret = vt_do_kdskbmeta(console, arg);\n\t\tbreak;\n\n\tcase KDGKBMETA:\n\t\t/* FIXME: should review whether this is worth locking */\n\t\tuival = vt_do_kdgkbmeta(console);\n\tsetint:\n\t\tret = put_user(uival, (int __user *)arg);\n\t\tbreak;\n\n\tcase KDGETKEYCODE:\n\tcase KDSETKEYCODE:\n\t\tif(!capable(CAP_SYS_TTY_CONFIG))\n\t\t\tperm = 0;\n\t\tret = vt_do_kbkeycode_ioctl(cmd, up, perm);\n\t\tbreak;\n\n\tcase KDGKBENT:\n\tcase KDSKBENT:\n\t\tret = vt_do_kdsk_ioctl(cmd, up, perm, console);\n\t\tbreak;\n\n\tcase KDGKBSENT:\n\tcase KDSKBSENT:\n\t\tret = vt_do_kdgkb_ioctl(cmd, up, perm);\n\t\tbreak;\n\n\t/* Diacritical processing. Handled in keyboard.c as it has\n\t to operate on the keyboard locks and structures */\n\tcase KDGKBDIACR:\n\tcase KDGKBDIACRUC:\n\tcase KDSKBDIACR:\n\tcase KDSKBDIACRUC:\n\t\tret = vt_do_diacrit(cmd, up, perm);\n\t\tbreak;\n\n\t/* the ioctls below read/set the flags usually shown in the leds */\n\t/* don't use them - they will go away without warning */\n\tcase KDGKBLED:\n\tcase KDSKBLED:\n\tcase KDGETLED:\n\tcase KDSETLED:\n\t\tret = vt_do_kdskled(console, cmd, arg, perm);\n\t\tbreak;\n\n\t/*\n\t * A process can indicate its willingness to accept signals\n\t * generated by pressing an appropriate key combination.\n\t * Thus, one can have a daemon that e.g. spawns a new console\n\t * upon a keypress and then changes to it.\n\t * See also the kbrequest field of inittab(5).\n\t */\n\tcase KDSIGACCEPT:\n\t{\n\t\tif (!perm || !capable(CAP_KILL))\n\t\t\treturn -EPERM;\n\t\tif (!valid_signal(arg) || arg < 1 || arg == SIGKILL)\n\t\t\tret = -EINVAL;\n\t\telse {\n\t\t\tspin_lock_irq(&vt_spawn_con.lock);\n\t\t\tput_pid(vt_spawn_con.pid);\n\t\t\tvt_spawn_con.pid = get_pid(task_pid(current));\n\t\t\tvt_spawn_con.sig = arg;\n\t\t\tspin_unlock_irq(&vt_spawn_con.lock);\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase VT_SETMODE:\n\t{\n\t\tstruct vt_mode tmp;\n\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (copy_from_user(&tmp, up, sizeof(struct vt_mode))) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto out;\n\t\t}\n\t\tif (tmp.mode != VT_AUTO && tmp.mode != VT_PROCESS) {\n\t\t\tret = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t\tconsole_lock();\n\t\tvc->vt_mode = tmp;\n\t\t/* the frsig is ignored, so we set it to 0 */\n\t\tvc->vt_mode.frsig = 0;\n\t\tput_pid(vc->vt_pid);\n\t\tvc->vt_pid = get_pid(task_pid(current));\n\t\t/* no switch is required -- saw@shade.msu.ru */\n\t\tvc->vt_newvt = -1;\n\t\tconsole_unlock();\n\t\tbreak;\n\t}\n\n\tcase VT_GETMODE:\n\t{\n\t\tstruct vt_mode tmp;\n\t\tint rc;\n\n\t\tconsole_lock();\n\t\tmemcpy(&tmp, &vc->vt_mode, sizeof(struct vt_mode));\n\t\tconsole_unlock();\n\n\t\trc = copy_to_user(up, &tmp, sizeof(struct vt_mode));\n\t\tif (rc)\n\t\t\tret = -EFAULT;\n\t\tbreak;\n\t}\n\n\t/*\n\t * Returns global vt state. Note that VT 0 is always open, since\n\t * it's an alias for the current VT, and people can't use it here.\n\t * We cannot return state for more than 16 VTs, since v_state is short.\n\t */\n\tcase VT_GETSTATE:\n\t{\n\t\tstruct vt_stat __user *vtstat = up;\n\t\tunsigned short state, mask;\n\n\t\t/* Review: FIXME: Console lock ? */\n\t\tif (put_user(fg_console + 1, &vtstat->v_active))\n\t\t\tret = -EFAULT;\n\t\telse {\n\t\t\tstate = 1;\t/* /dev/tty0 is always open */\n\t\t\tfor (i = 0, mask = 2; i < MAX_NR_CONSOLES && mask;\n\t\t\t\t\t\t\t++i, mask <<= 1)\n\t\t\t\tif (VT_IS_IN_USE(i))\n\t\t\t\t\tstate |= mask;\n\t\t\tret = put_user(state, &vtstat->v_state);\n\t\t}\n\t\tbreak;\n\t}\n\n\t/*\n\t * Returns the first available (non-opened) console.\n\t */\n\tcase VT_OPENQRY:\n\t\t/* FIXME: locking ? - but then this is a stupid API */\n\t\tfor (i = 0; i < MAX_NR_CONSOLES; ++i)\n\t\t\tif (! VT_IS_IN_USE(i))\n\t\t\t\tbreak;\n\t\tuival = i < MAX_NR_CONSOLES ? (i+1) : -1;\n\t\tgoto setint;\t\t \n\n\t/*\n\t * ioctl(fd, VT_ACTIVATE, num) will cause us to switch to vt # num,\n\t * with num >= 1 (switches to vt 0, our console, are not allowed, just\n\t * to preserve sanity).\n\t */\n\tcase VT_ACTIVATE:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (arg == 0 || arg > MAX_NR_CONSOLES)\n\t\t\tret = -ENXIO;\n\t\telse {\n\t\t\targ--;\n\t\t\tconsole_lock();\n\t\t\tret = vc_allocate(arg);\n\t\t\tconsole_unlock();\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\t\t\tset_console(arg);\n\t\t}\n\t\tbreak;\n\n\tcase VT_SETACTIVATE:\n\t{\n\t\tstruct vt_setactivate vsa;\n\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\n\t\tif (copy_from_user(&vsa, (struct vt_setactivate __user *)arg,\n\t\t\t\t\tsizeof(struct vt_setactivate))) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto out;\n\t\t}\n\t\tif (vsa.console == 0 || vsa.console > MAX_NR_CONSOLES)\n\t\t\tret = -ENXIO;\n\t\telse {\n\t\t\tvsa.console = array_index_nospec(vsa.console,\n\t\t\t\t\t\t\t MAX_NR_CONSOLES + 1);\n\t\t\tvsa.console--;\n\t\t\tconsole_lock();\n\t\t\tret = vc_allocate(vsa.console);\n\t\t\tif (ret == 0) {\n\t\t\t\tstruct vc_data *nvc;\n\t\t\t\t/* This is safe providing we don't drop the\n\t\t\t\t console sem between vc_allocate and\n\t\t\t\t finishing referencing nvc */\n\t\t\t\tnvc = vc_cons[vsa.console].d;\n\t\t\t\tnvc->vt_mode = vsa.mode;\n\t\t\t\tnvc->vt_mode.frsig = 0;\n\t\t\t\tput_pid(nvc->vt_pid);\n\t\t\t\tnvc->vt_pid = get_pid(task_pid(current));\n\t\t\t}\n\t\t\tconsole_unlock();\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\t\t\t/* Commence switch and lock */\n\t\t\t/* Review set_console locks */\n\t\t\tset_console(vsa.console);\n\t\t}\n\t\tbreak;\n\t}\n\n\t/*\n\t * wait until the specified VT has been activated\n\t */\n\tcase VT_WAITACTIVE:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (arg == 0 || arg > MAX_NR_CONSOLES)\n\t\t\tret = -ENXIO;\n\t\telse\n\t\t\tret = vt_waitactive(arg);\n\t\tbreak;\n\n\t/*\n\t * If a vt is under process control, the kernel will not switch to it\n\t * immediately, but postpone the operation until the process calls this\n\t * ioctl, allowing the switch to complete.\n\t *\n\t * According to the X sources this is the behavior:\n\t *\t0:\tpending switch-from not OK\n\t *\t1:\tpending switch-from OK\n\t *\t2:\tcompleted switch-to OK\n\t */\n\tcase VT_RELDISP:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\n\t\tconsole_lock();\n\t\tif (vc->vt_mode.mode != VT_PROCESS) {\n\t\t\tconsole_unlock();\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\t/*\n\t\t * Switching-from response\n\t\t */\n\t\tif (vc->vt_newvt >= 0) {\n\t\t\tif (arg == 0)\n\t\t\t\t/*\n\t\t\t\t * Switch disallowed, so forget we were trying\n\t\t\t\t * to do it.\n\t\t\t\t */\n\t\t\t\tvc->vt_newvt = -1;\n\n\t\t\telse {\n\t\t\t\t/*\n\t\t\t\t * The current vt has been released, so\n\t\t\t\t * complete the switch.\n\t\t\t\t */\n\t\t\t\tint newvt;\n\t\t\t\tnewvt = vc->vt_newvt;\n\t\t\t\tvc->vt_newvt = -1;\n\t\t\t\tret = vc_allocate(newvt);\n\t\t\t\tif (ret) {\n\t\t\t\t\tconsole_unlock();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * When we actually do the console switch,\n\t\t\t\t * make sure we are atomic with respect to\n\t\t\t\t * other console switches..\n\t\t\t\t */\n\t\t\t\tcomplete_change_console(vc_cons[newvt].d);\n\t\t\t}\n\t\t} else {\n\t\t\t/*\n\t\t\t * Switched-to response\n\t\t\t */\n\t\t\t/*\n\t\t\t * If it's just an ACK, ignore it\n\t\t\t */\n\t\t\tif (arg != VT_ACKACQ)\n\t\t\t\tret = -EINVAL;\n\t\t}\n\t\tconsole_unlock();\n\t\tbreak;\n\n\t /*\n\t * Disallocate memory associated to VT (but leave VT1)\n\t */\n\t case VT_DISALLOCATE:\n\t\tif (arg > MAX_NR_CONSOLES) {\n\t\t\tret = -ENXIO;\n\t\t\tbreak;\n\t\t}\n\t\tif (arg == 0)\n\t\t\tvt_disallocate_all();\n\t\telse\n\t\t\tret = vt_disallocate(--arg);\n\t\tbreak;\n\n\tcase VT_RESIZE:\n\t{\n\t\tstruct vt_sizes __user *vtsizes = up;\n\t\tstruct vc_data *vc;\n\n\t\tushort ll,cc;\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (get_user(ll, &vtsizes->v_rows) ||\n\t\t get_user(cc, &vtsizes->v_cols))\n\t\t\tret = -EFAULT;\n\t\telse {\n\t\t\tconsole_lock();\n\t\t\tfor (i = 0; i < MAX_NR_CONSOLES; i++) {\n\t\t\t\tvc = vc_cons[i].d;\n\n\t\t\t\tif (vc) {\n\t\t\t\t\tvc->vc_resize_user = 1;\n\t\t\t\t\t/* FIXME: review v tty lock */\n\t\t\t\t\tvc_resize(vc_cons[i].d, cc, ll);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconsole_unlock();\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase VT_RESIZEX:\n\t{\n\t\tstruct vt_consize v;\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tif (copy_from_user(&v, up, sizeof(struct vt_consize)))\n\t\t\treturn -EFAULT;\n\t\t/* FIXME: Should check the copies properly */\n\t\tif (!v.v_vlin)\n\t\t\tv.v_vlin = vc->vc_scan_lines;\n\t\tif (v.v_clin) {\n\t\t\tint rows = v.v_vlin/v.v_clin;\n\t\t\tif (v.v_rows != rows) {\n\t\t\t\tif (v.v_rows) /* Parameters don't add up */\n\t\t\t\t\treturn -EINVAL;\n\t\t\t\tv.v_rows = rows;\n\t\t\t}\n\t\t}\n\t\tif (v.v_vcol && v.v_ccol) {\n\t\t\tint cols = v.v_vcol/v.v_ccol;\n\t\t\tif (v.v_cols != cols) {\n\t\t\t\tif (v.v_cols)\n\t\t\t\t\treturn -EINVAL;\n\t\t\t\tv.v_cols = cols;\n\t\t\t}\n\t\t}\n\n\t\tif (v.v_clin > 32)\n\t\t\treturn -EINVAL;\n\n\t\tfor (i = 0; i < MAX_NR_CONSOLES; i++) {\n\t\t\tstruct vc_data *vcp;\n\n\t\t\tif (!vc_cons[i].d)\n\t\t\t\tcontinue;\n\t\t\tconsole_lock();\n\t\t\tvcp = vc_cons[i].d;\n\t\t\tif (vcp) {\n\t\t\t\tif (v.v_vlin)\n\t\t\t\t\tvcp->vc_scan_lines = v.v_vlin;\n\t\t\t\tif (v.v_clin)\n\t\t\t\t\tvcp->vc_font.height = v.v_clin;\n\t\t\t\tvcp->vc_resize_user = 1;\n\t\t\t\tvc_resize(vcp, v.v_cols, v.v_rows);\n\t\t\t}\n\t\t\tconsole_unlock();\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase PIO_FONT: {\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\top.op = KD_FONT_OP_SET;\n\t\top.flags = KD_FONT_FLAG_OLD | KD_FONT_FLAG_DONT_RECALC;\t/* Compatibility */\n\t\top.width = 8;\n\t\top.height = 0;\n\t\top.charcount = 256;\n\t\top.data = up;\n\t\tret = con_font_op(vc_cons[fg_console].d, &op);\n\t\tbreak;\n\t}\n\n\tcase GIO_FONT: {\n\t\top.op = KD_FONT_OP_GET;\n\t\top.flags = KD_FONT_FLAG_OLD;\n\t\top.width = 8;\n\t\top.height = 32;\n\t\top.charcount = 256;\n\t\top.data = up;\n\t\tret = con_font_op(vc_cons[fg_console].d, &op);\n\t\tbreak;\n\t}\n\n\tcase PIO_CMAP:\n if (!perm)\n\t\t\tret = -EPERM;\n\t\telse\n\t ret = con_set_cmap(up);\n\t\tbreak;\n\n\tcase GIO_CMAP:\n ret = con_get_cmap(up);\n\t\tbreak;\n\n\tcase PIO_FONTX:\n\tcase GIO_FONTX:\n\t\tret = do_fontx_ioctl(cmd, up, perm, &op);\n\t\tbreak;\n\n\tcase PIO_FONTRESET:\n\t{\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\n#ifdef BROKEN_GRAPHICS_PROGRAMS\n\t\t/* With BROKEN_GRAPHICS_PROGRAMS defined, the default\n\t\t font is not saved. */\n\t\tret = -ENOSYS;\n\t\tbreak;\n#else\n\t\t{\n\t\top.op = KD_FONT_OP_SET_DEFAULT;\n\t\top.data = NULL;\n\t\tret = con_font_op(vc_cons[fg_console].d, &op);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tconsole_lock();\n\t\tcon_set_default_unimap(vc_cons[fg_console].d);\n\t\tconsole_unlock();\n\t\tbreak;\n\t\t}\n#endif\n\t}\n\n\tcase KDFONTOP: {\n\t\tif (copy_from_user(&op, up, sizeof(op))) {\n\t\t\tret = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\tif (!perm && op.op != KD_FONT_OP_GET)\n\t\t\treturn -EPERM;\n\t\tret = con_font_op(vc, &op);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tif (copy_to_user(up, &op, sizeof(op)))\n\t\t\tret = -EFAULT;\n\t\tbreak;\n\t}\n\n\tcase PIO_SCRNMAP:\n\t\tif (!perm)\n\t\t\tret = -EPERM;\n\t\telse\n\t\t\tret = con_set_trans_old(up);\n\t\tbreak;\n\n\tcase GIO_SCRNMAP:\n\t\tret = con_get_trans_old(up);\n\t\tbreak;\n\n\tcase PIO_UNISCRNMAP:\n\t\tif (!perm)\n\t\t\tret = -EPERM;\n\t\telse\n\t\t\tret = con_set_trans_new(up);\n\t\tbreak;\n\n\tcase GIO_UNISCRNMAP:\n\t\tret = con_get_trans_new(up);\n\t\tbreak;\n\n\tcase PIO_UNIMAPCLR:\n\t\tif (!perm)\n\t\t\treturn -EPERM;\n\t\tcon_clear_unimap(vc);\n\t\tbreak;\n\n\tcase PIO_UNIMAP:\n\tcase GIO_UNIMAP:\n\t\tret = do_unimap_ioctl(cmd, up, perm, vc);\n\t\tbreak;\n\n\tcase VT_LOCKSWITCH:\n\t\tif (!capable(CAP_SYS_TTY_CONFIG))\n\t\t\treturn -EPERM;\n\t\tvt_dont_switch = 1;\n\t\tbreak;\n\tcase VT_UNLOCKSWITCH:\n\t\tif (!capable(CAP_SYS_TTY_CONFIG))\n\t\t\treturn -EPERM;\n\t\tvt_dont_switch = 0;\n\t\tbreak;\n\tcase VT_GETHIFONTMASK:\n\t\tret = put_user(vc->vc_hi_font_mask,\n\t\t\t\t\t(unsigned short __user *)arg);\n\t\tbreak;\n\tcase VT_WAITEVENT:\n\t\tret = vt_event_wait_ioctl((struct vt_event __user *)arg);\n\t\tbreak;\n\tdefault:\n\t\tret = -ENOIOCTLCMD;\n\t}\nout:\n\treturn ret;\n}", "project": "linux", "hash": 188901637298738474521041844492795398881, "size": 701, "commit_id": "6cd1ed50efd88261298577cd92a14f2768eddeeb", "message": "vt: vt_ioctl: fix race in VT_RESIZEX\n\nWe need to make sure vc_cons[i].d is not NULL after grabbing\nconsole_lock(), or risk a crash.\n\ngeneral protection fault, probably for non-canonical address 0xdffffc0000000068: 0000 [#1] PREEMPT SMP KASAN\nKASAN: null-ptr-deref in range [0x0000000000000340-0x0000000000000347]\nCPU: 1 PID: 19462 Comm: syz-executor.5 Not tainted 5.5.0-syzkaller #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\nRIP: 0010:vt_ioctl+0x1f96/0x26d0 drivers/tty/vt/vt_ioctl.c:883\nCode: 74 41 e8 bd a6 84 fd 48 89 d8 48 c1 e8 03 42 80 3c 28 00 0f 85 e4 04 00 00 48 8b 03 48 8d b8 40 03 00 00 48 89 fa 48 c1 ea 03 <42> 0f b6 14 2a 84 d2 74 09 80 fa 03 0f 8e b1 05 00 00 44 89 b8 40\nRSP: 0018:ffffc900086d7bb0 EFLAGS: 00010202\nRAX: 0000000000000000 RBX: ffffffff8c34ee88 RCX: ffffc9001415c000\nRDX: 0000000000000068 RSI: ffffffff83f0e6e3 RDI: 0000000000000340\nRBP: ffffc900086d7cd0 R08: ffff888054ce0100 R09: fffffbfff16a2f6d\nR10: ffff888054ce0998 R11: ffff888054ce0100 R12: 000000000000001d\nR13: dffffc0000000000 R14: 1ffff920010daf79 R15: 000000000000ff7f\nFS: 00007f7d13c12700(0000) GS:ffff8880ae900000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 00007ffd477e3c38 CR3: 0000000095d0a000 CR4: 00000000001406e0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\nCall Trace:\n tty_ioctl+0xa37/0x14f0 drivers/tty/tty_io.c:2660\n vfs_ioctl fs/ioctl.c:47 [inline]\n ksys_ioctl+0x123/0x180 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+0xfa/0x790 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x45b399\nCode: ad b6 fb ff c3 66 2e 0f 1f 84 00 00 00 00 00 66 90 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 0f 83 7b b6 fb ff c3 66 2e 0f 1f 84 00 00 00 00\nRSP: 002b:00007f7d13c11c78 EFLAGS: 00000246 ORIG_RAX: 0000000000000010\nRAX: ffffffffffffffda RBX: 00007f7d13c126d4 RCX: 000000000045b399\nRDX: 0000000020000080 RSI: 000000000000560a RDI: 0000000000000003\nRBP: 000000000075bf20 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00000000ffffffff\nR13: 0000000000000666 R14: 00000000004c7f04 R15: 000000000075bf2c\nModules linked in:\n---[ end trace 80970faf7a67eb77 ]---\nRIP: 0010:vt_ioctl+0x1f96/0x26d0 drivers/tty/vt/vt_ioctl.c:883\nCode: 74 41 e8 bd a6 84 fd 48 89 d8 48 c1 e8 03 42 80 3c 28 00 0f 85 e4 04 00 00 48 8b 03 48 8d b8 40 03 00 00 48 89 fa 48 c1 ea 03 <42> 0f b6 14 2a 84 d2 74 09 80 fa 03 0f 8e b1 05 00 00 44 89 b8 40\nRSP: 0018:ffffc900086d7bb0 EFLAGS: 00010202\nRAX: 0000000000000000 RBX: ffffffff8c34ee88 RCX: ffffc9001415c000\nRDX: 0000000000000068 RSI: ffffffff83f0e6e3 RDI: 0000000000000340\nRBP: ffffc900086d7cd0 R08: ffff888054ce0100 R09: fffffbfff16a2f6d\nR10: ffff888054ce0998 R11: ffff888054ce0100 R12: 000000000000001d\nR13: dffffc0000000000 R14: 1ffff920010daf79 R15: 000000000000ff7f\nFS: 00007f7d13c12700(0000) GS:ffff8880ae900000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 00007ffd477e3c38 CR3: 0000000095d0a000 CR4: 00000000001406e0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Eric Dumazet <edumazet@google.com>\nCc: stable <stable@vger.kernel.org>\nReported-by: syzbot <syzkaller@googlegroups.com>\nLink: https://lore.kernel.org/r/20200210190721.200418-1-edumazet@google.com\nSigned-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>", "target": 0, "dataset": "other", "idx": 458189}
  923. {"func": "Pl_ASCIIHexDecoder::flush()\n{\n if (this->pos == 0)\n {\n\tQTC::TC(\"libtests\", \"Pl_ASCIIHexDecoder no-op flush\");\n\treturn;\n }\n int b[2];\n for (int i = 0; i < 2; ++i)\n {\n\tif (this->inbuf[i] >= 'A')\n\t{\n\t b[i] = this->inbuf[i] - 'A' + 10;\n\t}\n\telse\n\t{\n\t b[i] = this->inbuf[i] - '0';\n\t}\n }\n unsigned char ch = static_cast<unsigned char>((b[0] << 4) + b[1]);\n\n QTC::TC(\"libtests\", \"Pl_ASCIIHexDecoder partial flush\",\n\t (this->pos == 2) ? 0 : 1);\n getNext()->write(&ch, 1);\n\n this->pos = 0;\n this->inbuf[0] = '0';\n this->inbuf[1] = '0';\n this->inbuf[2] = '\\0';\n}", "project": "qpdf", "hash": 203118129371621348619685394824494279281, "size": 30, "commit_id": "dc92574c10f3e2516ec6445b88c5d584f40df4e5", "message": "Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)", "target": 1, "dataset": "other", "idx": 212373}
  924. {"func": "Pl_ASCIIHexDecoder::flush()\n{\n if (this->pos == 0)\n {\n\tQTC::TC(\"libtests\", \"Pl_ASCIIHexDecoder no-op flush\");\n\treturn;\n }\n int b[2];\n for (int i = 0; i < 2; ++i)\n {\n\tif (this->inbuf[i] >= 'A')\n\t{\n\t b[i] = this->inbuf[i] - 'A' + 10;\n\t}\n\telse\n\t{\n\t b[i] = this->inbuf[i] - '0';\n\t}\n }\n unsigned char ch = static_cast<unsigned char>((b[0] << 4) + b[1]);\n\n QTC::TC(\"libtests\", \"Pl_ASCIIHexDecoder partial flush\",\n\t (this->pos == 2) ? 0 : 1);\n // Reset before calling getNext()->write in case that throws an\n // exception.\n this->pos = 0;\n this->inbuf[0] = '0';\n this->inbuf[1] = '0';\n this->inbuf[2] = '\\0';\n\n getNext()->write(&ch, 1);\n}", "project": "qpdf", "hash": 210240176858994773313725168075493405218, "size": 32, "commit_id": "dc92574c10f3e2516ec6445b88c5d584f40df4e5", "message": "Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)", "target": 0, "dataset": "other", "idx": 458316}
  925. {"func": "Pl_AES_PDF::flush(bool strip_padding)\n{\n assert(this->offset == this->buf_size);\n\n if (first)\n {\n\tfirst = false;\n bool return_after_init = false;\n\tif (this->cbc_mode)\n\t{\n\t if (encrypt)\n\t {\n\t\t// Set cbc_block to the initialization vector, and if\n\t\t// not zero, write it to the output stream.\n\t\tinitializeVector();\n if (! (this->use_zero_iv || this->use_specified_iv))\n {\n getNext()->write(this->cbc_block, this->buf_size);\n }\n\t }\n\t else if (this->use_zero_iv || this->use_specified_iv)\n {\n // Initialize vector with zeroes; zero vector was not\n // written to the beginning of the input file.\n initializeVector();\n }\n else\n\t {\n\t\t// Take the first block of input as the initialization\n\t\t// vector. There's nothing to write at this time.\n\t\tmemcpy(this->cbc_block, this->inbuf, this->buf_size);\n\t\tthis->offset = 0;\n return_after_init = true;\n\t }\n\t}\n this->crypto->rijndael_init(\n encrypt, this->key.get(), key_bytes,\n this->cbc_mode, this->cbc_block);\n if (return_after_init)\n {\n return;\n }\n }\n\n if (this->encrypt)\n {\n\tthis->crypto->rijndael_process(this->inbuf, this->outbuf);\n }\n else\n {\n\tthis->crypto->rijndael_process(this->inbuf, this->outbuf);\n }\n unsigned int bytes = this->buf_size;\n if (strip_padding)\n {\n\tunsigned char last = this->outbuf[this->buf_size - 1];\n\tif (last <= this->buf_size)\n\t{\n\t bool strip = true;\n\t for (unsigned int i = 1; i <= last; ++i)\n\t {\n\t\tif (this->outbuf[this->buf_size - i] != last)\n\t\t{\n\t\t strip = false;\n\t\t break;\n\t\t}\n\t }\n\t if (strip)\n\t {\n\t\tbytes -= last;\n\t }\n\t}\n }\n getNext()->write(this->outbuf, bytes);\n this->offset = 0;\n}", "project": "qpdf", "hash": 210723206961795046431763152490099955651, "size": 76, "commit_id": "dc92574c10f3e2516ec6445b88c5d584f40df4e5", "message": "Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)", "target": 1, "dataset": "other", "idx": 212374}
  926. {"func": "Pl_AES_PDF::flush(bool strip_padding)\n{\n assert(this->offset == this->buf_size);\n\n if (first)\n {\n\tfirst = false;\n bool return_after_init = false;\n\tif (this->cbc_mode)\n\t{\n\t if (encrypt)\n\t {\n\t\t// Set cbc_block to the initialization vector, and if\n\t\t// not zero, write it to the output stream.\n\t\tinitializeVector();\n if (! (this->use_zero_iv || this->use_specified_iv))\n {\n getNext()->write(this->cbc_block, this->buf_size);\n }\n\t }\n\t else if (this->use_zero_iv || this->use_specified_iv)\n {\n // Initialize vector with zeroes; zero vector was not\n // written to the beginning of the input file.\n initializeVector();\n }\n else\n\t {\n\t\t// Take the first block of input as the initialization\n\t\t// vector. There's nothing to write at this time.\n\t\tmemcpy(this->cbc_block, this->inbuf, this->buf_size);\n\t\tthis->offset = 0;\n return_after_init = true;\n\t }\n\t}\n this->crypto->rijndael_init(\n encrypt, this->key.get(), key_bytes,\n this->cbc_mode, this->cbc_block);\n if (return_after_init)\n {\n return;\n }\n }\n\n if (this->encrypt)\n {\n\tthis->crypto->rijndael_process(this->inbuf, this->outbuf);\n }\n else\n {\n\tthis->crypto->rijndael_process(this->inbuf, this->outbuf);\n }\n unsigned int bytes = this->buf_size;\n if (strip_padding)\n {\n\tunsigned char last = this->outbuf[this->buf_size - 1];\n\tif (last <= this->buf_size)\n\t{\n\t bool strip = true;\n\t for (unsigned int i = 1; i <= last; ++i)\n\t {\n\t\tif (this->outbuf[this->buf_size - i] != last)\n\t\t{\n\t\t strip = false;\n\t\t break;\n\t\t}\n\t }\n\t if (strip)\n\t {\n\t\tbytes -= last;\n\t }\n\t}\n }\n this->offset = 0;\n getNext()->write(this->outbuf, bytes);\n}", "project": "qpdf", "hash": 322713675875595696904824155170504505595, "size": 76, "commit_id": "dc92574c10f3e2516ec6445b88c5d584f40df4e5", "message": "Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)", "target": 0, "dataset": "other", "idx": 458323}
  927. {"func": "Pl_ASCII85Decoder::flush()\n{\n if (this->pos == 0)\n {\n\tQTC::TC(\"libtests\", \"Pl_ASCII85Decoder no-op flush\");\n\treturn;\n }\n unsigned long lval = 0;\n for (int i = 0; i < 5; ++i)\n {\n\tlval *= 85;\n\tlval += (this->inbuf[i] - 33U);\n }\n\n unsigned char outbuf[4];\n memset(outbuf, 0, 4);\n for (int i = 3; i >= 0; --i)\n {\n\toutbuf[i] = lval & 0xff;\n\tlval >>= 8;\n }\n\n QTC::TC(\"libtests\", \"Pl_ASCII85Decoder partial flush\",\n\t (this->pos == 5) ? 0 : 1);\n getNext()->write(outbuf, this->pos - 1);\n\n this->pos = 0;\n memset(this->inbuf, 117, 5);\n}", "project": "qpdf", "hash": 85528360671820919508396699545533821192, "size": 29, "commit_id": "dc92574c10f3e2516ec6445b88c5d584f40df4e5", "message": "Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)", "target": 1, "dataset": "other", "idx": 212375}
  928. {"func": "Pl_ASCII85Decoder::flush()\n{\n if (this->pos == 0)\n {\n\tQTC::TC(\"libtests\", \"Pl_ASCII85Decoder no-op flush\");\n\treturn;\n }\n unsigned long lval = 0;\n for (int i = 0; i < 5; ++i)\n {\n\tlval *= 85;\n\tlval += (this->inbuf[i] - 33U);\n }\n\n unsigned char outbuf[4];\n memset(outbuf, 0, 4);\n for (int i = 3; i >= 0; --i)\n {\n\toutbuf[i] = lval & 0xff;\n\tlval >>= 8;\n }\n\n QTC::TC(\"libtests\", \"Pl_ASCII85Decoder partial flush\",\n\t (this->pos == 5) ? 0 : 1);\n // Reset before calling getNext()->write in case that throws an\n // exception.\n auto t = this->pos - 1;\n this->pos = 0;\n memset(this->inbuf, 117, 5);\n\n getNext()->write(outbuf, t);\n}", "project": "qpdf", "hash": 295062865177124626965605267616423090069, "size": 32, "commit_id": "dc92574c10f3e2516ec6445b88c5d584f40df4e5", "message": "Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)", "target": 0, "dataset": "other", "idx": 458318}
  929. {"func": "Pl_Count::write(unsigned char* buf, size_t len)\n{\n if (len)\n {\n\tthis->m->count += QIntC::to_offset(len);\n\tgetNext()->write(buf, len);\n\tthis->m->last_char = buf[len - 1];\n }\n}", "project": "qpdf", "hash": 175837226178792908914233242113513690803, "size": 9, "commit_id": "dc92574c10f3e2516ec6445b88c5d584f40df4e5", "message": "Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)", "target": 1, "dataset": "other", "idx": 212376}
  930. {"func": "Pl_Count::write(unsigned char* buf, size_t len)\n{\n if (len)\n {\n\tthis->m->count += QIntC::to_offset(len);\n\tthis->m->last_char = buf[len - 1];\n\tgetNext()->write(buf, len);\n }\n}", "project": "qpdf", "hash": 17982642016827745233059699776008762845, "size": 9, "commit_id": "dc92574c10f3e2516ec6445b88c5d584f40df4e5", "message": "Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)", "target": 0, "dataset": "other", "idx": 458315}
  931. {"func": "static int mt_touch_input_mapping(struct hid_device *hdev, struct hid_input *hi,\n\t\tstruct hid_field *field, struct hid_usage *usage,\n\t\tunsigned long **bit, int *max, struct mt_application *app)\n{\n\tstruct mt_device *td = hid_get_drvdata(hdev);\n\tstruct mt_class *cls = &td->mtclass;\n\tint code;\n\tstruct hid_usage *prev_usage = NULL;\n\n\t/*\n\t * Model touchscreens providing buttons as touchpads.\n\t */\n\tif (field->application == HID_DG_TOUCHSCREEN &&\n\t (usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) {\n\t\tapp->mt_flags |= INPUT_MT_POINTER;\n\t\ttd->inputmode_value = MT_INPUTMODE_TOUCHPAD;\n\t}\n\n\t/* count the buttons on touchpads */\n\tif ((usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON)\n\t\tapp->buttons_count++;\n\n\tif (usage->usage_index)\n\t\tprev_usage = &field->usage[usage->usage_index - 1];\n\n\tswitch (usage->hid & HID_USAGE_PAGE) {\n\n\tcase HID_UP_GENDESK:\n\t\tswitch (usage->hid) {\n\t\tcase HID_GD_X:\n\t\t\tif (prev_usage && (prev_usage->hid == usage->hid)) {\n\t\t\t\tcode = ABS_MT_TOOL_X;\n\t\t\t\tMT_STORE_FIELD(cx);\n\t\t\t} else {\n\t\t\t\tcode = ABS_MT_POSITION_X;\n\t\t\t\tMT_STORE_FIELD(x);\n\t\t\t}\n\n\t\t\tset_abs(hi->input, code, field, cls->sn_move);\n\n\t\t\t/*\n\t\t\t * A system multi-axis that exports X and Y has a high\n\t\t\t * chance of being used directly on a surface\n\t\t\t */\n\t\t\tif (field->application == HID_GD_SYSTEM_MULTIAXIS) {\n\t\t\t\t__set_bit(INPUT_PROP_DIRECT,\n\t\t\t\t\t hi->input->propbit);\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\t ABS_MT_TOOL_TYPE,\n\t\t\t\t\t\t MT_TOOL_DIAL,\n\t\t\t\t\t\t MT_TOOL_DIAL, 0, 0);\n\t\t\t}\n\n\t\t\treturn 1;\n\t\tcase HID_GD_Y:\n\t\t\tif (prev_usage && (prev_usage->hid == usage->hid)) {\n\t\t\t\tcode = ABS_MT_TOOL_Y;\n\t\t\t\tMT_STORE_FIELD(cy);\n\t\t\t} else {\n\t\t\t\tcode = ABS_MT_POSITION_Y;\n\t\t\t\tMT_STORE_FIELD(y);\n\t\t\t}\n\n\t\t\tset_abs(hi->input, code, field, cls->sn_move);\n\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\n\tcase HID_UP_DIGITIZER:\n\t\tswitch (usage->hid) {\n\t\tcase HID_DG_INRANGE:\n\t\t\tif (app->quirks & MT_QUIRK_HOVERING) {\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\tABS_MT_DISTANCE, 0, 1, 0, 0);\n\t\t\t}\n\t\t\tMT_STORE_FIELD(inrange_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONFIDENCE:\n\t\t\tif (cls->name == MT_CLS_WIN_8 &&\n\t\t\t\t(field->application == HID_DG_TOUCHPAD ||\n\t\t\t\t field->application == HID_DG_TOUCHSCREEN))\n\t\t\t\tapp->quirks |= MT_QUIRK_CONFIDENCE;\n\n\t\t\tif (app->quirks & MT_QUIRK_CONFIDENCE)\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\t ABS_MT_TOOL_TYPE,\n\t\t\t\t\t\t MT_TOOL_FINGER,\n\t\t\t\t\t\t MT_TOOL_PALM, 0, 0);\n\n\t\t\tMT_STORE_FIELD(confidence_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_TIPSWITCH:\n\t\t\tif (field->application != HID_GD_SYSTEM_MULTIAXIS)\n\t\t\t\tinput_set_capability(hi->input,\n\t\t\t\t\t\t EV_KEY, BTN_TOUCH);\n\t\t\tMT_STORE_FIELD(tip_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTID:\n\t\t\tMT_STORE_FIELD(contactid);\n\t\t\tapp->touches_by_report++;\n\t\t\treturn 1;\n\t\tcase HID_DG_WIDTH:\n\t\t\tif (!(app->quirks & MT_QUIRK_NO_AREA))\n\t\t\t\tset_abs(hi->input, ABS_MT_TOUCH_MAJOR, field,\n\t\t\t\t\tcls->sn_width);\n\t\t\tMT_STORE_FIELD(w);\n\t\t\treturn 1;\n\t\tcase HID_DG_HEIGHT:\n\t\t\tif (!(app->quirks & MT_QUIRK_NO_AREA)) {\n\t\t\t\tset_abs(hi->input, ABS_MT_TOUCH_MINOR, field,\n\t\t\t\t\tcls->sn_height);\n\n\t\t\t\t/*\n\t\t\t\t * Only set ABS_MT_ORIENTATION if it is not\n\t\t\t\t * already set by the HID_DG_AZIMUTH usage.\n\t\t\t\t */\n\t\t\t\tif (!test_bit(ABS_MT_ORIENTATION,\n\t\t\t\t\t\thi->input->absbit))\n\t\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\tABS_MT_ORIENTATION, 0, 1, 0, 0);\n\t\t\t}\n\t\t\tMT_STORE_FIELD(h);\n\t\t\treturn 1;\n\t\tcase HID_DG_TIPPRESSURE:\n\t\t\tset_abs(hi->input, ABS_MT_PRESSURE, field,\n\t\t\t\tcls->sn_pressure);\n\t\t\tMT_STORE_FIELD(p);\n\t\t\treturn 1;\n\t\tcase HID_DG_SCANTIME:\n\t\t\tinput_set_capability(hi->input, EV_MSC, MSC_TIMESTAMP);\n\t\t\tapp->scantime = &field->value[usage->usage_index];\n\t\t\tapp->scantime_logical_max = field->logical_maximum;\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTCOUNT:\n\t\t\tapp->have_contact_count = true;\n\t\t\tapp->raw_cc = &field->value[usage->usage_index];\n\t\t\treturn 1;\n\t\tcase HID_DG_AZIMUTH:\n\t\t\t/*\n\t\t\t * Azimuth has the range of [0, MAX) representing a full\n\t\t\t * revolution. Set ABS_MT_ORIENTATION to a quarter of\n\t\t\t * MAX according the definition of ABS_MT_ORIENTATION\n\t\t\t */\n\t\t\tinput_set_abs_params(hi->input, ABS_MT_ORIENTATION,\n\t\t\t\t-field->logical_maximum / 4,\n\t\t\t\tfield->logical_maximum / 4,\n\t\t\t\tcls->sn_move ?\n\t\t\t\tfield->logical_maximum / cls->sn_move : 0, 0);\n\t\t\tMT_STORE_FIELD(a);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTMAX:\n\t\t\t/* contact max are global to the report */\n\t\t\treturn -1;\n\t\tcase HID_DG_TOUCH:\n\t\t\t/* Legacy devices use TIPSWITCH and not TOUCH.\n\t\t\t * Let's just ignore this field. */\n\t\t\treturn -1;\n\t\t}\n\t\t/* let hid-input decide for the others */\n\t\treturn 0;\n\n\tcase HID_UP_BUTTON:\n\t\tcode = BTN_MOUSE + ((usage->hid - 1) & HID_USAGE);\n\t\t/*\n\t\t * MS PTP spec says that external buttons left and right have\n\t\t * usages 2 and 3.\n\t\t */\n\t\tif ((app->quirks & MT_QUIRK_WIN8_PTP_BUTTONS) &&\n\t\t field->application == HID_DG_TOUCHPAD &&\n\t\t (usage->hid & HID_USAGE) > 1)\n\t\t\tcode--;\n\n\t\tif (field->application == HID_GD_SYSTEM_MULTIAXIS)\n\t\t\tcode = BTN_0 + ((usage->hid - 1) & HID_USAGE);\n\n\t\thid_map_usage(hi, usage, bit, max, EV_KEY, code);\n\t\tinput_set_capability(hi->input, EV_KEY, code);\n\t\treturn 1;\n\n\tcase 0xff000000:\n\t\t/* we do not want to map these: no input-oriented meaning */\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "project": "linux", "hash": 48282048289716496461900266037257497045, "size": 187, "commit_id": "35556bed836f8dc07ac55f69c8d17dce3e7f0e25", "message": "HID: core: Sanitize event code and type when mapping input\n\nWhen calling into hid_map_usage(), the passed event code is\nblindly stored as is, even if it doesn't fit in the associated bitmap.\n\nThis event code can come from a variety of sources, including devices\nmasquerading as input devices, only a bit more \"programmable\".\n\nInstead of taking the event code at face value, check that it actually\nfits the corresponding bitmap, and if it doesn't:\n- spit out a warning so that we know which device is acting up\n- NULLify the bitmap pointer so that we catch unexpected uses\n\nCode paths that can make use of untrusted inputs can now check\nthat the mapping was indeed correct and bail out if not.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Marc Zyngier <maz@kernel.org>\nSigned-off-by: Benjamin Tissoires <benjamin.tissoires@gmail.com>", "target": 1, "dataset": "other", "idx": 212377}
  932. {"func": "static int mt_touch_input_mapping(struct hid_device *hdev, struct hid_input *hi,\n\t\tstruct hid_field *field, struct hid_usage *usage,\n\t\tunsigned long **bit, int *max, struct mt_application *app)\n{\n\tstruct mt_device *td = hid_get_drvdata(hdev);\n\tstruct mt_class *cls = &td->mtclass;\n\tint code;\n\tstruct hid_usage *prev_usage = NULL;\n\n\t/*\n\t * Model touchscreens providing buttons as touchpads.\n\t */\n\tif (field->application == HID_DG_TOUCHSCREEN &&\n\t (usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) {\n\t\tapp->mt_flags |= INPUT_MT_POINTER;\n\t\ttd->inputmode_value = MT_INPUTMODE_TOUCHPAD;\n\t}\n\n\t/* count the buttons on touchpads */\n\tif ((usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON)\n\t\tapp->buttons_count++;\n\n\tif (usage->usage_index)\n\t\tprev_usage = &field->usage[usage->usage_index - 1];\n\n\tswitch (usage->hid & HID_USAGE_PAGE) {\n\n\tcase HID_UP_GENDESK:\n\t\tswitch (usage->hid) {\n\t\tcase HID_GD_X:\n\t\t\tif (prev_usage && (prev_usage->hid == usage->hid)) {\n\t\t\t\tcode = ABS_MT_TOOL_X;\n\t\t\t\tMT_STORE_FIELD(cx);\n\t\t\t} else {\n\t\t\t\tcode = ABS_MT_POSITION_X;\n\t\t\t\tMT_STORE_FIELD(x);\n\t\t\t}\n\n\t\t\tset_abs(hi->input, code, field, cls->sn_move);\n\n\t\t\t/*\n\t\t\t * A system multi-axis that exports X and Y has a high\n\t\t\t * chance of being used directly on a surface\n\t\t\t */\n\t\t\tif (field->application == HID_GD_SYSTEM_MULTIAXIS) {\n\t\t\t\t__set_bit(INPUT_PROP_DIRECT,\n\t\t\t\t\t hi->input->propbit);\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\t ABS_MT_TOOL_TYPE,\n\t\t\t\t\t\t MT_TOOL_DIAL,\n\t\t\t\t\t\t MT_TOOL_DIAL, 0, 0);\n\t\t\t}\n\n\t\t\treturn 1;\n\t\tcase HID_GD_Y:\n\t\t\tif (prev_usage && (prev_usage->hid == usage->hid)) {\n\t\t\t\tcode = ABS_MT_TOOL_Y;\n\t\t\t\tMT_STORE_FIELD(cy);\n\t\t\t} else {\n\t\t\t\tcode = ABS_MT_POSITION_Y;\n\t\t\t\tMT_STORE_FIELD(y);\n\t\t\t}\n\n\t\t\tset_abs(hi->input, code, field, cls->sn_move);\n\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\n\tcase HID_UP_DIGITIZER:\n\t\tswitch (usage->hid) {\n\t\tcase HID_DG_INRANGE:\n\t\t\tif (app->quirks & MT_QUIRK_HOVERING) {\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\tABS_MT_DISTANCE, 0, 1, 0, 0);\n\t\t\t}\n\t\t\tMT_STORE_FIELD(inrange_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONFIDENCE:\n\t\t\tif (cls->name == MT_CLS_WIN_8 &&\n\t\t\t\t(field->application == HID_DG_TOUCHPAD ||\n\t\t\t\t field->application == HID_DG_TOUCHSCREEN))\n\t\t\t\tapp->quirks |= MT_QUIRK_CONFIDENCE;\n\n\t\t\tif (app->quirks & MT_QUIRK_CONFIDENCE)\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\t ABS_MT_TOOL_TYPE,\n\t\t\t\t\t\t MT_TOOL_FINGER,\n\t\t\t\t\t\t MT_TOOL_PALM, 0, 0);\n\n\t\t\tMT_STORE_FIELD(confidence_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_TIPSWITCH:\n\t\t\tif (field->application != HID_GD_SYSTEM_MULTIAXIS)\n\t\t\t\tinput_set_capability(hi->input,\n\t\t\t\t\t\t EV_KEY, BTN_TOUCH);\n\t\t\tMT_STORE_FIELD(tip_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTID:\n\t\t\tMT_STORE_FIELD(contactid);\n\t\t\tapp->touches_by_report++;\n\t\t\treturn 1;\n\t\tcase HID_DG_WIDTH:\n\t\t\tif (!(app->quirks & MT_QUIRK_NO_AREA))\n\t\t\t\tset_abs(hi->input, ABS_MT_TOUCH_MAJOR, field,\n\t\t\t\t\tcls->sn_width);\n\t\t\tMT_STORE_FIELD(w);\n\t\t\treturn 1;\n\t\tcase HID_DG_HEIGHT:\n\t\t\tif (!(app->quirks & MT_QUIRK_NO_AREA)) {\n\t\t\t\tset_abs(hi->input, ABS_MT_TOUCH_MINOR, field,\n\t\t\t\t\tcls->sn_height);\n\n\t\t\t\t/*\n\t\t\t\t * Only set ABS_MT_ORIENTATION if it is not\n\t\t\t\t * already set by the HID_DG_AZIMUTH usage.\n\t\t\t\t */\n\t\t\t\tif (!test_bit(ABS_MT_ORIENTATION,\n\t\t\t\t\t\thi->input->absbit))\n\t\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\tABS_MT_ORIENTATION, 0, 1, 0, 0);\n\t\t\t}\n\t\t\tMT_STORE_FIELD(h);\n\t\t\treturn 1;\n\t\tcase HID_DG_TIPPRESSURE:\n\t\t\tset_abs(hi->input, ABS_MT_PRESSURE, field,\n\t\t\t\tcls->sn_pressure);\n\t\t\tMT_STORE_FIELD(p);\n\t\t\treturn 1;\n\t\tcase HID_DG_SCANTIME:\n\t\t\tinput_set_capability(hi->input, EV_MSC, MSC_TIMESTAMP);\n\t\t\tapp->scantime = &field->value[usage->usage_index];\n\t\t\tapp->scantime_logical_max = field->logical_maximum;\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTCOUNT:\n\t\t\tapp->have_contact_count = true;\n\t\t\tapp->raw_cc = &field->value[usage->usage_index];\n\t\t\treturn 1;\n\t\tcase HID_DG_AZIMUTH:\n\t\t\t/*\n\t\t\t * Azimuth has the range of [0, MAX) representing a full\n\t\t\t * revolution. Set ABS_MT_ORIENTATION to a quarter of\n\t\t\t * MAX according the definition of ABS_MT_ORIENTATION\n\t\t\t */\n\t\t\tinput_set_abs_params(hi->input, ABS_MT_ORIENTATION,\n\t\t\t\t-field->logical_maximum / 4,\n\t\t\t\tfield->logical_maximum / 4,\n\t\t\t\tcls->sn_move ?\n\t\t\t\tfield->logical_maximum / cls->sn_move : 0, 0);\n\t\t\tMT_STORE_FIELD(a);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTMAX:\n\t\t\t/* contact max are global to the report */\n\t\t\treturn -1;\n\t\tcase HID_DG_TOUCH:\n\t\t\t/* Legacy devices use TIPSWITCH and not TOUCH.\n\t\t\t * Let's just ignore this field. */\n\t\t\treturn -1;\n\t\t}\n\t\t/* let hid-input decide for the others */\n\t\treturn 0;\n\n\tcase HID_UP_BUTTON:\n\t\tcode = BTN_MOUSE + ((usage->hid - 1) & HID_USAGE);\n\t\t/*\n\t\t * MS PTP spec says that external buttons left and right have\n\t\t * usages 2 and 3.\n\t\t */\n\t\tif ((app->quirks & MT_QUIRK_WIN8_PTP_BUTTONS) &&\n\t\t field->application == HID_DG_TOUCHPAD &&\n\t\t (usage->hid & HID_USAGE) > 1)\n\t\t\tcode--;\n\n\t\tif (field->application == HID_GD_SYSTEM_MULTIAXIS)\n\t\t\tcode = BTN_0 + ((usage->hid - 1) & HID_USAGE);\n\n\t\thid_map_usage(hi, usage, bit, max, EV_KEY, code);\n\t\tif (!*bit)\n\t\t\treturn -1;\n\t\tinput_set_capability(hi->input, EV_KEY, code);\n\t\treturn 1;\n\n\tcase 0xff000000:\n\t\t/* we do not want to map these: no input-oriented meaning */\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "project": "linux", "hash": 237709689285808653462224634864316547202, "size": 189, "commit_id": "35556bed836f8dc07ac55f69c8d17dce3e7f0e25", "message": "HID: core: Sanitize event code and type when mapping input\n\nWhen calling into hid_map_usage(), the passed event code is\nblindly stored as is, even if it doesn't fit in the associated bitmap.\n\nThis event code can come from a variety of sources, including devices\nmasquerading as input devices, only a bit more \"programmable\".\n\nInstead of taking the event code at face value, check that it actually\nfits the corresponding bitmap, and if it doesn't:\n- spit out a warning so that we know which device is acting up\n- NULLify the bitmap pointer so that we catch unexpected uses\n\nCode paths that can make use of untrusted inputs can now check\nthat the mapping was indeed correct and bail out if not.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Marc Zyngier <maz@kernel.org>\nSigned-off-by: Benjamin Tissoires <benjamin.tissoires@gmail.com>", "target": 0, "dataset": "other", "idx": 458382}
  933. {"func": "ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms)\n{\n unsigned int nbits;\n gpg_err_code_t rc;\n struct pk_encoding_ctx ctx;\n gcry_sexp_t l1 = NULL;\n gcry_mpi_t data_e = NULL;\n ECC_secret_key sk;\n gcry_mpi_t mpi_g = NULL;\n char *curvename = NULL;\n mpi_ec_t ec = NULL;\n mpi_point_struct kG;\n mpi_point_struct R;\n gcry_mpi_t r = NULL;\n int flags = 0;\n\n memset (&sk, 0, sizeof sk);\n point_init (&kG);\n point_init (&R);\n\n _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT,\n (nbits = ecc_get_nbits (keyparms)));\n\n /* Look for flags. */\n l1 = sexp_find_token (keyparms, \"flags\", 0);\n if (l1)\n {\n rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL);\n if (rc)\n goto leave;\n }\n sexp_release (l1);\n l1 = NULL;\n\n /*\n * Extract the data.\n */\n rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx);\n if (rc)\n goto leave;\n rc = sexp_extract_param (l1, NULL, \"e\", &data_e, NULL);\n if (rc)\n goto leave;\n if (DBG_CIPHER)\n log_printmpi (\"ecc_decrypt d_e\", data_e);\n if (mpi_is_opaque (data_e))\n {\n rc = GPG_ERR_INV_DATA;\n goto leave;\n }\n\n /*\n * Extract the key.\n */\n rc = sexp_extract_param (keyparms, NULL, \"-p?a?b?g?n?h?+d\",\n &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n,\n &sk.E.h, &sk.d, NULL);\n if (rc)\n goto leave;\n if (mpi_g)\n {\n point_init (&sk.E.G);\n rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g);\n if (rc)\n goto leave;\n }\n /* Add missing parameters using the optional curve parameter. */\n sexp_release (l1);\n l1 = sexp_find_token (keyparms, \"curve\", 5);\n if (l1)\n {\n curvename = sexp_nth_string (l1, 1);\n if (curvename)\n {\n rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL);\n if (rc)\n goto leave;\n }\n }\n /* Guess required fields if a curve parameter has not been given. */\n if (!curvename)\n {\n sk.E.model = MPI_EC_WEIERSTRASS;\n sk.E.dialect = ECC_DIALECT_STANDARD;\n if (!sk.E.h)\n\tsk.E.h = mpi_const (MPI_C_ONE);\n }\n if (DBG_CIPHER)\n {\n log_debug (\"ecc_decrypt info: %s/%s\\n\",\n _gcry_ecc_model2str (sk.E.model),\n _gcry_ecc_dialect2str (sk.E.dialect));\n if (sk.E.name)\n log_debug (\"ecc_decrypt name: %s\\n\", sk.E.name);\n log_printmpi (\"ecc_decrypt p\", sk.E.p);\n log_printmpi (\"ecc_decrypt a\", sk.E.a);\n log_printmpi (\"ecc_decrypt b\", sk.E.b);\n log_printpnt (\"ecc_decrypt g\", &sk.E.G, NULL);\n log_printmpi (\"ecc_decrypt n\", sk.E.n);\n log_printmpi (\"ecc_decrypt h\", sk.E.h);\n if (!fips_mode ())\n log_printmpi (\"ecc_decrypt d\", sk.d);\n }\n if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d)\n {\n rc = GPG_ERR_NO_OBJ;\n goto leave;\n }\n\n\n ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags,\n sk.E.p, sk.E.a, sk.E.b);\n\n /*\n * Compute the plaintext.\n */\n if (ec->model == MPI_EC_MONTGOMERY)\n rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG);\n else\n rc = _gcry_ecc_os2ec (&kG, data_e);\n if (rc)\n goto leave;\n\n if (DBG_CIPHER)\n log_printpnt (\"ecc_decrypt kG\", &kG, NULL);\n\n if (!(flags & PUBKEY_FLAG_DJB_TWEAK)\n /* For X25519, by its definition, validation should not be done. */\n && !_gcry_mpi_ec_curve_point (&kG, ec))\n {\n rc = GPG_ERR_INV_DATA;\n goto leave;\n }\n\n /* R = dkG */\n _gcry_mpi_ec_mul_point (&R, sk.d, &kG, ec);\n\n /* The following is false: assert( mpi_cmp_ui( R.x, 1 )==0 );, so: */\n {\n gcry_mpi_t x, y;\n\n x = mpi_new (0);\n if (ec->model == MPI_EC_MONTGOMERY)\n y = NULL;\n else\n y = mpi_new (0);\n\n if (_gcry_mpi_ec_get_affine (x, y, &R, ec))\n {\n rc = GPG_ERR_INV_DATA;\n goto leave;\n /*\n * Note for X25519.\n *\n * By the definition of X25519, this is the case where X25519\n * returns 0, mapping infinity to zero. However, we\n * deliberately let it return an error.\n *\n * For X25519 ECDH, comming here means that it might be\n * decrypted by anyone with the shared secret of 0 (the result\n * of this function could be always 0 by other scalar values,\n * other than the private key of SK.D).\n *\n * So, it looks like an encrypted message but it can be\n * decrypted by anyone, or at least something wrong\n * happens. Recipient should not proceed as if it were\n * properly encrypted message.\n *\n * This handling is needed for our major usage of GnuPG,\n * where it does the One-Pass Diffie-Hellman method,\n * C(1, 1, ECC CDH), with an ephemeral key.\n */\n }\n\n if (y)\n r = _gcry_ecc_ec2os (x, y, sk.E.p);\n else\n {\n unsigned char *rawmpi;\n unsigned int rawmpilen;\n\n rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1,\n &rawmpilen, NULL);\n if (!rawmpi)\n {\n rc = gpg_err_code_from_syserror ();\n goto leave;\n }\n else\n {\n rawmpi[0] = 0x40;\n rawmpilen++;\n r = mpi_new (0);\n mpi_set_opaque (r, rawmpi, rawmpilen*8);\n }\n }\n if (!r)\n rc = gpg_err_code_from_syserror ();\n else\n rc = 0;\n mpi_free (x);\n mpi_free (y);\n }\n if (DBG_CIPHER)\n log_printmpi (\"ecc_decrypt res\", r);\n\n if (!rc)\n rc = sexp_build (r_plain, NULL, \"(value %m)\", r);\n\n leave:\n point_free (&R);\n point_free (&kG);\n _gcry_mpi_release (r);\n _gcry_mpi_release (sk.E.p);\n _gcry_mpi_release (sk.E.a);\n _gcry_mpi_release (sk.E.b);\n _gcry_mpi_release (mpi_g);\n point_free (&sk.E.G);\n _gcry_mpi_release (sk.E.n);\n _gcry_mpi_release (sk.E.h);\n _gcry_mpi_release (sk.d);\n _gcry_mpi_release (data_e);\n xfree (curvename);\n sexp_release (l1);\n _gcry_mpi_ec_free (ec);\n _gcry_pk_util_free_encoding_ctx (&ctx);\n if (DBG_CIPHER)\n log_debug (\"ecc_decrypt => %s\\n\", gpg_strerror (rc));\n return rc;\n}", "project": "libgcrypt", "hash": 125664893693859396705351501621878215385, "size": 230, "commit_id": "bf76acbf0da6b0f245e491bec12c0f0a1b5be7c9", "message": "ecc: Add input validation for X25519.\n\n* cipher/ecc.c (ecc_decrypt_raw): Add input validation.\n* mpi/ec.c (ec_p_init): Use scratch buffer for bad points.\n(_gcry_mpi_ec_bad_point): New.\n\n--\n\nFollowing is the paper describing the attack:\n\n May the Fourth Be With You: A Microarchitectural Side Channel Attack\n on Real-World Applications of Curve25519\n by Daniel Genkin, Luke Valenta, and Yuval Yarom\n\nIn the current implementation, we do output checking and it results an\nerror for those bad points. However, when attacked, the computation\nwill done with leak of private key, even it will results errors. To\nmitigate leak, we added input validation.\n\nNote that we only list bad points with MSB=0. By X25519, MSB is\nalways cleared.\n\nIn future, we should implement constant-time field computation. Then,\nthis input validation could be removed, if performance is important\nand we are sure for no leak.\n\nCVE-id: CVE-2017-0379\nSigned-off-by: NIIBE Yutaka <gniibe@fsij.org>", "target": 1, "dataset": "other", "idx": 212389}
  934. {"func": "ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms)\n{\n unsigned int nbits;\n gpg_err_code_t rc;\n struct pk_encoding_ctx ctx;\n gcry_sexp_t l1 = NULL;\n gcry_mpi_t data_e = NULL;\n ECC_secret_key sk;\n gcry_mpi_t mpi_g = NULL;\n char *curvename = NULL;\n mpi_ec_t ec = NULL;\n mpi_point_struct kG;\n mpi_point_struct R;\n gcry_mpi_t r = NULL;\n int flags = 0;\n\n memset (&sk, 0, sizeof sk);\n point_init (&kG);\n point_init (&R);\n\n _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT,\n (nbits = ecc_get_nbits (keyparms)));\n\n /* Look for flags. */\n l1 = sexp_find_token (keyparms, \"flags\", 0);\n if (l1)\n {\n rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL);\n if (rc)\n goto leave;\n }\n sexp_release (l1);\n l1 = NULL;\n\n /*\n * Extract the data.\n */\n rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx);\n if (rc)\n goto leave;\n rc = sexp_extract_param (l1, NULL, \"e\", &data_e, NULL);\n if (rc)\n goto leave;\n if (DBG_CIPHER)\n log_printmpi (\"ecc_decrypt d_e\", data_e);\n if (mpi_is_opaque (data_e))\n {\n rc = GPG_ERR_INV_DATA;\n goto leave;\n }\n\n /*\n * Extract the key.\n */\n rc = sexp_extract_param (keyparms, NULL, \"-p?a?b?g?n?h?+d\",\n &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n,\n &sk.E.h, &sk.d, NULL);\n if (rc)\n goto leave;\n if (mpi_g)\n {\n point_init (&sk.E.G);\n rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g);\n if (rc)\n goto leave;\n }\n /* Add missing parameters using the optional curve parameter. */\n sexp_release (l1);\n l1 = sexp_find_token (keyparms, \"curve\", 5);\n if (l1)\n {\n curvename = sexp_nth_string (l1, 1);\n if (curvename)\n {\n rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL);\n if (rc)\n goto leave;\n }\n }\n /* Guess required fields if a curve parameter has not been given. */\n if (!curvename)\n {\n sk.E.model = MPI_EC_WEIERSTRASS;\n sk.E.dialect = ECC_DIALECT_STANDARD;\n if (!sk.E.h)\n\tsk.E.h = mpi_const (MPI_C_ONE);\n }\n if (DBG_CIPHER)\n {\n log_debug (\"ecc_decrypt info: %s/%s\\n\",\n _gcry_ecc_model2str (sk.E.model),\n _gcry_ecc_dialect2str (sk.E.dialect));\n if (sk.E.name)\n log_debug (\"ecc_decrypt name: %s\\n\", sk.E.name);\n log_printmpi (\"ecc_decrypt p\", sk.E.p);\n log_printmpi (\"ecc_decrypt a\", sk.E.a);\n log_printmpi (\"ecc_decrypt b\", sk.E.b);\n log_printpnt (\"ecc_decrypt g\", &sk.E.G, NULL);\n log_printmpi (\"ecc_decrypt n\", sk.E.n);\n log_printmpi (\"ecc_decrypt h\", sk.E.h);\n if (!fips_mode ())\n log_printmpi (\"ecc_decrypt d\", sk.d);\n }\n if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d)\n {\n rc = GPG_ERR_NO_OBJ;\n goto leave;\n }\n\n\n ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags,\n sk.E.p, sk.E.a, sk.E.b);\n\n /*\n * Compute the plaintext.\n */\n if (ec->model == MPI_EC_MONTGOMERY)\n rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG);\n else\n rc = _gcry_ecc_os2ec (&kG, data_e);\n if (rc)\n goto leave;\n\n if (DBG_CIPHER)\n log_printpnt (\"ecc_decrypt kG\", &kG, NULL);\n\n if ((flags & PUBKEY_FLAG_DJB_TWEAK))\n {\n /* For X25519, by its definition, validation should not be done. */\n /* (Instead, we do output check.)\n *\n * However, to mitigate secret key leak from our implementation,\n * we also do input validation here. For constant-time\n * implementation, we can remove this input validation.\n */\n if (_gcry_mpi_ec_bad_point (&kG, ec))\n {\n rc = GPG_ERR_INV_DATA;\n goto leave;\n }\n }\n else if (!_gcry_mpi_ec_curve_point (&kG, ec))\n {\n rc = GPG_ERR_INV_DATA;\n goto leave;\n }\n\n /* R = dkG */\n _gcry_mpi_ec_mul_point (&R, sk.d, &kG, ec);\n\n /* The following is false: assert( mpi_cmp_ui( R.x, 1 )==0 );, so: */\n {\n gcry_mpi_t x, y;\n\n x = mpi_new (0);\n if (ec->model == MPI_EC_MONTGOMERY)\n y = NULL;\n else\n y = mpi_new (0);\n\n if (_gcry_mpi_ec_get_affine (x, y, &R, ec))\n {\n rc = GPG_ERR_INV_DATA;\n goto leave;\n /*\n * Note for X25519.\n *\n * By the definition of X25519, this is the case where X25519\n * returns 0, mapping infinity to zero. However, we\n * deliberately let it return an error.\n *\n * For X25519 ECDH, comming here means that it might be\n * decrypted by anyone with the shared secret of 0 (the result\n * of this function could be always 0 by other scalar values,\n * other than the private key of SK.D).\n *\n * So, it looks like an encrypted message but it can be\n * decrypted by anyone, or at least something wrong\n * happens. Recipient should not proceed as if it were\n * properly encrypted message.\n *\n * This handling is needed for our major usage of GnuPG,\n * where it does the One-Pass Diffie-Hellman method,\n * C(1, 1, ECC CDH), with an ephemeral key.\n */\n }\n\n if (y)\n r = _gcry_ecc_ec2os (x, y, sk.E.p);\n else\n {\n unsigned char *rawmpi;\n unsigned int rawmpilen;\n\n rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1,\n &rawmpilen, NULL);\n if (!rawmpi)\n {\n rc = gpg_err_code_from_syserror ();\n goto leave;\n }\n else\n {\n rawmpi[0] = 0x40;\n rawmpilen++;\n r = mpi_new (0);\n mpi_set_opaque (r, rawmpi, rawmpilen*8);\n }\n }\n if (!r)\n rc = gpg_err_code_from_syserror ();\n else\n rc = 0;\n mpi_free (x);\n mpi_free (y);\n }\n if (DBG_CIPHER)\n log_printmpi (\"ecc_decrypt res\", r);\n\n if (!rc)\n rc = sexp_build (r_plain, NULL, \"(value %m)\", r);\n\n leave:\n point_free (&R);\n point_free (&kG);\n _gcry_mpi_release (r);\n _gcry_mpi_release (sk.E.p);\n _gcry_mpi_release (sk.E.a);\n _gcry_mpi_release (sk.E.b);\n _gcry_mpi_release (mpi_g);\n point_free (&sk.E.G);\n _gcry_mpi_release (sk.E.n);\n _gcry_mpi_release (sk.E.h);\n _gcry_mpi_release (sk.d);\n _gcry_mpi_release (data_e);\n xfree (curvename);\n sexp_release (l1);\n _gcry_mpi_ec_free (ec);\n _gcry_pk_util_free_encoding_ctx (&ctx);\n if (DBG_CIPHER)\n log_debug (\"ecc_decrypt => %s\\n\", gpg_strerror (rc));\n return rc;\n}", "project": "libgcrypt", "hash": 221349693093505639736378931380558430882, "size": 243, "commit_id": "bf76acbf0da6b0f245e491bec12c0f0a1b5be7c9", "message": "ecc: Add input validation for X25519.\n\n* cipher/ecc.c (ecc_decrypt_raw): Add input validation.\n* mpi/ec.c (ec_p_init): Use scratch buffer for bad points.\n(_gcry_mpi_ec_bad_point): New.\n\n--\n\nFollowing is the paper describing the attack:\n\n May the Fourth Be With You: A Microarchitectural Side Channel Attack\n on Real-World Applications of Curve25519\n by Daniel Genkin, Luke Valenta, and Yuval Yarom\n\nIn the current implementation, we do output checking and it results an\nerror for those bad points. However, when attacked, the computation\nwill done with leak of private key, even it will results errors. To\nmitigate leak, we added input validation.\n\nNote that we only list bad points with MSB=0. By X25519, MSB is\nalways cleared.\n\nIn future, we should implement constant-time field computation. Then,\nthis input validation could be removed, if performance is important\nand we are sure for no leak.\n\nCVE-id: CVE-2017-0379\nSigned-off-by: NIIBE Yutaka <gniibe@fsij.org>", "target": 0, "dataset": "other", "idx": 458698}
  935. {"func": "static MagickBooleanType ReadHEICImageByID(const ImageInfo *image_info,\n Image *image,struct heif_context *heif_context,heif_item_id image_id,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n int\n stride_y,\n stride_cb,\n stride_cr;\n\n MagickBooleanType\n status;\n\n ssize_t\n y;\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 error=heif_context_get_image_handle(heif_context,image_id,&image_handle);\n if (IsHeifSuccess(&error,image,exception) == MagickFalse)\n return(MagickFalse);\n if (ReadHEICColorProfile(image,image_handle,exception) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickFalse);\n }\n if (ReadHEICExifProfile(image,image_handle,exception) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickFalse);\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 return(MagickTrue);\n }\n if (HEICSkipImage(image_info,image) != MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickTrue);\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickFalse);\n }\n /*\n Copy HEIF image into ImageMagick data structures.\n */\n (void) SetImageColorspace(image,YCbCrColorspace,exception);\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\",exception);\n error=heif_decode_image(image_handle,&heif_image,heif_colorspace_YCbCr,\n heif_chroma_420,decode_options);\n if (IsHeifSuccess(&error,image,exception) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickFalse);\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,exception);\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 return(MagickFalse);\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 Quantum\n *q;\n\n register ssize_t\n x;\n\n q=QueueAuthenticPixels(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 SetPixelRed(image,ScaleCharToQuantum((unsigned char) p_y[y*\n stride_y+x]),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char) p_cb[(y/2)*\n stride_cb+x/2]),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char) p_cr[(y/2)*\n stride_cr+x/2]),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n return(MagickTrue);\n}", "project": "ImageMagick", "hash": 154557627643794820744368940487947565708, "size": 138, "commit_id": "868aad754ee599eb7153b84d610f2ecdf7b339f6", "message": "Always correct the width and height of the image (#1859).", "target": 1, "dataset": "other", "idx": 212425}
  936. {"func": "static MagickBooleanType ReadHEICImageByID(const ImageInfo *image_info,\n Image *image,struct heif_context *heif_context,heif_item_id image_id,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n int\n stride_y,\n stride_cb,\n stride_cr;\n\n MagickBooleanType\n status;\n\n ssize_t\n y;\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 error=heif_context_get_image_handle(heif_context,image_id,&image_handle);\n if (IsHeifSuccess(&error,image,exception) == MagickFalse)\n return(MagickFalse);\n if (ReadHEICColorProfile(image,image_handle,exception) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickFalse);\n }\n if (ReadHEICExifProfile(image,image_handle,exception) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickFalse);\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 return(MagickTrue);\n }\n if (HEICSkipImage(image_info,image) != MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickTrue);\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickFalse);\n }\n /*\n Copy HEIF image into ImageMagick data structures.\n */\n (void) SetImageColorspace(image,YCbCrColorspace,exception);\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\",exception);\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,exception) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n return(MagickFalse);\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,exception);\n if (status == MagickFalse)\n {\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n return(MagickFalse);\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 Quantum\n *q;\n\n register ssize_t\n x;\n\n q=QueueAuthenticPixels(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 SetPixelRed(image,ScaleCharToQuantum((unsigned char) p_y[y*\n stride_y+x]),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char) p_cb[(y/2)*\n stride_cb+x/2]),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char) p_cr[(y/2)*\n stride_cr+x/2]),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n return(MagickTrue);\n}", "project": "ImageMagick", "hash": 152426799834776983096599814137214229220, "size": 136, "commit_id": "868aad754ee599eb7153b84d610f2ecdf7b339f6", "message": "Always correct the width and height of the image (#1859).", "target": 0, "dataset": "other", "idx": 459319}
  937. {"func": "static MagickBooleanType TIFFGetProfiles(TIFF *tiff,Image *image,\n ExceptionInfo *exception)\n{\n MagickBooleanType\n status;\n\n uint32\n length = 0;\n\n unsigned char\n *profile = (unsigned char *) NULL;\n\n status=MagickTrue;\n#if defined(TIFFTAG_ICCPROFILE)\n if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n status=ReadProfile(image,\"icc\",profile,(ssize_t) length,exception);\n#endif\n#if defined(TIFFTAG_PHOTOSHOP)\n if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n status=ReadProfile(image,\"8bim\",profile,(ssize_t) length,exception);\n#endif\n#if defined(TIFFTAG_RICHTIFFIPTC)\n if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n {\n if (TIFFIsByteSwapped(tiff) != 0)\n TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);\n status=ReadProfile(image,\"iptc\",profile,4L*length,exception);\n }\n#endif\n#if defined(TIFFTAG_XMLPACKET)\n if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n {\n StringInfo\n *dng;\n\n status=ReadProfile(image,\"xmp\",profile,(ssize_t) length,exception);\n dng=BlobToStringInfo(profile,length);\n if (dng != (StringInfo *) NULL)\n {\n const char\n *target = \"dc:format=\\\"image/dng\\\"\";\n\n if (strstr((char *) GetStringInfoDatum(dng),target) != (char *) NULL)\n (void) CopyMagickString(image->magick,\"DNG\",MagickPathExtent);\n dng=DestroyStringInfo(dng);\n }\n }\n#endif\n if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n status=ReadProfile(image,\"tiff:34118\",profile,(ssize_t) length,\n exception);\n if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n status=ReadProfile(image,\"tiff:37724\",profile,(ssize_t) length,exception);\n return(status);\n}", "project": "ImageMagick", "hash": 80273906805248286578189872570147097025, "size": 61, "commit_id": "824f344ceb823e156ad6e85314d79c087933c2a0", "message": "Check the type of the field before performing the multiplication (details in #2132)", "target": 1, "dataset": "other", "idx": 212435}
  938. {"func": "static MagickBooleanType TIFFGetProfiles(TIFF *tiff,Image *image,\n ExceptionInfo *exception)\n{\n MagickBooleanType\n status;\n\n uint32\n length = 0;\n\n unsigned char\n *profile = (unsigned char *) NULL;\n\n status=MagickTrue;\n#if defined(TIFFTAG_ICCPROFILE)\n if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n status=ReadProfile(image,\"icc\",profile,(ssize_t) length,exception);\n#endif\n#if defined(TIFFTAG_PHOTOSHOP)\n if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n status=ReadProfile(image,\"8bim\",profile,(ssize_t) length,exception);\n#endif\n#if defined(TIFFTAG_RICHTIFFIPTC)\n if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n {\n const TIFFField\n *field;\n\n if (TIFFIsByteSwapped(tiff) != 0)\n TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);\n field=TIFFFieldWithTag(tiff,TIFFTAG_RICHTIFFIPTC);\n if (TIFFFieldDataType(field) == TIFF_LONG)\n status=ReadProfile(image,\"iptc\",profile,4L*length,exception);\n else\n status=ReadProfile(image,\"iptc\",profile,length,exception);\n }\n#endif\n#if defined(TIFFTAG_XMLPACKET)\n if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n {\n StringInfo\n *dng;\n\n status=ReadProfile(image,\"xmp\",profile,(ssize_t) length,exception);\n dng=BlobToStringInfo(profile,length);\n if (dng != (StringInfo *) NULL)\n {\n const char\n *target = \"dc:format=\\\"image/dng\\\"\";\n\n if (strstr((char *) GetStringInfoDatum(dng),target) != (char *) NULL)\n (void) CopyMagickString(image->magick,\"DNG\",MagickPathExtent);\n dng=DestroyStringInfo(dng);\n }\n }\n#endif\n if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n status=ReadProfile(image,\"tiff:34118\",profile,(ssize_t) length,\n exception);\n if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&\n (profile != (unsigned char *) NULL))\n status=ReadProfile(image,\"tiff:37724\",profile,(ssize_t) length,exception);\n return(status);\n}", "project": "ImageMagick", "hash": 13944005594410488667034111483743253825, "size": 68, "commit_id": "824f344ceb823e156ad6e85314d79c087933c2a0", "message": "Check the type of the field before performing the multiplication (details in #2132)", "target": 0, "dataset": "other", "idx": 459504}
  939. {"func": "readfile(\n char_u\t*fname,\n char_u\t*sfname,\n linenr_T\tfrom,\n linenr_T\tlines_to_skip,\n linenr_T\tlines_to_read,\n exarg_T\t*eap,\t\t\t/* can be NULL! */\n int\t\tflags)\n{\n int\t\tfd = 0;\n int\t\tnewfile = (flags & READ_NEW);\n int\t\tcheck_readonly;\n int\t\tfiltering = (flags & READ_FILTER);\n int\t\tread_stdin = (flags & READ_STDIN);\n int\t\tread_buffer = (flags & READ_BUFFER);\n int\t\tread_fifo = (flags & READ_FIFO);\n int\t\tset_options = newfile || read_buffer\n\t\t\t\t\t || (eap != NULL && eap->read_edit);\n linenr_T\tread_buf_lnum = 1;\t/* next line to read from curbuf */\n colnr_T\tread_buf_col = 0;\t/* next char to read from this line */\n char_u\tc;\n linenr_T\tlnum = from;\n char_u\t*ptr = NULL;\t\t/* pointer into read buffer */\n char_u\t*buffer = NULL;\t\t/* read buffer */\n char_u\t*new_buffer = NULL;\t/* init to shut up gcc */\n char_u\t*line_start = NULL;\t/* init to shut up gcc */\n int\t\twasempty;\t\t/* buffer was empty before reading */\n colnr_T\tlen;\n long\tsize = 0;\n char_u\t*p;\n off_T\tfilesize = 0;\n int\t\tskip_read = FALSE;\n#ifdef FEAT_CRYPT\n char_u\t*cryptkey = NULL;\n int\t\tdid_ask_for_key = FALSE;\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n context_sha256_T sha_ctx;\n int\t\tread_undo_file = FALSE;\n#endif\n int\t\tsplit = 0;\t\t/* number of split lines */\n#define UNKNOWN\t 0x0fffffff\t\t/* file size is unknown */\n linenr_T\tlinecnt;\n int\t\terror = FALSE;\t\t/* errors encountered */\n int\t\tff_error = EOL_UNKNOWN; /* file format with errors */\n long\tlinerest = 0;\t\t/* remaining chars in line */\n#ifdef UNIX\n int\t\tperm = 0;\n int\t\tswap_mode = -1;\t\t/* protection bits for swap file */\n#else\n int\t\tperm;\n#endif\n int\t\tfileformat = 0;\t\t/* end-of-line format */\n int\t\tkeep_fileformat = FALSE;\n stat_T\tst;\n int\t\tfile_readonly;\n linenr_T\tskip_count = 0;\n linenr_T\tread_count = 0;\n int\t\tmsg_save = msg_scroll;\n linenr_T\tread_no_eol_lnum = 0; /* non-zero lnum when last line of\n\t\t\t\t\t * last read was missing the eol */\n int\t\ttry_mac;\n int\t\ttry_dos;\n int\t\ttry_unix;\n int\t\tfile_rewind = FALSE;\n#ifdef FEAT_MBYTE\n int\t\tcan_retry;\n linenr_T\tconv_error = 0;\t\t/* line nr with conversion error */\n linenr_T\tillegal_byte = 0;\t/* line nr with illegal byte */\n int\t\tkeep_dest_enc = FALSE;\t/* don't retry when char doesn't fit\n\t\t\t\t\t in destination encoding */\n int\t\tbad_char_behavior = BAD_REPLACE;\n\t\t\t\t\t/* BAD_KEEP, BAD_DROP or character to\n\t\t\t\t\t * replace with */\n char_u\t*tmpname = NULL;\t/* name of 'charconvert' output file */\n int\t\tfio_flags = 0;\n char_u\t*fenc;\t\t\t/* fileencoding to use */\n int\t\tfenc_alloced;\t\t/* fenc_next is in allocated memory */\n char_u\t*fenc_next = NULL;\t/* next item in 'fencs' or NULL */\n int\t\tadvance_fenc = FALSE;\n long\treal_size = 0;\n# ifdef USE_ICONV\n iconv_t\ticonv_fd = (iconv_t)-1;\t/* descriptor for iconv() or -1 */\n# ifdef FEAT_EVAL\n int\t\tdid_iconv = FALSE;\t/* TRUE when iconv() failed and trying\n\t\t\t\t\t 'charconvert' next */\n# endif\n# endif\n int\t\tconverted = FALSE;\t/* TRUE if conversion done */\n int\t\tnotconverted = FALSE;\t/* TRUE if conversion wanted but it\n\t\t\t\t\t wasn't possible */\n char_u\tconv_rest[CONV_RESTLEN];\n int\t\tconv_restlen = 0;\t/* nr of bytes in conv_rest[] */\n#endif\n#ifdef FEAT_AUTOCMD\n buf_T\t*old_curbuf;\n char_u\t*old_b_ffname;\n char_u\t*old_b_fname;\n int\t\tusing_b_ffname;\n int\t\tusing_b_fname;\n#endif\n\n#ifdef FEAT_AUTOCMD\n au_did_filetype = FALSE; /* reset before triggering any autocommands */\n#endif\n\n curbuf->b_no_eol_lnum = 0;\t/* in case it was set by the previous read */\n\n /*\n * If there is no file name yet, use the one for the read file.\n * BF_NOTEDITED is set to reflect this.\n * Don't do this for a read from a filter.\n * Only do this when 'cpoptions' contains the 'f' flag.\n */\n if (curbuf->b_ffname == NULL\n\t && !filtering\n\t && fname != NULL\n\t && vim_strchr(p_cpo, CPO_FNAMER) != NULL\n\t && !(flags & READ_DUMMY))\n {\n\tif (set_rw_fname(fname, sfname) == FAIL)\n\t return FAIL;\n }\n\n#ifdef FEAT_AUTOCMD\n /* Remember the initial values of curbuf, curbuf->b_ffname and\n * curbuf->b_fname to detect whether they are altered as a result of\n * executing nasty autocommands. Also check if \"fname\" and \"sfname\"\n * point to one of these values. */\n old_curbuf = curbuf;\n old_b_ffname = curbuf->b_ffname;\n old_b_fname = curbuf->b_fname;\n using_b_ffname = (fname == curbuf->b_ffname)\n\t\t\t\t\t || (sfname == curbuf->b_ffname);\n using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);\n#endif\n\n /* After reading a file the cursor line changes but we don't want to\n * display the line. */\n ex_no_reprint = TRUE;\n\n /* don't display the file info for another buffer now */\n need_fileinfo = FALSE;\n\n /*\n * For Unix: Use the short file name whenever possible.\n * Avoids problems with networks and when directory names are changed.\n * Don't do this for MS-DOS, a \"cd\" in a sub-shell may have moved us to\n * another directory, which we don't detect.\n */\n if (sfname == NULL)\n\tsfname = fname;\n#if defined(UNIX)\n fname = sfname;\n#endif\n\n#ifdef FEAT_AUTOCMD\n /*\n * The BufReadCmd and FileReadCmd events intercept the reading process by\n * executing the associated commands instead.\n */\n if (!filtering && !read_stdin && !read_buffer)\n {\n\tpos_T\t pos;\n\n\tpos = curbuf->b_op_start;\n\n\t/* Set '[ mark to the line above where the lines go (line 1 if zero). */\n\tcurbuf->b_op_start.lnum = ((from == 0) ? 1 : from);\n\tcurbuf->b_op_start.col = 0;\n\n\tif (newfile)\n\t{\n\t if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap))\n#ifdef FEAT_EVAL\n\t\treturn aborting() ? FAIL : OK;\n#else\n\t\treturn OK;\n#endif\n\t}\n\telse if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap))\n#ifdef FEAT_EVAL\n\t return aborting() ? FAIL : OK;\n#else\n\t return OK;\n#endif\n\n\tcurbuf->b_op_start = pos;\n }\n#endif\n\n if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)\n\tmsg_scroll = FALSE;\t/* overwrite previous file message */\n else\n\tmsg_scroll = TRUE;\t/* don't overwrite previous file message */\n\n /*\n * If the name ends in a path separator, we can't open it. Check here,\n * because reading the file may actually work, but then creating the swap\n * file may destroy it! Reported on MS-DOS and Win 95.\n * If the name is too long we might crash further on, quit here.\n */\n if (fname != NULL && *fname != NUL)\n {\n\tp = fname + STRLEN(fname);\n\tif (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)\n\t{\n\t filemess(curbuf, fname, (char_u *)_(\"Illegal file name\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return FAIL;\n\t}\n }\n\n if (!read_stdin && !read_buffer && !read_fifo)\n {\n#ifdef UNIX\n\t/*\n\t * On Unix it is possible to read a directory, so we have to\n\t * check for it before the mch_open().\n\t */\n\tperm = mch_getperm(fname);\n\tif (perm >= 0 && !S_ISREG(perm)\t\t /* not a regular file ... */\n# ifdef S_ISFIFO\n\t\t && !S_ISFIFO(perm)\t /* ... or fifo */\n# endif\n# ifdef S_ISSOCK\n\t\t && !S_ISSOCK(perm)\t /* ... or socket */\n# endif\n# ifdef OPEN_CHR_FILES\n\t\t && !(S_ISCHR(perm) && is_dev_fd_file(fname))\n\t\t\t/* ... or a character special file named /dev/fd/<n> */\n# endif\n\t\t\t\t\t\t)\n\t{\n\t int retval = FAIL;\n\n\t if (S_ISDIR(perm))\n\t {\n\t\tfilemess(curbuf, fname, (char_u *)_(\"is a directory\"), 0);\n\t\tretval = NOTDONE;\n\t }\n\t else\n\t\tfilemess(curbuf, fname, (char_u *)_(\"is not a file\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return retval;\n\t}\n#endif\n#if defined(MSWIN)\n\t/*\n\t * MS-Windows allows opening a device, but we will probably get stuck\n\t * trying to read it.\n\t */\n\tif (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)\n\t{\n\t filemess(curbuf, fname, (char_u *)_(\"is a device (disabled with 'opendevice' option)\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return FAIL;\n\t}\n#endif\n }\n\n /* Set default or forced 'fileformat' and 'binary'. */\n set_file_options(set_options, eap);\n\n /*\n * When opening a new file we take the readonly flag from the file.\n * Default is r/w, can be set to r/o below.\n * Don't reset it when in readonly mode\n * Only set/reset b_p_ro when BF_CHECK_RO is set.\n */\n check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));\n if (check_readonly && !readonlymode)\n\tcurbuf->b_p_ro = FALSE;\n\n if (newfile && !read_stdin && !read_buffer && !read_fifo)\n {\n\t/* Remember time of file. */\n\tif (mch_stat((char *)fname, &st) >= 0)\n\t{\n\t buf_store_time(curbuf, &st, fname);\n\t curbuf->b_mtime_read = curbuf->b_mtime;\n#ifdef UNIX\n\t /*\n\t * Use the protection bits of the original file for the swap file.\n\t * This makes it possible for others to read the name of the\n\t * edited file from the swapfile, but only if they can read the\n\t * edited file.\n\t * Remove the \"write\" and \"execute\" bits for group and others\n\t * (they must not write the swapfile).\n\t * Add the \"read\" and \"write\" bits for the user, otherwise we may\n\t * not be able to write to the file ourselves.\n\t * Setting the bits is done below, after creating the swap file.\n\t */\n\t swap_mode = (st.st_mode & 0644) | 0600;\n#endif\n#ifdef FEAT_CW_EDITOR\n\t /* Get the FSSpec on MacOS\n\t * TODO: Update it properly when the buffer name changes\n\t */\n\t (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);\n#endif\n#ifdef VMS\n\t curbuf->b_fab_rfm = st.st_fab_rfm;\n\t curbuf->b_fab_rat = st.st_fab_rat;\n\t curbuf->b_fab_mrs = st.st_fab_mrs;\n#endif\n\t}\n\telse\n\t{\n\t curbuf->b_mtime = 0;\n\t curbuf->b_mtime_read = 0;\n\t curbuf->b_orig_size = 0;\n\t curbuf->b_orig_mode = 0;\n\t}\n\n\t/* Reset the \"new file\" flag. It will be set again below when the\n\t * file doesn't exist. */\n\tcurbuf->b_flags &= ~(BF_NEW | BF_NEW_W);\n }\n\n/*\n * for UNIX: check readonly with perm and mch_access()\n * for Amiga: check readonly by trying to open the file for writing\n */\n file_readonly = FALSE;\n if (read_stdin)\n {\n#if defined(MSWIN)\n\t/* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */\n\tsetmode(0, O_BINARY);\n#endif\n }\n else if (!read_buffer)\n {\n#ifdef USE_MCH_ACCESS\n\tif (\n# ifdef UNIX\n\t !(perm & 0222) ||\n# endif\n\t\t\t\tmch_access((char *)fname, W_OK))\n\t file_readonly = TRUE;\n\tfd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);\n#else\n\tif (!newfile\n\t\t|| readonlymode\n\t\t|| (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)\n\t{\n\t file_readonly = TRUE;\n\t /* try to open ro */\n\t fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);\n\t}\n#endif\n }\n\n if (fd < 0)\t\t\t /* cannot open at all */\n {\n#ifndef UNIX\n\tint\tisdir_f;\n#endif\n\tmsg_scroll = msg_save;\n#ifndef UNIX\n\t/*\n\t * On Amiga we can't open a directory, check here.\n\t */\n\tisdir_f = (mch_isdir(fname));\n\tperm = mch_getperm(fname); /* check if the file exists */\n\tif (isdir_f)\n\t{\n\t filemess(curbuf, sfname, (char_u *)_(\"is a directory\"), 0);\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t}\n\telse\n#endif\n\t if (newfile)\n\t {\n\t\tif (perm < 0\n#ifdef ENOENT\n\t\t\t&& errno == ENOENT\n#endif\n\t\t )\n\t\t{\n\t\t /*\n\t\t * Set the 'new-file' flag, so that when the file has\n\t\t * been created by someone else, a \":w\" will complain.\n\t\t */\n\t\t curbuf->b_flags |= BF_NEW;\n\n\t\t /* Create a swap file now, so that other Vims are warned\n\t\t * that we are editing this file. Don't do this for a\n\t\t * \"nofile\" or \"nowrite\" buffer type. */\n#ifdef FEAT_QUICKFIX\n\t\t if (!bt_dontwrite(curbuf))\n#endif\n\t\t {\n\t\t\tcheck_need_swap(newfile);\n#ifdef FEAT_AUTOCMD\n\t\t\t/* SwapExists autocommand may mess things up */\n\t\t\tif (curbuf != old_curbuf\n\t\t\t\t|| (using_b_ffname\n\t\t\t\t\t&& (old_b_ffname != curbuf->b_ffname))\n\t\t\t\t|| (using_b_fname\n\t\t\t\t\t && (old_b_fname != curbuf->b_fname)))\n\t\t\t{\n\t\t\t EMSG(_(e_auchangedbuf));\n\t\t\t return FAIL;\n\t\t\t}\n#endif\n\t\t }\n\t\t if (dir_of_file_exists(fname))\n\t\t\tfilemess(curbuf, sfname, (char_u *)_(\"[New File]\"), 0);\n\t\t else\n\t\t\tfilemess(curbuf, sfname,\n\t\t\t\t\t (char_u *)_(\"[New DIRECTORY]\"), 0);\n#ifdef FEAT_VIMINFO\n\t\t /* Even though this is a new file, it might have been\n\t\t * edited before and deleted. Get the old marks. */\n\t\t check_marks_read();\n#endif\n#ifdef FEAT_MBYTE\n\t\t /* Set forced 'fileencoding'. */\n\t\t if (eap != NULL)\n\t\t\tset_forced_fenc(eap);\n#endif\n#ifdef FEAT_AUTOCMD\n\t\t apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n#endif\n\t\t /* remember the current fileformat */\n\t\t save_file_ff(curbuf);\n\n#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)\n\t\t if (aborting()) /* autocmds may abort script processing */\n\t\t\treturn FAIL;\n#endif\n\t\t return OK;\t /* a new file is not an error */\n\t\t}\n\t\telse\n\t\t{\n\t\t filemess(curbuf, sfname, (char_u *)(\n# ifdef EFBIG\n\t\t\t (errno == EFBIG) ? _(\"[File too big]\") :\n# endif\n# ifdef EOVERFLOW\n\t\t\t (errno == EOVERFLOW) ? _(\"[File too big]\") :\n# endif\n\t\t\t\t\t\t_(\"[Permission Denied]\")), 0);\n\t\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t\t}\n\t }\n\n\treturn FAIL;\n }\n\n /*\n * Only set the 'ro' flag for readonly files the first time they are\n * loaded.\tHelp files always get readonly mode\n */\n if ((check_readonly && file_readonly) || curbuf->b_help)\n\tcurbuf->b_p_ro = TRUE;\n\n if (set_options)\n {\n\t/* Don't change 'eol' if reading from buffer as it will already be\n\t * correctly set when reading stdin. */\n\tif (!read_buffer)\n\t{\n\t curbuf->b_p_eol = TRUE;\n\t curbuf->b_start_eol = TRUE;\n\t}\n#ifdef FEAT_MBYTE\n\tcurbuf->b_p_bomb = FALSE;\n\tcurbuf->b_start_bomb = FALSE;\n#endif\n }\n\n /* Create a swap file now, so that other Vims are warned that we are\n * editing this file.\n * Don't do this for a \"nofile\" or \"nowrite\" buffer type. */\n#ifdef FEAT_QUICKFIX\n if (!bt_dontwrite(curbuf))\n#endif\n {\n\tcheck_need_swap(newfile);\n#ifdef FEAT_AUTOCMD\n\tif (!read_stdin && (curbuf != old_curbuf\n\t\t|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))\n\t\t|| (using_b_fname && (old_b_fname != curbuf->b_fname))))\n\t{\n\t EMSG(_(e_auchangedbuf));\n\t if (!read_buffer)\n\t\tclose(fd);\n\t return FAIL;\n\t}\n#endif\n#ifdef UNIX\n\t/* Set swap file protection bits after creating it. */\n\tif (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL\n\t\t\t && curbuf->b_ml.ml_mfp->mf_fname != NULL)\n\t (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);\n#endif\n }\n\n#if defined(HAS_SWAP_EXISTS_ACTION)\n /* If \"Quit\" selected at ATTENTION dialog, don't load the file */\n if (swap_exists_action == SEA_QUIT)\n {\n\tif (!read_buffer && !read_stdin)\n\t close(fd);\n\treturn FAIL;\n }\n#endif\n\n ++no_wait_return;\t /* don't wait for return yet */\n\n /*\n * Set '[ mark to the line above where the lines go (line 1 if zero).\n */\n curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);\n curbuf->b_op_start.col = 0;\n\n try_mac = (vim_strchr(p_ffs, 'm') != NULL);\n try_dos = (vim_strchr(p_ffs, 'd') != NULL);\n try_unix = (vim_strchr(p_ffs, 'x') != NULL);\n\n#ifdef FEAT_AUTOCMD\n if (!read_buffer)\n {\n\tint\tm = msg_scroll;\n\tint\tn = msg_scrolled;\n\n\t/*\n\t * The file must be closed again, the autocommands may want to change\n\t * the file before reading it.\n\t */\n\tif (!read_stdin)\n\t close(fd);\t\t/* ignore errors */\n\n\t/*\n\t * The output from the autocommands should not overwrite anything and\n\t * should not be overwritten: Set msg_scroll, restore its value if no\n\t * output was done.\n\t */\n\tmsg_scroll = TRUE;\n\tif (filtering)\n\t apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (read_stdin)\n\t apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (newfile)\n\t apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse\n\t apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap);\n\t/* autocommands may have changed it */\n\ttry_mac = (vim_strchr(p_ffs, 'm') != NULL);\n\ttry_dos = (vim_strchr(p_ffs, 'd') != NULL);\n\ttry_unix = (vim_strchr(p_ffs, 'x') != NULL);\n\n\tif (msg_scrolled == n)\n\t msg_scroll = m;\n\n#ifdef FEAT_EVAL\n\tif (aborting())\t /* autocmds may abort script processing */\n\t{\n\t --no_wait_return;\n\t msg_scroll = msg_save;\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t return FAIL;\n\t}\n#endif\n\t/*\n\t * Don't allow the autocommands to change the current buffer.\n\t * Try to re-open the file.\n\t *\n\t * Don't allow the autocommands to change the buffer name either\n\t * (cd for example) if it invalidates fname or sfname.\n\t */\n\tif (!read_stdin && (curbuf != old_curbuf\n\t\t|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))\n\t\t|| (using_b_fname && (old_b_fname != curbuf->b_fname))\n\t\t|| (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))\n\t{\n\t --no_wait_return;\n\t msg_scroll = msg_save;\n\t if (fd < 0)\n\t\tEMSG(_(\"E200: *ReadPre autocommands made the file unreadable\"));\n\t else\n\t\tEMSG(_(\"E201: *ReadPre autocommands must not change current buffer\"));\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t return FAIL;\n\t}\n }\n#endif /* FEAT_AUTOCMD */\n\n /* Autocommands may add lines to the file, need to check if it is empty */\n wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);\n\n if (!recoverymode && !filtering && !(flags & READ_DUMMY))\n {\n\t/*\n\t * Show the user that we are busy reading the input. Sometimes this\n\t * may take a while. When reading from stdin another program may\n\t * still be running, don't move the cursor to the last line, unless\n\t * always using the GUI.\n\t */\n\tif (read_stdin)\n\t{\n#ifndef ALWAYS_USE_GUI\n\t mch_msg(_(\"Vim: Reading from stdin...\\n\"));\n#endif\n#ifdef FEAT_GUI\n\t /* Also write a message in the GUI window, if there is one. */\n\t if (gui.in_use && !gui.dying && !gui.starting)\n\t {\n\t\tp = (char_u *)_(\"Reading from stdin...\");\n\t\tgui_write(p, (int)STRLEN(p));\n\t }\n#endif\n\t}\n\telse if (!read_buffer)\n\t filemess(curbuf, sfname, (char_u *)\"\", 0);\n }\n\n msg_scroll = FALSE;\t\t\t/* overwrite the file message */\n\n /*\n * Set linecnt now, before the \"retry\" caused by a wrong guess for\n * fileformat, and after the autocommands, which may change them.\n */\n linecnt = curbuf->b_ml.ml_line_count;\n\n#ifdef FEAT_MBYTE\n /* \"++bad=\" argument. */\n if (eap != NULL && eap->bad_char != 0)\n {\n\tbad_char_behavior = eap->bad_char;\n\tif (set_options)\n\t curbuf->b_bad_char = eap->bad_char;\n }\n else\n\tcurbuf->b_bad_char = 0;\n\n /*\n * Decide which 'encoding' to use or use first.\n */\n if (eap != NULL && eap->force_enc != 0)\n {\n\tfenc = enc_canonize(eap->cmd + eap->force_enc);\n\tfenc_alloced = TRUE;\n\tkeep_dest_enc = TRUE;\n }\n else if (curbuf->b_p_bin)\n {\n\tfenc = (char_u *)\"\";\t\t/* binary: don't convert */\n\tfenc_alloced = FALSE;\n }\n else if (curbuf->b_help)\n {\n\tchar_u\t firstline[80];\n\tint\t fc;\n\n\t/* Help files are either utf-8 or latin1. Try utf-8 first, if this\n\t * fails it must be latin1.\n\t * Always do this when 'encoding' is \"utf-8\". Otherwise only do\n\t * this when needed to avoid [converted] remarks all the time.\n\t * It is needed when the first line contains non-ASCII characters.\n\t * That is only in *.??x files. */\n\tfenc = (char_u *)\"latin1\";\n\tc = enc_utf8;\n\tif (!c && !read_stdin)\n\t{\n\t fc = fname[STRLEN(fname) - 1];\n\t if (TOLOWER_ASC(fc) == 'x')\n\t {\n\t\t/* Read the first line (and a bit more). Immediately rewind to\n\t\t * the start of the file. If the read() fails \"len\" is -1. */\n\t\tlen = read_eintr(fd, firstline, 80);\n\t\tvim_lseek(fd, (off_T)0L, SEEK_SET);\n\t\tfor (p = firstline; p < firstline + len; ++p)\n\t\t if (*p >= 0x80)\n\t\t {\n\t\t\tc = TRUE;\n\t\t\tbreak;\n\t\t }\n\t }\n\t}\n\n\tif (c)\n\t{\n\t fenc_next = fenc;\n\t fenc = (char_u *)\"utf-8\";\n\n\t /* When the file is utf-8 but a character doesn't fit in\n\t * 'encoding' don't retry. In help text editing utf-8 bytes\n\t * doesn't make sense. */\n\t if (!enc_utf8)\n\t\tkeep_dest_enc = TRUE;\n\t}\n\tfenc_alloced = FALSE;\n }\n else if (*p_fencs == NUL)\n {\n\tfenc = curbuf->b_p_fenc;\t/* use format from buffer */\n\tfenc_alloced = FALSE;\n }\n else\n {\n\tfenc_next = p_fencs;\t\t/* try items in 'fileencodings' */\n\tfenc = next_fenc(&fenc_next);\n\tfenc_alloced = TRUE;\n }\n#endif\n\n /*\n * Jump back here to retry reading the file in different ways.\n * Reasons to retry:\n * - encoding conversion failed: try another one from \"fenc_next\"\n * - BOM detected and fenc was set, need to setup conversion\n * - \"fileformat\" check failed: try another\n *\n * Variables set for special retry actions:\n * \"file_rewind\"\tRewind the file to start reading it again.\n * \"advance_fenc\"\tAdvance \"fenc\" using \"fenc_next\".\n * \"skip_read\"\tRe-use already read bytes (BOM detected).\n * \"did_iconv\"\ticonv() conversion failed, try 'charconvert'.\n * \"keep_fileformat\" Don't reset \"fileformat\".\n *\n * Other status indicators:\n * \"tmpname\"\tWhen != NULL did conversion with 'charconvert'.\n *\t\t\tOutput file has to be deleted afterwards.\n * \"iconv_fd\"\tWhen != -1 did conversion with iconv().\n */\nretry:\n\n if (file_rewind)\n {\n\tif (read_buffer)\n\t{\n\t read_buf_lnum = 1;\n\t read_buf_col = 0;\n\t}\n\telse if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)\n\t{\n\t /* Can't rewind the file, give up. */\n\t error = TRUE;\n\t goto failed;\n\t}\n\t/* Delete the previously read lines. */\n\twhile (lnum > from)\n\t ml_delete(lnum--, FALSE);\n\tfile_rewind = FALSE;\n#ifdef FEAT_MBYTE\n\tif (set_options)\n\t{\n\t curbuf->b_p_bomb = FALSE;\n\t curbuf->b_start_bomb = FALSE;\n\t}\n\tconv_error = 0;\n#endif\n }\n\n /*\n * When retrying with another \"fenc\" and the first time \"fileformat\"\n * will be reset.\n */\n if (keep_fileformat)\n\tkeep_fileformat = FALSE;\n else\n {\n\tif (eap != NULL && eap->force_ff != 0)\n\t{\n\t fileformat = get_fileformat_force(curbuf, eap);\n\t try_unix = try_dos = try_mac = FALSE;\n\t}\n\telse if (curbuf->b_p_bin)\n\t fileformat = EOL_UNIX;\t\t/* binary: use Unix format */\n\telse if (*p_ffs == NUL)\n\t fileformat = get_fileformat(curbuf);/* use format from buffer */\n\telse\n\t fileformat = EOL_UNKNOWN;\t\t/* detect from file */\n }\n\n#ifdef FEAT_MBYTE\n# ifdef USE_ICONV\n if (iconv_fd != (iconv_t)-1)\n {\n\t/* aborted conversion with iconv(), close the descriptor */\n\ticonv_close(iconv_fd);\n\ticonv_fd = (iconv_t)-1;\n }\n# endif\n\n if (advance_fenc)\n {\n\t/*\n\t * Try the next entry in 'fileencodings'.\n\t */\n\tadvance_fenc = FALSE;\n\n\tif (eap != NULL && eap->force_enc != 0)\n\t{\n\t /* Conversion given with \"++cc=\" wasn't possible, read\n\t * without conversion. */\n\t notconverted = TRUE;\n\t conv_error = 0;\n\t if (fenc_alloced)\n\t\tvim_free(fenc);\n\t fenc = (char_u *)\"\";\n\t fenc_alloced = FALSE;\n\t}\n\telse\n\t{\n\t if (fenc_alloced)\n\t\tvim_free(fenc);\n\t if (fenc_next != NULL)\n\t {\n\t\tfenc = next_fenc(&fenc_next);\n\t\tfenc_alloced = (fenc_next != NULL);\n\t }\n\t else\n\t {\n\t\tfenc = (char_u *)\"\";\n\t\tfenc_alloced = FALSE;\n\t }\n\t}\n\tif (tmpname != NULL)\n\t{\n\t mch_remove(tmpname);\t\t/* delete converted file */\n\t vim_free(tmpname);\n\t tmpname = NULL;\n\t}\n }\n\n /*\n * Conversion may be required when the encoding of the file is different\n * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.\n */\n fio_flags = 0;\n converted = need_conversion(fenc);\n if (converted)\n {\n\n\t/* \"ucs-bom\" means we need to check the first bytes of the file\n\t * for a BOM. */\n\tif (STRCMP(fenc, ENC_UCSBOM) == 0)\n\t fio_flags = FIO_UCSBOM;\n\n\t/*\n\t * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be\n\t * done. This is handled below after read(). Prepare the\n\t * fio_flags to avoid having to parse the string each time.\n\t * Also check for Unicode to Latin1 conversion, because iconv()\n\t * appears not to handle this correctly. This works just like\n\t * conversion to UTF-8 except how the resulting character is put in\n\t * the buffer.\n\t */\n\telse if (enc_utf8 || STRCMP(p_enc, \"latin1\") == 0)\n\t fio_flags = get_fio_flags(fenc);\n\n# ifdef WIN3264\n\t/*\n\t * Conversion from an MS-Windows codepage to UTF-8 or another codepage\n\t * is handled with MultiByteToWideChar().\n\t */\n\tif (fio_flags == 0)\n\t fio_flags = get_win_fio_flags(fenc);\n# endif\n\n# ifdef MACOS_CONVERT\n\t/* Conversion from Apple MacRoman to latin1 or UTF-8 */\n\tif (fio_flags == 0)\n\t fio_flags = get_mac_fio_flags(fenc);\n# endif\n\n# ifdef USE_ICONV\n\t/*\n\t * Try using iconv() if we can't convert internally.\n\t */\n\tif (fio_flags == 0\n# ifdef FEAT_EVAL\n\t\t&& !did_iconv\n# endif\n\t\t)\n\t iconv_fd = (iconv_t)my_iconv_open(\n\t\t\t\t enc_utf8 ? (char_u *)\"utf-8\" : p_enc, fenc);\n# endif\n\n# ifdef FEAT_EVAL\n\t/*\n\t * Use the 'charconvert' expression when conversion is required\n\t * and we can't do it internally or with iconv().\n\t */\n\tif (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL\n\t\t\t\t\t\t && !read_fifo\n# ifdef USE_ICONV\n\t\t\t\t\t\t && iconv_fd == (iconv_t)-1\n# endif\n\t\t)\n\t{\n# ifdef USE_ICONV\n\t did_iconv = FALSE;\n# endif\n\t /* Skip conversion when it's already done (retry for wrong\n\t * \"fileformat\"). */\n\t if (tmpname == NULL)\n\t {\n\t\ttmpname = readfile_charconvert(fname, fenc, &fd);\n\t\tif (tmpname == NULL)\n\t\t{\n\t\t /* Conversion failed. Try another one. */\n\t\t advance_fenc = TRUE;\n\t\t if (fd < 0)\n\t\t {\n\t\t\t/* Re-opening the original file failed! */\n\t\t\tEMSG(_(\"E202: Conversion made file unreadable!\"));\n\t\t\terror = TRUE;\n\t\t\tgoto failed;\n\t\t }\n\t\t goto retry;\n\t\t}\n\t }\n\t}\n\telse\n# endif\n\t{\n\t if (fio_flags == 0\n# ifdef USE_ICONV\n\t\t && iconv_fd == (iconv_t)-1\n# endif\n\t )\n\t {\n\t\t/* Conversion wanted but we can't.\n\t\t * Try the next conversion in 'fileencodings' */\n\t\tadvance_fenc = TRUE;\n\t\tgoto retry;\n\t }\n\t}\n }\n\n /* Set \"can_retry\" when it's possible to rewind the file and try with\n * another \"fenc\" value. It's FALSE when no other \"fenc\" to try, reading\n * stdin or fixed at a specific encoding. */\n can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);\n#endif\n\n if (!skip_read)\n {\n\tlinerest = 0;\n\tfilesize = 0;\n\tskip_count = lines_to_skip;\n\tread_count = lines_to_read;\n#ifdef FEAT_MBYTE\n\tconv_restlen = 0;\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\tread_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0\n\t\t\t\t && curbuf->b_ffname != NULL\n\t\t\t\t && curbuf->b_p_udf\n\t\t\t\t && !filtering\n\t\t\t\t && !read_fifo\n\t\t\t\t && !read_stdin\n\t\t\t\t && !read_buffer);\n\tif (read_undo_file)\n\t sha256_start(&sha_ctx);\n#endif\n#ifdef FEAT_CRYPT\n\tif (curbuf->b_cryptstate != NULL)\n\t{\n\t /* Need to free the state, but keep the key, don't want to ask for\n\t * it again. */\n\t crypt_free_state(curbuf->b_cryptstate);\n\t curbuf->b_cryptstate = NULL;\n\t}\n#endif\n }\n\n while (!error && !got_int)\n {\n\t/*\n\t * We allocate as much space for the file as we can get, plus\n\t * space for the old line plus room for one terminating NUL.\n\t * The amount is limited by the fact that read() only can read\n\t * upto max_unsigned characters (and other things).\n\t */\n#if VIM_SIZEOF_INT <= 2\n\tif (linerest >= 0x7ff0)\n\t{\n\t ++split;\n\t *ptr = NL;\t\t /* split line by inserting a NL */\n\t size = 1;\n\t}\n\telse\n#endif\n\t{\n\t if (!skip_read)\n\t {\n#if VIM_SIZEOF_INT > 2\n# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)\n\t\tsize = SSIZE_MAX;\t\t /* use max I/O size, 52K */\n# else\n\t\tsize = 0x10000L;\t\t /* use buffer >= 64K */\n# endif\n#else\n\t\tsize = 0x7ff0L - linerest;\t /* limit buffer to 32K */\n#endif\n\n\t\tfor ( ; size >= 10; size = (long)((long_u)size >> 1))\n\t\t{\n\t\t if ((new_buffer = lalloc((long_u)(size + linerest + 1),\n\t\t\t\t\t\t\t FALSE)) != NULL)\n\t\t\tbreak;\n\t\t}\n\t\tif (new_buffer == NULL)\n\t\t{\n\t\t do_outofmem_msg((long_u)(size * 2 + linerest + 1));\n\t\t error = TRUE;\n\t\t break;\n\t\t}\n\t\tif (linerest)\t/* copy characters from the previous buffer */\n\t\t mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);\n\t\tvim_free(buffer);\n\t\tbuffer = new_buffer;\n\t\tptr = buffer + linerest;\n\t\tline_start = buffer;\n\n#ifdef FEAT_MBYTE\n\t\t/* May need room to translate into.\n\t\t * For iconv() we don't really know the required space, use a\n\t\t * factor ICONV_MULT.\n\t\t * latin1 to utf-8: 1 byte becomes up to 2 bytes\n\t\t * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes\n\t\t * become up to 4 bytes, size must be multiple of 2\n\t\t * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be\n\t\t * multiple of 2\n\t\t * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be\n\t\t * multiple of 4 */\n\t\treal_size = (int)size;\n# ifdef USE_ICONV\n\t\tif (iconv_fd != (iconv_t)-1)\n\t\t size = size / ICONV_MULT;\n\t\telse\n# endif\n\t\t if (fio_flags & FIO_LATIN1)\n\t\t size = size / 2;\n\t\telse if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t size = (size * 2 / 3) & ~1;\n\t\telse if (fio_flags & FIO_UCS4)\n\t\t size = (size * 2 / 3) & ~3;\n\t\telse if (fio_flags == FIO_UCSBOM)\n\t\t size = size / ICONV_MULT;\t/* worst case */\n# ifdef WIN3264\n\t\telse if (fio_flags & FIO_CODEPAGE)\n\t\t size = size / ICONV_MULT;\t/* also worst case */\n# endif\n# ifdef MACOS_CONVERT\n\t\telse if (fio_flags & FIO_MACROMAN)\n\t\t size = size / ICONV_MULT;\t/* also worst case */\n# endif\n#endif\n\n#ifdef FEAT_MBYTE\n\t\tif (conv_restlen > 0)\n\t\t{\n\t\t /* Insert unconverted bytes from previous line. */\n\t\t mch_memmove(ptr, conv_rest, conv_restlen);\n\t\t ptr += conv_restlen;\n\t\t size -= conv_restlen;\n\t\t}\n#endif\n\n\t\tif (read_buffer)\n\t\t{\n\t\t /*\n\t\t * Read bytes from curbuf. Used for converting text read\n\t\t * from stdin.\n\t\t */\n\t\t if (read_buf_lnum > from)\n\t\t\tsize = 0;\n\t\t else\n\t\t {\n\t\t\tint\tn, ni;\n\t\t\tlong\ttlen;\n\n\t\t\ttlen = 0;\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t p = ml_get(read_buf_lnum) + read_buf_col;\n\t\t\t n = (int)STRLEN(p);\n\t\t\t if ((int)tlen + n + 1 > size)\n\t\t\t {\n\t\t\t\t/* Filled up to \"size\", append partial line.\n\t\t\t\t * Change NL to NUL to reverse the effect done\n\t\t\t\t * below. */\n\t\t\t\tn = (int)(size - tlen);\n\t\t\t\tfor (ni = 0; ni < n; ++ni)\n\t\t\t\t{\n\t\t\t\t if (p[ni] == NL)\n\t\t\t\t\tptr[tlen++] = NUL;\n\t\t\t\t else\n\t\t\t\t\tptr[tlen++] = p[ni];\n\t\t\t\t}\n\t\t\t\tread_buf_col += n;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\t/* Append whole line and new-line. Change NL\n\t\t\t\t * to NUL to reverse the effect done below. */\n\t\t\t\tfor (ni = 0; ni < n; ++ni)\n\t\t\t\t{\n\t\t\t\t if (p[ni] == NL)\n\t\t\t\t\tptr[tlen++] = NUL;\n\t\t\t\t else\n\t\t\t\t\tptr[tlen++] = p[ni];\n\t\t\t\t}\n\t\t\t\tptr[tlen++] = NL;\n\t\t\t\tread_buf_col = 0;\n\t\t\t\tif (++read_buf_lnum > from)\n\t\t\t\t{\n\t\t\t\t /* When the last line didn't have an\n\t\t\t\t * end-of-line don't add it now either. */\n\t\t\t\t if (!curbuf->b_p_eol)\n\t\t\t\t\t--tlen;\n\t\t\t\t size = tlen;\n\t\t\t\t break;\n\t\t\t\t}\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t /*\n\t\t * Read bytes from the file.\n\t\t */\n\t\t size = read_eintr(fd, ptr, size);\n\t\t}\n\n#ifdef FEAT_CRYPT\n\t\t/*\n\t\t * At start of file: Check for magic number of encryption.\n\t\t */\n\t\tif (filesize == 0 && size > 0)\n\t\t cryptkey = check_for_cryptkey(cryptkey, ptr, &size,\n\t\t\t\t\t\t &filesize, newfile, sfname,\n\t\t\t\t\t\t &did_ask_for_key);\n\t\t/*\n\t\t * Decrypt the read bytes. This is done before checking for\n\t\t * EOF because the crypt layer may be buffering.\n\t\t */\n\t\tif (cryptkey != NULL && curbuf->b_cryptstate != NULL\n\t\t\t\t\t\t\t\t && size > 0)\n\t\t{\n\t\t if (crypt_works_inplace(curbuf->b_cryptstate))\n\t\t {\n\t\t\tcrypt_decode_inplace(curbuf->b_cryptstate, ptr, size);\n\t\t }\n\t\t else\n\t\t {\n\t\t\tchar_u\t*newptr = NULL;\n\t\t\tint\tdecrypted_size;\n\n\t\t\tdecrypted_size = crypt_decode_alloc(\n\t\t\t\t curbuf->b_cryptstate, ptr, size, &newptr);\n\n\t\t\t/* If the crypt layer is buffering, not producing\n\t\t\t * anything yet, need to read more. */\n\t\t\tif (size > 0 && decrypted_size == 0)\n\t\t\t continue;\n\n\t\t\tif (linerest == 0)\n\t\t\t{\n\t\t\t /* Simple case: reuse returned buffer (may be\n\t\t\t * NULL, checked later). */\n\t\t\t new_buffer = newptr;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t long_u\tnew_size;\n\n\t\t\t /* Need new buffer to add bytes carried over. */\n\t\t\t new_size = (long_u)(decrypted_size + linerest + 1);\n\t\t\t new_buffer = lalloc(new_size, FALSE);\n\t\t\t if (new_buffer == NULL)\n\t\t\t {\n\t\t\t\tdo_outofmem_msg(new_size);\n\t\t\t\terror = TRUE;\n\t\t\t\tbreak;\n\t\t\t }\n\n\t\t\t mch_memmove(new_buffer, buffer, linerest);\n\t\t\t if (newptr != NULL)\n\t\t\t\tmch_memmove(new_buffer + linerest, newptr,\n\t\t\t\t\t\t\t decrypted_size);\n\t\t\t}\n\n\t\t\tif (new_buffer != NULL)\n\t\t\t{\n\t\t\t vim_free(buffer);\n\t\t\t buffer = new_buffer;\n\t\t\t new_buffer = NULL;\n\t\t\t line_start = buffer;\n\t\t\t ptr = buffer + linerest;\n\t\t\t}\n\t\t\tsize = decrypted_size;\n\t\t }\n\t\t}\n#endif\n\n\t\tif (size <= 0)\n\t\t{\n\t\t if (size < 0)\t\t /* read error */\n\t\t\terror = TRUE;\n#ifdef FEAT_MBYTE\n\t\t else if (conv_restlen > 0)\n\t\t {\n\t\t\t/*\n\t\t\t * Reached end-of-file but some trailing bytes could\n\t\t\t * not be converted. Truncated file?\n\t\t\t */\n\n\t\t\t/* When we did a conversion report an error. */\n\t\t\tif (fio_flags != 0\n# ifdef USE_ICONV\n\t\t\t\t|| iconv_fd != (iconv_t)-1\n# endif\n\t\t\t )\n\t\t\t{\n\t\t\t if (can_retry)\n\t\t\t\tgoto rewind_retry;\n\t\t\t if (conv_error == 0)\n\t\t\t\tconv_error = curbuf->b_ml.ml_line_count\n\t\t\t\t\t\t\t\t- linecnt + 1;\n\t\t\t}\n\t\t\t/* Remember the first linenr with an illegal byte */\n\t\t\telse if (illegal_byte == 0)\n\t\t\t illegal_byte = curbuf->b_ml.ml_line_count\n\t\t\t\t\t\t\t\t- linecnt + 1;\n\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t{\n\t\t\t *(ptr - conv_restlen) = NUL;\n\t\t\t conv_restlen = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t /* Replace the trailing bytes with the replacement\n\t\t\t * character if we were converting; if we weren't,\n\t\t\t * leave the UTF8 checking code to do it, as it\n\t\t\t * works slightly differently. */\n\t\t\t if (bad_char_behavior != BAD_KEEP && (fio_flags != 0\n# ifdef USE_ICONV\n\t\t\t\t || iconv_fd != (iconv_t)-1\n# endif\n\t\t\t ))\n\t\t\t {\n\t\t\t\twhile (conv_restlen > 0)\n\t\t\t\t{\n\t\t\t\t *(--ptr) = bad_char_behavior;\n\t\t\t\t --conv_restlen;\n\t\t\t\t}\n\t\t\t }\n\t\t\t fio_flags = 0;\t/* don't convert this */\n# ifdef USE_ICONV\n\t\t\t if (iconv_fd != (iconv_t)-1)\n\t\t\t {\n\t\t\t\ticonv_close(iconv_fd);\n\t\t\t\ticonv_fd = (iconv_t)-1;\n\t\t\t }\n# endif\n\t\t\t}\n\t\t }\n#endif\n\t\t}\n\t }\n\t skip_read = FALSE;\n\n#ifdef FEAT_MBYTE\n\t /*\n\t * At start of file (or after crypt magic number): Check for BOM.\n\t * Also check for a BOM for other Unicode encodings, but not after\n\t * converting with 'charconvert' or when a BOM has already been\n\t * found.\n\t */\n\t if ((filesize == 0\n# ifdef FEAT_CRYPT\n\t\t || (cryptkey != NULL\n\t\t\t&& filesize == crypt_get_header_len(\n\t\t\t\t\t\t crypt_get_method_nr(curbuf)))\n# endif\n\t\t )\n\t\t && (fio_flags == FIO_UCSBOM\n\t\t\t|| (!curbuf->b_p_bomb\n\t\t\t && tmpname == NULL\n\t\t\t && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))\n\t {\n\t\tchar_u\t*ccname;\n\t\tint\tblen;\n\n\t\t/* no BOM detection in a short file or in binary mode */\n\t\tif (size < 2 || curbuf->b_p_bin)\n\t\t ccname = NULL;\n\t\telse\n\t\t ccname = check_for_bom(ptr, size, &blen,\n\t\t fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));\n\t\tif (ccname != NULL)\n\t\t{\n\t\t /* Remove BOM from the text */\n\t\t filesize += blen;\n\t\t size -= blen;\n\t\t mch_memmove(ptr, ptr + blen, (size_t)size);\n\t\t if (set_options)\n\t\t {\n\t\t\tcurbuf->b_p_bomb = TRUE;\n\t\t\tcurbuf->b_start_bomb = TRUE;\n\t\t }\n\t\t}\n\n\t\tif (fio_flags == FIO_UCSBOM)\n\t\t{\n\t\t if (ccname == NULL)\n\t\t {\n\t\t\t/* No BOM detected: retry with next encoding. */\n\t\t\tadvance_fenc = TRUE;\n\t\t }\n\t\t else\n\t\t {\n\t\t\t/* BOM detected: set \"fenc\" and jump back */\n\t\t\tif (fenc_alloced)\n\t\t\t vim_free(fenc);\n\t\t\tfenc = ccname;\n\t\t\tfenc_alloced = FALSE;\n\t\t }\n\t\t /* retry reading without getting new bytes or rewinding */\n\t\t skip_read = TRUE;\n\t\t goto retry;\n\t\t}\n\t }\n\n\t /* Include not converted bytes. */\n\t ptr -= conv_restlen;\n\t size += conv_restlen;\n\t conv_restlen = 0;\n#endif\n\t /*\n\t * Break here for a read error or end-of-file.\n\t */\n\t if (size <= 0)\n\t\tbreak;\n\n#ifdef FEAT_MBYTE\n\n# ifdef USE_ICONV\n\t if (iconv_fd != (iconv_t)-1)\n\t {\n\t\t/*\n\t\t * Attempt conversion of the read bytes to 'encoding' using\n\t\t * iconv().\n\t\t */\n\t\tconst char\t*fromp;\n\t\tchar\t\t*top;\n\t\tsize_t\t\tfrom_size;\n\t\tsize_t\t\tto_size;\n\n\t\tfromp = (char *)ptr;\n\t\tfrom_size = size;\n\t\tptr += size;\n\t\ttop = (char *)ptr;\n\t\tto_size = real_size - size;\n\n\t\t/*\n\t\t * If there is conversion error or not enough room try using\n\t\t * another conversion. Except for when there is no\n\t\t * alternative (help files).\n\t\t */\n\t\twhile ((iconv(iconv_fd, (void *)&fromp, &from_size,\n\t\t\t\t\t\t\t &top, &to_size)\n\t\t\t == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)\n\t\t\t\t\t\t || from_size > CONV_RESTLEN)\n\t\t{\n\t\t if (can_retry)\n\t\t\tgoto rewind_retry;\n\t\t if (conv_error == 0)\n\t\t\tconv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t ptr, (char_u *)top);\n\n\t\t /* Deal with a bad byte and continue with the next. */\n\t\t ++fromp;\n\t\t --from_size;\n\t\t if (bad_char_behavior == BAD_KEEP)\n\t\t {\n\t\t\t*top++ = *(fromp - 1);\n\t\t\t--to_size;\n\t\t }\n\t\t else if (bad_char_behavior != BAD_DROP)\n\t\t {\n\t\t\t*top++ = bad_char_behavior;\n\t\t\t--to_size;\n\t\t }\n\t\t}\n\n\t\tif (from_size > 0)\n\t\t{\n\t\t /* Some remaining characters, keep them for the next\n\t\t * round. */\n\t\t mch_memmove(conv_rest, (char_u *)fromp, from_size);\n\t\t conv_restlen = (int)from_size;\n\t\t}\n\n\t\t/* move the linerest to before the converted characters */\n\t\tline_start = ptr - linerest;\n\t\tmch_memmove(line_start, buffer, (size_t)linerest);\n\t\tsize = (long)((char_u *)top - ptr);\n\t }\n# endif\n\n# ifdef WIN3264\n\t if (fio_flags & FIO_CODEPAGE)\n\t {\n\t\tchar_u\t*src, *dst;\n\t\tWCHAR\tucs2buf[3];\n\t\tint\tucs2len;\n\t\tint\tcodepage = FIO_GET_CP(fio_flags);\n\t\tint\tbytelen;\n\t\tint\tfound_bad;\n\t\tchar\treplstr[2];\n\n\t\t/*\n\t\t * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or\n\t\t * a codepage, using standard MS-Windows functions. This\n\t\t * requires two steps:\n\t\t * 1. convert from 'fileencoding' to ucs-2\n\t\t * 2. convert from ucs-2 to 'encoding'\n\t\t *\n\t\t * Because there may be illegal bytes AND an incomplete byte\n\t\t * sequence at the end, we may have to do the conversion one\n\t\t * character at a time to get it right.\n\t\t */\n\n\t\t/* Replacement string for WideCharToMultiByte(). */\n\t\tif (bad_char_behavior > 0)\n\t\t replstr[0] = bad_char_behavior;\n\t\telse\n\t\t replstr[0] = '?';\n\t\treplstr[1] = NUL;\n\n\t\t/*\n\t\t * Move the bytes to the end of the buffer, so that we have\n\t\t * room to put the result at the start.\n\t\t */\n\t\tsrc = ptr + real_size - size;\n\t\tmch_memmove(src, ptr, size);\n\n\t\t/*\n\t\t * Do the conversion.\n\t\t */\n\t\tdst = ptr;\n\t\tsize = size;\n\t\twhile (size > 0)\n\t\t{\n\t\t found_bad = FALSE;\n\n# ifdef CP_UTF8\t/* VC 4.1 doesn't define CP_UTF8 */\n\t\t if (codepage == CP_UTF8)\n\t\t {\n\t\t\t/* Handle CP_UTF8 input ourselves to be able to handle\n\t\t\t * trailing bytes properly.\n\t\t\t * Get one UTF-8 character from src. */\n\t\t\tbytelen = (int)utf_ptr2len_len(src, size);\n\t\t\tif (bytelen > size)\n\t\t\t{\n\t\t\t /* Only got some bytes of a character. Normally\n\t\t\t * it's put in \"conv_rest\", but if it's too long\n\t\t\t * deal with it as if they were illegal bytes. */\n\t\t\t if (bytelen <= CONV_RESTLEN)\n\t\t\t\tbreak;\n\n\t\t\t /* weird overlong byte sequence */\n\t\t\t bytelen = size;\n\t\t\t found_bad = TRUE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t int\t u8c = utf_ptr2char(src);\n\n\t\t\t if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))\n\t\t\t\tfound_bad = TRUE;\n\t\t\t ucs2buf[0] = u8c;\n\t\t\t ucs2len = 1;\n\t\t\t}\n\t\t }\n\t\t else\n# endif\n\t\t {\n\t\t\t/* We don't know how long the byte sequence is, try\n\t\t\t * from one to three bytes. */\n\t\t\tfor (bytelen = 1; bytelen <= size && bytelen <= 3;\n\t\t\t\t\t\t\t\t ++bytelen)\n\t\t\t{\n\t\t\t ucs2len = MultiByteToWideChar(codepage,\n\t\t\t\t\t\t\t MB_ERR_INVALID_CHARS,\n\t\t\t\t\t\t\t (LPCSTR)src, bytelen,\n\t\t\t\t\t\t\t\t ucs2buf, 3);\n\t\t\t if (ucs2len > 0)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ucs2len == 0)\n\t\t\t{\n\t\t\t /* If we have only one byte then it's probably an\n\t\t\t * incomplete byte sequence. Otherwise discard\n\t\t\t * one byte as a bad character. */\n\t\t\t if (size == 1)\n\t\t\t\tbreak;\n\t\t\t found_bad = TRUE;\n\t\t\t bytelen = 1;\n\t\t\t}\n\t\t }\n\n\t\t if (!found_bad)\n\t\t {\n\t\t\tint\ti;\n\n\t\t\t/* Convert \"ucs2buf[ucs2len]\" to 'enc' in \"dst\". */\n\t\t\tif (enc_utf8)\n\t\t\t{\n\t\t\t /* From UCS-2 to UTF-8. Cannot fail. */\n\t\t\t for (i = 0; i < ucs2len; ++i)\n\t\t\t\tdst += utf_char2bytes(ucs2buf[i], dst);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t BOOL\tbad = FALSE;\n\t\t\t int\t\tdstlen;\n\n\t\t\t /* From UCS-2 to \"enc_codepage\". If the\n\t\t\t * conversion uses the default character \"?\",\n\t\t\t * the data doesn't fit in this encoding. */\n\t\t\t dstlen = WideCharToMultiByte(enc_codepage, 0,\n\t\t\t\t (LPCWSTR)ucs2buf, ucs2len,\n\t\t\t\t (LPSTR)dst, (int)(src - dst),\n\t\t\t\t replstr, &bad);\n\t\t\t if (bad)\n\t\t\t\tfound_bad = TRUE;\n\t\t\t else\n\t\t\t\tdst += dstlen;\n\t\t\t}\n\t\t }\n\n\t\t if (found_bad)\n\t\t {\n\t\t\t/* Deal with bytes we can't convert. */\n\t\t\tif (can_retry)\n\t\t\t goto rewind_retry;\n\t\t\tif (conv_error == 0)\n\t\t\t conv_error = readfile_linenr(linecnt, ptr, dst);\n\t\t\tif (bad_char_behavior != BAD_DROP)\n\t\t\t{\n\t\t\t if (bad_char_behavior == BAD_KEEP)\n\t\t\t {\n\t\t\t\tmch_memmove(dst, src, bytelen);\n\t\t\t\tdst += bytelen;\n\t\t\t }\n\t\t\t else\n\t\t\t\t*dst++ = bad_char_behavior;\n\t\t\t}\n\t\t }\n\n\t\t src += bytelen;\n\t\t size -= bytelen;\n\t\t}\n\n\t\tif (size > 0)\n\t\t{\n\t\t /* An incomplete byte sequence remaining. */\n\t\t mch_memmove(conv_rest, src, size);\n\t\t conv_restlen = size;\n\t\t}\n\n\t\t/* The new size is equal to how much \"dst\" was advanced. */\n\t\tsize = (long)(dst - ptr);\n\t }\n\t else\n# endif\n# ifdef MACOS_CONVERT\n\t if (fio_flags & FIO_MACROMAN)\n\t {\n\t\t/*\n\t\t * Conversion from Apple MacRoman char encoding to UTF-8 or\n\t\t * latin1. This is in os_mac_conv.c.\n\t\t */\n\t\tif (macroman2enc(ptr, &size, real_size) == FAIL)\n\t\t goto rewind_retry;\n\t }\n\t else\n# endif\n\t if (fio_flags != 0)\n\t {\n\t\tint\tu8c;\n\t\tchar_u\t*dest;\n\t\tchar_u\t*tail = NULL;\n\n\t\t/*\n\t\t * \"enc_utf8\" set: Convert Unicode or Latin1 to UTF-8.\n\t\t * \"enc_utf8\" not set: Convert Unicode to Latin1.\n\t\t * Go from end to start through the buffer, because the number\n\t\t * of bytes may increase.\n\t\t * \"dest\" points to after where the UTF-8 bytes go, \"p\" points\n\t\t * to after the next character to convert.\n\t\t */\n\t\tdest = ptr + real_size;\n\t\tif (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)\n\t\t{\n\t\t p = ptr + size;\n\t\t if (fio_flags == FIO_UTF8)\n\t\t {\n\t\t\t/* Check for a trailing incomplete UTF-8 sequence */\n\t\t\ttail = ptr + size - 1;\n\t\t\twhile (tail > ptr && (*tail & 0xc0) == 0x80)\n\t\t\t --tail;\n\t\t\tif (tail + utf_byte2len(*tail) <= ptr + size)\n\t\t\t tail = NULL;\n\t\t\telse\n\t\t\t p = tail;\n\t\t }\n\t\t}\n\t\telse if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t{\n\t\t /* Check for a trailing byte */\n\t\t p = ptr + (size & ~1);\n\t\t if (size & 1)\n\t\t\ttail = p;\n\t\t if ((fio_flags & FIO_UTF16) && p > ptr)\n\t\t {\n\t\t\t/* Check for a trailing leading word */\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (*--p << 8);\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (*--p << 8);\n\t\t\t}\n\t\t\tif (u8c >= 0xd800 && u8c <= 0xdbff)\n\t\t\t tail = p;\n\t\t\telse\n\t\t\t p += 2;\n\t\t }\n\t\t}\n\t\telse /* FIO_UCS4 */\n\t\t{\n\t\t /* Check for trailing 1, 2 or 3 bytes */\n\t\t p = ptr + (size & ~3);\n\t\t if (size & 3)\n\t\t\ttail = p;\n\t\t}\n\n\t\t/* If there is a trailing incomplete sequence move it to\n\t\t * conv_rest[]. */\n\t\tif (tail != NULL)\n\t\t{\n\t\t conv_restlen = (int)((ptr + size) - tail);\n\t\t mch_memmove(conv_rest, (char_u *)tail, conv_restlen);\n\t\t size -= conv_restlen;\n\t\t}\n\n\n\t\twhile (p > ptr)\n\t\t{\n\t\t if (fio_flags & FIO_LATIN1)\n\t\t\tu8c = *--p;\n\t\t else if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t {\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (*--p << 8);\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (*--p << 8);\n\t\t\t}\n\t\t\tif ((fio_flags & FIO_UTF16)\n\t\t\t\t\t && u8c >= 0xdc00 && u8c <= 0xdfff)\n\t\t\t{\n\t\t\t int u16c;\n\n\t\t\t if (p == ptr)\n\t\t\t {\n\t\t\t\t/* Missing leading word. */\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\n\t\t\t /* found second word of double-word, get the first\n\t\t\t * word and compute the resulting character */\n\t\t\t if (fio_flags & FIO_ENDIAN_L)\n\t\t\t {\n\t\t\t\tu16c = (*--p << 8);\n\t\t\t\tu16c += *--p;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\tu16c = *--p;\n\t\t\t\tu16c += (*--p << 8);\n\t\t\t }\n\t\t\t u8c = 0x10000 + ((u16c & 0x3ff) << 10)\n\t\t\t\t\t\t\t + (u8c & 0x3ff);\n\n\t\t\t /* Check if the word is indeed a leading word. */\n\t\t\t if (u16c < 0xd800 || u16c > 0xdbff)\n\t\t\t {\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t else if (fio_flags & FIO_UCS4)\n\t\t {\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (unsigned)*--p << 24;\n\t\t\t u8c += (unsigned)*--p << 16;\n\t\t\t u8c += (unsigned)*--p << 8;\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\t/* big endian */\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (unsigned)*--p << 8;\n\t\t\t u8c += (unsigned)*--p << 16;\n\t\t\t u8c += (unsigned)*--p << 24;\n\t\t\t}\n\t\t }\n\t\t else /* UTF-8 */\n\t\t {\n\t\t\tif (*--p < 0x80)\n\t\t\t u8c = *p;\n\t\t\telse\n\t\t\t{\n\t\t\t len = utf_head_off(ptr, p);\n\t\t\t p -= len;\n\t\t\t u8c = utf_ptr2char(p);\n\t\t\t if (len == 0)\n\t\t\t {\n\t\t\t\t/* Not a valid UTF-8 character, retry with\n\t\t\t\t * another fenc when possible, otherwise just\n\t\t\t\t * report the error. */\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t if (enc_utf8)\t/* produce UTF-8 */\n\t\t {\n\t\t\tdest -= utf_char2len(u8c);\n\t\t\t(void)utf_char2bytes(u8c, dest);\n\t\t }\n\t\t else\t\t/* produce Latin1 */\n\t\t {\n\t\t\t--dest;\n\t\t\tif (u8c >= 0x100)\n\t\t\t{\n\t\t\t /* character doesn't fit in latin1, retry with\n\t\t\t * another fenc when possible, otherwise just\n\t\t\t * report the error. */\n\t\t\t if (can_retry)\n\t\t\t\tgoto rewind_retry;\n\t\t\t if (conv_error == 0)\n\t\t\t\tconv_error = readfile_linenr(linecnt, ptr, p);\n\t\t\t if (bad_char_behavior == BAD_DROP)\n\t\t\t\t++dest;\n\t\t\t else if (bad_char_behavior == BAD_KEEP)\n\t\t\t\t*dest = u8c;\n\t\t\t else if (eap != NULL && eap->bad_char != 0)\n\t\t\t\t*dest = bad_char_behavior;\n\t\t\t else\n\t\t\t\t*dest = 0xBF;\n\t\t\t}\n\t\t\telse\n\t\t\t *dest = u8c;\n\t\t }\n\t\t}\n\n\t\t/* move the linerest to before the converted characters */\n\t\tline_start = dest - linerest;\n\t\tmch_memmove(line_start, buffer, (size_t)linerest);\n\t\tsize = (long)((ptr + real_size) - dest);\n\t\tptr = dest;\n\t }\n\t else if (enc_utf8 && !curbuf->b_p_bin)\n\t {\n\t\tint incomplete_tail = FALSE;\n\n\t\t/* Reading UTF-8: Check if the bytes are valid UTF-8. */\n\t\tfor (p = ptr; ; ++p)\n\t\t{\n\t\t int\t todo = (int)((ptr + size) - p);\n\t\t int\t l;\n\n\t\t if (todo <= 0)\n\t\t\tbreak;\n\t\t if (*p >= 0x80)\n\t\t {\n\t\t\t/* A length of 1 means it's an illegal byte. Accept\n\t\t\t * an incomplete character at the end though, the next\n\t\t\t * read() will get the next bytes, we'll check it\n\t\t\t * then. */\n\t\t\tl = utf_ptr2len_len(p, todo);\n\t\t\tif (l > todo && !incomplete_tail)\n\t\t\t{\n\t\t\t /* Avoid retrying with a different encoding when\n\t\t\t * a truncated file is more likely, or attempting\n\t\t\t * to read the rest of an incomplete sequence when\n\t\t\t * we have already done so. */\n\t\t\t if (p > ptr || filesize > 0)\n\t\t\t\tincomplete_tail = TRUE;\n\t\t\t /* Incomplete byte sequence, move it to conv_rest[]\n\t\t\t * and try to read the rest of it, unless we've\n\t\t\t * already done so. */\n\t\t\t if (p > ptr)\n\t\t\t {\n\t\t\t\tconv_restlen = todo;\n\t\t\t\tmch_memmove(conv_rest, p, conv_restlen);\n\t\t\t\tsize -= conv_restlen;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}\n\t\t\tif (l == 1 || l > todo)\n\t\t\t{\n\t\t\t /* Illegal byte. If we can try another encoding\n\t\t\t * do that, unless at EOF where a truncated\n\t\t\t * file is more likely than a conversion error. */\n\t\t\t if (can_retry && !incomplete_tail)\n\t\t\t\tbreak;\n# ifdef USE_ICONV\n\t\t\t /* When we did a conversion report an error. */\n\t\t\t if (iconv_fd != (iconv_t)-1 && conv_error == 0)\n\t\t\t\tconv_error = readfile_linenr(linecnt, ptr, p);\n# endif\n\t\t\t /* Remember the first linenr with an illegal byte */\n\t\t\t if (conv_error == 0 && illegal_byte == 0)\n\t\t\t\tillegal_byte = readfile_linenr(linecnt, ptr, p);\n\n\t\t\t /* Drop, keep or replace the bad byte. */\n\t\t\t if (bad_char_behavior == BAD_DROP)\n\t\t\t {\n\t\t\t\tmch_memmove(p, p + 1, todo - 1);\n\t\t\t\t--p;\n\t\t\t\t--size;\n\t\t\t }\n\t\t\t else if (bad_char_behavior != BAD_KEEP)\n\t\t\t\t*p = bad_char_behavior;\n\t\t\t}\n\t\t\telse\n\t\t\t p += l - 1;\n\t\t }\n\t\t}\n\t\tif (p < ptr + size && !incomplete_tail)\n\t\t{\n\t\t /* Detected a UTF-8 error. */\nrewind_retry:\n\t\t /* Retry reading with another conversion. */\n# if defined(FEAT_EVAL) && defined(USE_ICONV)\n\t\t if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)\n\t\t\t/* iconv() failed, try 'charconvert' */\n\t\t\tdid_iconv = TRUE;\n\t\t else\n# endif\n\t\t\t/* use next item from 'fileencodings' */\n\t\t\tadvance_fenc = TRUE;\n\t\t file_rewind = TRUE;\n\t\t goto retry;\n\t\t}\n\t }\n#endif\n\n\t /* count the number of characters (after conversion!) */\n\t filesize += size;\n\n\t /*\n\t * when reading the first part of a file: guess EOL type\n\t */\n\t if (fileformat == EOL_UNKNOWN)\n\t {\n\t\t/* First try finding a NL, for Dos and Unix */\n\t\tif (try_dos || try_unix)\n\t\t{\n\t\t /* Reset the carriage return counter. */\n\t\t if (try_mac)\n\t\t\ttry_mac = 1;\n\n\t\t for (p = ptr; p < ptr + size; ++p)\n\t\t {\n\t\t\tif (*p == NL)\n\t\t\t{\n\t\t\t if (!try_unix\n\t\t\t\t || (try_dos && p > ptr && p[-1] == CAR))\n\t\t\t\tfileformat = EOL_DOS;\n\t\t\t else\n\t\t\t\tfileformat = EOL_UNIX;\n\t\t\t break;\n\t\t\t}\n\t\t\telse if (*p == CAR && try_mac)\n\t\t\t try_mac++;\n\t\t }\n\n\t\t /* Don't give in to EOL_UNIX if EOL_MAC is more likely */\n\t\t if (fileformat == EOL_UNIX && try_mac)\n\t\t {\n\t\t\t/* Need to reset the counters when retrying fenc. */\n\t\t\ttry_mac = 1;\n\t\t\ttry_unix = 1;\n\t\t\tfor (; p >= ptr && *p != CAR; p--)\n\t\t\t ;\n\t\t\tif (p >= ptr)\n\t\t\t{\n\t\t\t for (p = ptr; p < ptr + size; ++p)\n\t\t\t {\n\t\t\t\tif (*p == NL)\n\t\t\t\t try_unix++;\n\t\t\t\telse if (*p == CAR)\n\t\t\t\t try_mac++;\n\t\t\t }\n\t\t\t if (try_mac > try_unix)\n\t\t\t\tfileformat = EOL_MAC;\n\t\t\t}\n\t\t }\n\t\t else if (fileformat == EOL_UNKNOWN && try_mac == 1)\n\t\t\t/* Looking for CR but found no end-of-line markers at\n\t\t\t * all: use the default format. */\n\t\t\tfileformat = default_fileformat();\n\t\t}\n\n\t\t/* No NL found: may use Mac format */\n\t\tif (fileformat == EOL_UNKNOWN && try_mac)\n\t\t fileformat = EOL_MAC;\n\n\t\t/* Still nothing found? Use first format in 'ffs' */\n\t\tif (fileformat == EOL_UNKNOWN)\n\t\t fileformat = default_fileformat();\n\n\t\t/* if editing a new file: may set p_tx and p_ff */\n\t\tif (set_options)\n\t\t set_fileformat(fileformat, OPT_LOCAL);\n\t }\n\t}\n\n\t/*\n\t * This loop is executed once for every character read.\n\t * Keep it fast!\n\t */\n\tif (fileformat == EOL_MAC)\n\t{\n\t --ptr;\n\t while (++ptr, --size >= 0)\n\t {\n\t\t/* catch most common case first */\n\t\tif ((c = *ptr) != NUL && c != CAR && c != NL)\n\t\t continue;\n\t\tif (c == NUL)\n\t\t *ptr = NL;\t/* NULs are replaced by newlines! */\n\t\telse if (c == NL)\n\t\t *ptr = CAR;\t/* NLs are replaced by CRs! */\n\t\telse\n\t\t{\n\t\t if (skip_count == 0)\n\t\t {\n\t\t\t*ptr = NUL;\t /* end of line */\n\t\t\tlen = (colnr_T) (ptr - line_start + 1);\n\t\t\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t\t\t{\n\t\t\t error = TRUE;\n\t\t\t break;\n\t\t\t}\n#ifdef FEAT_PERSISTENT_UNDO\n\t\t\tif (read_undo_file)\n\t\t\t sha256_update(&sha_ctx, line_start, len);\n#endif\n\t\t\t++lnum;\n\t\t\tif (--read_count == 0)\n\t\t\t{\n\t\t\t error = TRUE;\t/* break loop */\n\t\t\t line_start = ptr;\t/* nothing left to write */\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t\t--skip_count;\n\t\t line_start = ptr + 1;\n\t\t}\n\t }\n\t}\n\telse\n\t{\n\t --ptr;\n\t while (++ptr, --size >= 0)\n\t {\n\t\tif ((c = *ptr) != NUL && c != NL) /* catch most common case */\n\t\t continue;\n\t\tif (c == NUL)\n\t\t *ptr = NL;\t/* NULs are replaced by newlines! */\n\t\telse\n\t\t{\n\t\t if (skip_count == 0)\n\t\t {\n\t\t\t*ptr = NUL;\t\t/* end of line */\n\t\t\tlen = (colnr_T)(ptr - line_start + 1);\n\t\t\tif (fileformat == EOL_DOS)\n\t\t\t{\n\t\t\t if (ptr > line_start && ptr[-1] == CAR)\n\t\t\t {\n\t\t\t\t/* remove CR before NL */\n\t\t\t\tptr[-1] = NUL;\n\t\t\t\t--len;\n\t\t\t }\n\t\t\t /*\n\t\t\t * Reading in Dos format, but no CR-LF found!\n\t\t\t * When 'fileformats' includes \"unix\", delete all\n\t\t\t * the lines read so far and start all over again.\n\t\t\t * Otherwise give an error message later.\n\t\t\t */\n\t\t\t else if (ff_error != EOL_DOS)\n\t\t\t {\n\t\t\t\tif ( try_unix\n\t\t\t\t && !read_stdin\n\t\t\t\t && (read_buffer\n\t\t\t\t\t|| vim_lseek(fd, (off_T)0L, SEEK_SET)\n\t\t\t\t\t\t\t\t\t == 0))\n\t\t\t\t{\n\t\t\t\t fileformat = EOL_UNIX;\n\t\t\t\t if (set_options)\n\t\t\t\t\tset_fileformat(EOL_UNIX, OPT_LOCAL);\n\t\t\t\t file_rewind = TRUE;\n\t\t\t\t keep_fileformat = TRUE;\n\t\t\t\t goto retry;\n\t\t\t\t}\n\t\t\t\tff_error = EOL_DOS;\n\t\t\t }\n\t\t\t}\n\t\t\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t\t\t{\n\t\t\t error = TRUE;\n\t\t\t break;\n\t\t\t}\n#ifdef FEAT_PERSISTENT_UNDO\n\t\t\tif (read_undo_file)\n\t\t\t sha256_update(&sha_ctx, line_start, len);\n#endif\n\t\t\t++lnum;\n\t\t\tif (--read_count == 0)\n\t\t\t{\n\t\t\t error = TRUE;\t /* break loop */\n\t\t\t line_start = ptr;\t/* nothing left to write */\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t\t--skip_count;\n\t\t line_start = ptr + 1;\n\t\t}\n\t }\n\t}\n\tlinerest = (long)(ptr - line_start);\n\tui_breakcheck();\n }\n\nfailed:\n /* not an error, max. number of lines reached */\n if (error && read_count == 0)\n\terror = FALSE;\n\n /*\n * If we get EOF in the middle of a line, note the fact and\n * complete the line ourselves.\n * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.\n */\n if (!error\n\t && !got_int\n\t && linerest != 0\n\t && !(!curbuf->b_p_bin\n\t\t&& fileformat == EOL_DOS\n\t\t&& *line_start == Ctrl_Z\n\t\t&& ptr == line_start + 1))\n {\n\t/* remember for when writing */\n\tif (set_options)\n\t curbuf->b_p_eol = FALSE;\n\t*ptr = NUL;\n\tlen = (colnr_T)(ptr - line_start + 1);\n\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t error = TRUE;\n\telse\n\t{\n#ifdef FEAT_PERSISTENT_UNDO\n\t if (read_undo_file)\n\t\tsha256_update(&sha_ctx, line_start, len);\n#endif\n\t read_no_eol_lnum = ++lnum;\n\t}\n }\n\n if (set_options)\n\tsave_file_ff(curbuf);\t\t/* remember the current file format */\n\n#ifdef FEAT_CRYPT\n if (curbuf->b_cryptstate != NULL)\n {\n\tcrypt_free_state(curbuf->b_cryptstate);\n\tcurbuf->b_cryptstate = NULL;\n }\n if (cryptkey != NULL && cryptkey != curbuf->b_p_key)\n\tcrypt_free_key(cryptkey);\n /* Don't set cryptkey to NULL, it's used below as a flag that\n * encryption was used. */\n#endif\n\n#ifdef FEAT_MBYTE\n /* If editing a new file: set 'fenc' for the current buffer.\n * Also for \":read ++edit file\". */\n if (set_options)\n\tset_string_option_direct((char_u *)\"fenc\", -1, fenc,\n\t\t\t\t\t\t OPT_FREE|OPT_LOCAL, 0);\n if (fenc_alloced)\n\tvim_free(fenc);\n# ifdef USE_ICONV\n if (iconv_fd != (iconv_t)-1)\n {\n\ticonv_close(iconv_fd);\n\ticonv_fd = (iconv_t)-1;\n }\n# endif\n#endif\n\n if (!read_buffer && !read_stdin)\n\tclose(fd);\t\t\t\t/* errors are ignored */\n#ifdef HAVE_FD_CLOEXEC\n else\n {\n\tint fdflags = fcntl(fd, F_GETFD);\n\tif (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)\n\t (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);\n }\n#endif\n vim_free(buffer);\n\n#ifdef HAVE_DUP\n if (read_stdin)\n {\n\t/* Use stderr for stdin, makes shell commands work. */\n\tclose(0);\n\tignored = dup(2);\n }\n#endif\n\n#ifdef FEAT_MBYTE\n if (tmpname != NULL)\n {\n\tmch_remove(tmpname);\t\t/* delete converted file */\n\tvim_free(tmpname);\n }\n#endif\n --no_wait_return;\t\t\t/* may wait for return now */\n\n /*\n * In recovery mode everything but autocommands is skipped.\n */\n if (!recoverymode)\n {\n\t/* need to delete the last line, which comes from the empty buffer */\n\tif (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))\n\t{\n#ifdef FEAT_NETBEANS_INTG\n\t netbeansFireChanges = 0;\n#endif\n\t ml_delete(curbuf->b_ml.ml_line_count, FALSE);\n#ifdef FEAT_NETBEANS_INTG\n\t netbeansFireChanges = 1;\n#endif\n\t --linecnt;\n\t}\n\tlinecnt = curbuf->b_ml.ml_line_count - linecnt;\n\tif (filesize == 0)\n\t linecnt = 0;\n\tif (newfile || read_buffer)\n\t{\n\t redraw_curbuf_later(NOT_VALID);\n#ifdef FEAT_DIFF\n\t /* After reading the text into the buffer the diff info needs to\n\t * be updated. */\n\t diff_invalidate(curbuf);\n#endif\n#ifdef FEAT_FOLDING\n\t /* All folds in the window are invalid now. Mark them for update\n\t * before triggering autocommands. */\n\t foldUpdateAll(curwin);\n#endif\n\t}\n\telse if (linecnt)\t\t/* appended at least one line */\n\t appended_lines_mark(from, linecnt);\n\n#ifndef ALWAYS_USE_GUI\n\t/*\n\t * If we were reading from the same terminal as where messages go,\n\t * the screen will have been messed up.\n\t * Switch on raw mode now and clear the screen.\n\t */\n\tif (read_stdin)\n\t{\n\t settmode(TMODE_RAW);\t/* set to raw mode */\n\t starttermcap();\n\t screenclear();\n\t}\n#endif\n\n\tif (got_int)\n\t{\n\t if (!(flags & READ_DUMMY))\n\t {\n\t\tfilemess(curbuf, sfname, (char_u *)_(e_interr), 0);\n\t\tif (newfile)\n\t\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t }\n\t msg_scroll = msg_save;\n#ifdef FEAT_VIMINFO\n\t check_marks_read();\n#endif\n\t return OK;\t\t/* an interrupt isn't really an error */\n\t}\n\n\tif (!filtering && !(flags & READ_DUMMY))\n\t{\n\t msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */\n\t c = FALSE;\n\n#ifdef UNIX\n# ifdef S_ISFIFO\n\t if (S_ISFIFO(perm))\t\t\t /* fifo or socket */\n\t {\n\t\tSTRCAT(IObuff, _(\"[fifo/socket]\"));\n\t\tc = TRUE;\n\t }\n# else\n# ifdef S_IFIFO\n\t if ((perm & S_IFMT) == S_IFIFO)\t /* fifo */\n\t {\n\t\tSTRCAT(IObuff, _(\"[fifo]\"));\n\t\tc = TRUE;\n\t }\n# endif\n# ifdef S_IFSOCK\n\t if ((perm & S_IFMT) == S_IFSOCK)\t /* or socket */\n\t {\n\t\tSTRCAT(IObuff, _(\"[socket]\"));\n\t\tc = TRUE;\n\t }\n# endif\n# endif\n# ifdef OPEN_CHR_FILES\n\t if (S_ISCHR(perm))\t\t\t /* or character special */\n\t {\n\t\tSTRCAT(IObuff, _(\"[character special]\"));\n\t\tc = TRUE;\n\t }\n# endif\n#endif\n\t if (curbuf->b_p_ro)\n\t {\n\t\tSTRCAT(IObuff, shortmess(SHM_RO) ? _(\"[RO]\") : _(\"[readonly]\"));\n\t\tc = TRUE;\n\t }\n\t if (read_no_eol_lnum)\n\t {\n\t\tmsg_add_eol();\n\t\tc = TRUE;\n\t }\n\t if (ff_error == EOL_DOS)\n\t {\n\t\tSTRCAT(IObuff, _(\"[CR missing]\"));\n\t\tc = TRUE;\n\t }\n\t if (split)\n\t {\n\t\tSTRCAT(IObuff, _(\"[long lines split]\"));\n\t\tc = TRUE;\n\t }\n#ifdef FEAT_MBYTE\n\t if (notconverted)\n\t {\n\t\tSTRCAT(IObuff, _(\"[NOT converted]\"));\n\t\tc = TRUE;\n\t }\n\t else if (converted)\n\t {\n\t\tSTRCAT(IObuff, _(\"[converted]\"));\n\t\tc = TRUE;\n\t }\n#endif\n#ifdef FEAT_CRYPT\n\t if (cryptkey != NULL)\n\t {\n\t\tcrypt_append_msg(curbuf);\n\t\tc = TRUE;\n\t }\n#endif\n#ifdef FEAT_MBYTE\n\t if (conv_error != 0)\n\t {\n\t\tsprintf((char *)IObuff + STRLEN(IObuff),\n\t\t _(\"[CONVERSION ERROR in line %ld]\"), (long)conv_error);\n\t\tc = TRUE;\n\t }\n\t else if (illegal_byte > 0)\n\t {\n\t\tsprintf((char *)IObuff + STRLEN(IObuff),\n\t\t\t _(\"[ILLEGAL BYTE in line %ld]\"), (long)illegal_byte);\n\t\tc = TRUE;\n\t }\n\t else\n#endif\n\t\tif (error)\n\t {\n\t\tSTRCAT(IObuff, _(\"[READ ERRORS]\"));\n\t\tc = TRUE;\n\t }\n\t if (msg_add_fileformat(fileformat))\n\t\tc = TRUE;\n#ifdef FEAT_CRYPT\n\t if (cryptkey != NULL)\n\t\tmsg_add_lines(c, (long)linecnt, filesize\n\t\t\t - crypt_get_header_len(crypt_get_method_nr(curbuf)));\n\t else\n#endif\n\t\tmsg_add_lines(c, (long)linecnt, filesize);\n\n\t vim_free(keep_msg);\n\t keep_msg = NULL;\n\t msg_scrolled_ign = TRUE;\n#ifdef ALWAYS_USE_GUI\n\t /* Don't show the message when reading stdin, it would end up in a\n\t * message box (which might be shown when exiting!) */\n\t if (read_stdin || read_buffer)\n\t\tp = msg_may_trunc(FALSE, IObuff);\n\t else\n#endif\n\t\tp = msg_trunc_attr(IObuff, FALSE, 0);\n\t if (read_stdin || read_buffer || restart_edit != 0\n\t\t || (msg_scrolled != 0 && !need_wait_return))\n\t\t/* Need to repeat the message after redrawing when:\n\t\t * - When reading from stdin (the screen will be cleared next).\n\t\t * - When restart_edit is set (otherwise there will be a delay\n\t\t * before redrawing).\n\t\t * - When the screen was scrolled but there is no wait-return\n\t\t * prompt. */\n\t\tset_keep_msg(p, 0);\n\t msg_scrolled_ign = FALSE;\n\t}\n\n\t/* with errors writing the file requires \":w!\" */\n\tif (newfile && (error\n#ifdef FEAT_MBYTE\n\t\t || conv_error != 0\n\t\t || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)\n#endif\n\t\t ))\n\t curbuf->b_p_ro = TRUE;\n\n\tu_clearline();\t /* cannot use \"U\" command after adding lines */\n\n\t/*\n\t * In Ex mode: cursor at last new line.\n\t * Otherwise: cursor at first new line.\n\t */\n\tif (exmode_active)\n\t curwin->w_cursor.lnum = from + linecnt;\n\telse\n\t curwin->w_cursor.lnum = from + 1;\n\tcheck_cursor_lnum();\n\tbeginline(BL_WHITE | BL_FIX);\t /* on first non-blank */\n\n\t/*\n\t * Set '[ and '] marks to the newly read lines.\n\t */\n\tcurbuf->b_op_start.lnum = from + 1;\n\tcurbuf->b_op_start.col = 0;\n\tcurbuf->b_op_end.lnum = from + linecnt;\n\tcurbuf->b_op_end.col = 0;\n\n#ifdef WIN32\n\t/*\n\t * Work around a weird problem: When a file has two links (only\n\t * possible on NTFS) and we write through one link, then stat() it\n\t * through the other link, the timestamp information may be wrong.\n\t * It's correct again after reading the file, thus reset the timestamp\n\t * here.\n\t */\n\tif (newfile && !read_stdin && !read_buffer\n\t\t\t\t\t && mch_stat((char *)fname, &st) >= 0)\n\t{\n\t buf_store_time(curbuf, &st, fname);\n\t curbuf->b_mtime_read = curbuf->b_mtime;\n\t}\n#endif\n }\n msg_scroll = msg_save;\n\n#ifdef FEAT_VIMINFO\n /*\n * Get the marks before executing autocommands, so they can be used there.\n */\n check_marks_read();\n#endif\n\n /*\n * We remember if the last line of the read didn't have\n * an eol even when 'binary' is off, to support turning 'fixeol' off,\n * or writing the read again with 'binary' on. The latter is required\n * for \":autocmd FileReadPost *.gz set bin|'[,']!gunzip\" to work.\n */\n curbuf->b_no_eol_lnum = read_no_eol_lnum;\n\n /* When reloading a buffer put the cursor at the first line that is\n * different. */\n if (flags & READ_KEEP_UNDO)\n\tu_find_first_changed();\n\n#ifdef FEAT_PERSISTENT_UNDO\n /*\n * When opening a new file locate undo info and read it.\n */\n if (read_undo_file)\n {\n\tchar_u\thash[UNDO_HASH_SIZE];\n\n\tsha256_finish(&sha_ctx, hash);\n\tu_read_undo(NULL, hash, fname);\n }\n#endif\n\n#ifdef FEAT_AUTOCMD\n if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))\n {\n\tint m = msg_scroll;\n\tint n = msg_scrolled;\n\n\t/* Save the fileformat now, otherwise the buffer will be considered\n\t * modified if the format/encoding was automatically detected. */\n\tif (set_options)\n\t save_file_ff(curbuf);\n\n\t/*\n\t * The output from the autocommands should not overwrite anything and\n\t * should not be overwritten: Set msg_scroll, restore its value if no\n\t * output was done.\n\t */\n\tmsg_scroll = TRUE;\n\tif (filtering)\n\t apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (newfile || (read_buffer && sfname != NULL))\n\t{\n\t apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\t if (!au_did_filetype && *curbuf->b_p_ft != NUL)\n\t\t/*\n\t\t * EVENT_FILETYPE was not triggered but the buffer already has a\n\t\t * filetype. Trigger EVENT_FILETYPE using the existing filetype.\n\t\t */\n\t\tapply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,\n\t\t\tTRUE, curbuf);\n\t}\n\telse\n\t apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap);\n\tif (msg_scrolled == n)\n\t msg_scroll = m;\n# ifdef FEAT_EVAL\n\tif (aborting())\t /* autocmds may abort script processing */\n\t return FAIL;\n# endif\n }\n#endif\n\n if (recoverymode && error)\n\treturn FAIL;\n return OK;\n}", "project": "vim", "hash": 249564375416889539424239000884906838896, "size": 2516, "commit_id": "5a73e0ca54c77e067c3b12ea6f35e3e8681e8cf8", "message": "patch 8.0.1263: others can read the swap file if a user is careless\n\nProblem: Others can read the swap file if a user is careless with his\n primary group.\nSolution: If the group permission allows for reading but the world\n permissions doesn't, make sure the group is right.", "target": 1, "dataset": "other", "idx": 212695}
  940. {"func": "readfile(\n char_u\t*fname,\n char_u\t*sfname,\n linenr_T\tfrom,\n linenr_T\tlines_to_skip,\n linenr_T\tlines_to_read,\n exarg_T\t*eap,\t\t\t/* can be NULL! */\n int\t\tflags)\n{\n int\t\tfd = 0;\n int\t\tnewfile = (flags & READ_NEW);\n int\t\tcheck_readonly;\n int\t\tfiltering = (flags & READ_FILTER);\n int\t\tread_stdin = (flags & READ_STDIN);\n int\t\tread_buffer = (flags & READ_BUFFER);\n int\t\tread_fifo = (flags & READ_FIFO);\n int\t\tset_options = newfile || read_buffer\n\t\t\t\t\t || (eap != NULL && eap->read_edit);\n linenr_T\tread_buf_lnum = 1;\t/* next line to read from curbuf */\n colnr_T\tread_buf_col = 0;\t/* next char to read from this line */\n char_u\tc;\n linenr_T\tlnum = from;\n char_u\t*ptr = NULL;\t\t/* pointer into read buffer */\n char_u\t*buffer = NULL;\t\t/* read buffer */\n char_u\t*new_buffer = NULL;\t/* init to shut up gcc */\n char_u\t*line_start = NULL;\t/* init to shut up gcc */\n int\t\twasempty;\t\t/* buffer was empty before reading */\n colnr_T\tlen;\n long\tsize = 0;\n char_u\t*p;\n off_T\tfilesize = 0;\n int\t\tskip_read = FALSE;\n#ifdef FEAT_CRYPT\n char_u\t*cryptkey = NULL;\n int\t\tdid_ask_for_key = FALSE;\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n context_sha256_T sha_ctx;\n int\t\tread_undo_file = FALSE;\n#endif\n int\t\tsplit = 0;\t\t/* number of split lines */\n#define UNKNOWN\t 0x0fffffff\t\t/* file size is unknown */\n linenr_T\tlinecnt;\n int\t\terror = FALSE;\t\t/* errors encountered */\n int\t\tff_error = EOL_UNKNOWN; /* file format with errors */\n long\tlinerest = 0;\t\t/* remaining chars in line */\n#ifdef UNIX\n int\t\tperm = 0;\n int\t\tswap_mode = -1;\t\t/* protection bits for swap file */\n#else\n int\t\tperm;\n#endif\n int\t\tfileformat = 0;\t\t/* end-of-line format */\n int\t\tkeep_fileformat = FALSE;\n stat_T\tst;\n int\t\tfile_readonly;\n linenr_T\tskip_count = 0;\n linenr_T\tread_count = 0;\n int\t\tmsg_save = msg_scroll;\n linenr_T\tread_no_eol_lnum = 0; /* non-zero lnum when last line of\n\t\t\t\t\t * last read was missing the eol */\n int\t\ttry_mac;\n int\t\ttry_dos;\n int\t\ttry_unix;\n int\t\tfile_rewind = FALSE;\n#ifdef FEAT_MBYTE\n int\t\tcan_retry;\n linenr_T\tconv_error = 0;\t\t/* line nr with conversion error */\n linenr_T\tillegal_byte = 0;\t/* line nr with illegal byte */\n int\t\tkeep_dest_enc = FALSE;\t/* don't retry when char doesn't fit\n\t\t\t\t\t in destination encoding */\n int\t\tbad_char_behavior = BAD_REPLACE;\n\t\t\t\t\t/* BAD_KEEP, BAD_DROP or character to\n\t\t\t\t\t * replace with */\n char_u\t*tmpname = NULL;\t/* name of 'charconvert' output file */\n int\t\tfio_flags = 0;\n char_u\t*fenc;\t\t\t/* fileencoding to use */\n int\t\tfenc_alloced;\t\t/* fenc_next is in allocated memory */\n char_u\t*fenc_next = NULL;\t/* next item in 'fencs' or NULL */\n int\t\tadvance_fenc = FALSE;\n long\treal_size = 0;\n# ifdef USE_ICONV\n iconv_t\ticonv_fd = (iconv_t)-1;\t/* descriptor for iconv() or -1 */\n# ifdef FEAT_EVAL\n int\t\tdid_iconv = FALSE;\t/* TRUE when iconv() failed and trying\n\t\t\t\t\t 'charconvert' next */\n# endif\n# endif\n int\t\tconverted = FALSE;\t/* TRUE if conversion done */\n int\t\tnotconverted = FALSE;\t/* TRUE if conversion wanted but it\n\t\t\t\t\t wasn't possible */\n char_u\tconv_rest[CONV_RESTLEN];\n int\t\tconv_restlen = 0;\t/* nr of bytes in conv_rest[] */\n#endif\n#ifdef FEAT_AUTOCMD\n buf_T\t*old_curbuf;\n char_u\t*old_b_ffname;\n char_u\t*old_b_fname;\n int\t\tusing_b_ffname;\n int\t\tusing_b_fname;\n#endif\n\n#ifdef FEAT_AUTOCMD\n au_did_filetype = FALSE; /* reset before triggering any autocommands */\n#endif\n\n curbuf->b_no_eol_lnum = 0;\t/* in case it was set by the previous read */\n\n /*\n * If there is no file name yet, use the one for the read file.\n * BF_NOTEDITED is set to reflect this.\n * Don't do this for a read from a filter.\n * Only do this when 'cpoptions' contains the 'f' flag.\n */\n if (curbuf->b_ffname == NULL\n\t && !filtering\n\t && fname != NULL\n\t && vim_strchr(p_cpo, CPO_FNAMER) != NULL\n\t && !(flags & READ_DUMMY))\n {\n\tif (set_rw_fname(fname, sfname) == FAIL)\n\t return FAIL;\n }\n\n#ifdef FEAT_AUTOCMD\n /* Remember the initial values of curbuf, curbuf->b_ffname and\n * curbuf->b_fname to detect whether they are altered as a result of\n * executing nasty autocommands. Also check if \"fname\" and \"sfname\"\n * point to one of these values. */\n old_curbuf = curbuf;\n old_b_ffname = curbuf->b_ffname;\n old_b_fname = curbuf->b_fname;\n using_b_ffname = (fname == curbuf->b_ffname)\n\t\t\t\t\t || (sfname == curbuf->b_ffname);\n using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);\n#endif\n\n /* After reading a file the cursor line changes but we don't want to\n * display the line. */\n ex_no_reprint = TRUE;\n\n /* don't display the file info for another buffer now */\n need_fileinfo = FALSE;\n\n /*\n * For Unix: Use the short file name whenever possible.\n * Avoids problems with networks and when directory names are changed.\n * Don't do this for MS-DOS, a \"cd\" in a sub-shell may have moved us to\n * another directory, which we don't detect.\n */\n if (sfname == NULL)\n\tsfname = fname;\n#if defined(UNIX)\n fname = sfname;\n#endif\n\n#ifdef FEAT_AUTOCMD\n /*\n * The BufReadCmd and FileReadCmd events intercept the reading process by\n * executing the associated commands instead.\n */\n if (!filtering && !read_stdin && !read_buffer)\n {\n\tpos_T\t pos;\n\n\tpos = curbuf->b_op_start;\n\n\t/* Set '[ mark to the line above where the lines go (line 1 if zero). */\n\tcurbuf->b_op_start.lnum = ((from == 0) ? 1 : from);\n\tcurbuf->b_op_start.col = 0;\n\n\tif (newfile)\n\t{\n\t if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap))\n#ifdef FEAT_EVAL\n\t\treturn aborting() ? FAIL : OK;\n#else\n\t\treturn OK;\n#endif\n\t}\n\telse if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap))\n#ifdef FEAT_EVAL\n\t return aborting() ? FAIL : OK;\n#else\n\t return OK;\n#endif\n\n\tcurbuf->b_op_start = pos;\n }\n#endif\n\n if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)\n\tmsg_scroll = FALSE;\t/* overwrite previous file message */\n else\n\tmsg_scroll = TRUE;\t/* don't overwrite previous file message */\n\n /*\n * If the name ends in a path separator, we can't open it. Check here,\n * because reading the file may actually work, but then creating the swap\n * file may destroy it! Reported on MS-DOS and Win 95.\n * If the name is too long we might crash further on, quit here.\n */\n if (fname != NULL && *fname != NUL)\n {\n\tp = fname + STRLEN(fname);\n\tif (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)\n\t{\n\t filemess(curbuf, fname, (char_u *)_(\"Illegal file name\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return FAIL;\n\t}\n }\n\n if (!read_stdin && !read_buffer && !read_fifo)\n {\n#ifdef UNIX\n\t/*\n\t * On Unix it is possible to read a directory, so we have to\n\t * check for it before the mch_open().\n\t */\n\tperm = mch_getperm(fname);\n\tif (perm >= 0 && !S_ISREG(perm)\t\t /* not a regular file ... */\n# ifdef S_ISFIFO\n\t\t && !S_ISFIFO(perm)\t /* ... or fifo */\n# endif\n# ifdef S_ISSOCK\n\t\t && !S_ISSOCK(perm)\t /* ... or socket */\n# endif\n# ifdef OPEN_CHR_FILES\n\t\t && !(S_ISCHR(perm) && is_dev_fd_file(fname))\n\t\t\t/* ... or a character special file named /dev/fd/<n> */\n# endif\n\t\t\t\t\t\t)\n\t{\n\t int retval = FAIL;\n\n\t if (S_ISDIR(perm))\n\t {\n\t\tfilemess(curbuf, fname, (char_u *)_(\"is a directory\"), 0);\n\t\tretval = NOTDONE;\n\t }\n\t else\n\t\tfilemess(curbuf, fname, (char_u *)_(\"is not a file\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return retval;\n\t}\n#endif\n#if defined(MSWIN)\n\t/*\n\t * MS-Windows allows opening a device, but we will probably get stuck\n\t * trying to read it.\n\t */\n\tif (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)\n\t{\n\t filemess(curbuf, fname, (char_u *)_(\"is a device (disabled with 'opendevice' option)\"), 0);\n\t msg_end();\n\t msg_scroll = msg_save;\n\t return FAIL;\n\t}\n#endif\n }\n\n /* Set default or forced 'fileformat' and 'binary'. */\n set_file_options(set_options, eap);\n\n /*\n * When opening a new file we take the readonly flag from the file.\n * Default is r/w, can be set to r/o below.\n * Don't reset it when in readonly mode\n * Only set/reset b_p_ro when BF_CHECK_RO is set.\n */\n check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));\n if (check_readonly && !readonlymode)\n\tcurbuf->b_p_ro = FALSE;\n\n if (newfile && !read_stdin && !read_buffer && !read_fifo)\n {\n\t/* Remember time of file. */\n\tif (mch_stat((char *)fname, &st) >= 0)\n\t{\n\t buf_store_time(curbuf, &st, fname);\n\t curbuf->b_mtime_read = curbuf->b_mtime;\n#ifdef UNIX\n\t /*\n\t * Use the protection bits of the original file for the swap file.\n\t * This makes it possible for others to read the name of the\n\t * edited file from the swapfile, but only if they can read the\n\t * edited file.\n\t * Remove the \"write\" and \"execute\" bits for group and others\n\t * (they must not write the swapfile).\n\t * Add the \"read\" and \"write\" bits for the user, otherwise we may\n\t * not be able to write to the file ourselves.\n\t * Setting the bits is done below, after creating the swap file.\n\t */\n\t swap_mode = (st.st_mode & 0644) | 0600;\n#endif\n#ifdef FEAT_CW_EDITOR\n\t /* Get the FSSpec on MacOS\n\t * TODO: Update it properly when the buffer name changes\n\t */\n\t (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);\n#endif\n#ifdef VMS\n\t curbuf->b_fab_rfm = st.st_fab_rfm;\n\t curbuf->b_fab_rat = st.st_fab_rat;\n\t curbuf->b_fab_mrs = st.st_fab_mrs;\n#endif\n\t}\n\telse\n\t{\n\t curbuf->b_mtime = 0;\n\t curbuf->b_mtime_read = 0;\n\t curbuf->b_orig_size = 0;\n\t curbuf->b_orig_mode = 0;\n\t}\n\n\t/* Reset the \"new file\" flag. It will be set again below when the\n\t * file doesn't exist. */\n\tcurbuf->b_flags &= ~(BF_NEW | BF_NEW_W);\n }\n\n/*\n * for UNIX: check readonly with perm and mch_access()\n * for Amiga: check readonly by trying to open the file for writing\n */\n file_readonly = FALSE;\n if (read_stdin)\n {\n#if defined(MSWIN)\n\t/* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */\n\tsetmode(0, O_BINARY);\n#endif\n }\n else if (!read_buffer)\n {\n#ifdef USE_MCH_ACCESS\n\tif (\n# ifdef UNIX\n\t !(perm & 0222) ||\n# endif\n\t\t\t\tmch_access((char *)fname, W_OK))\n\t file_readonly = TRUE;\n\tfd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);\n#else\n\tif (!newfile\n\t\t|| readonlymode\n\t\t|| (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)\n\t{\n\t file_readonly = TRUE;\n\t /* try to open ro */\n\t fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);\n\t}\n#endif\n }\n\n if (fd < 0)\t\t\t /* cannot open at all */\n {\n#ifndef UNIX\n\tint\tisdir_f;\n#endif\n\tmsg_scroll = msg_save;\n#ifndef UNIX\n\t/*\n\t * On Amiga we can't open a directory, check here.\n\t */\n\tisdir_f = (mch_isdir(fname));\n\tperm = mch_getperm(fname); /* check if the file exists */\n\tif (isdir_f)\n\t{\n\t filemess(curbuf, sfname, (char_u *)_(\"is a directory\"), 0);\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t}\n\telse\n#endif\n\t if (newfile)\n\t {\n\t\tif (perm < 0\n#ifdef ENOENT\n\t\t\t&& errno == ENOENT\n#endif\n\t\t )\n\t\t{\n\t\t /*\n\t\t * Set the 'new-file' flag, so that when the file has\n\t\t * been created by someone else, a \":w\" will complain.\n\t\t */\n\t\t curbuf->b_flags |= BF_NEW;\n\n\t\t /* Create a swap file now, so that other Vims are warned\n\t\t * that we are editing this file. Don't do this for a\n\t\t * \"nofile\" or \"nowrite\" buffer type. */\n#ifdef FEAT_QUICKFIX\n\t\t if (!bt_dontwrite(curbuf))\n#endif\n\t\t {\n\t\t\tcheck_need_swap(newfile);\n#ifdef FEAT_AUTOCMD\n\t\t\t/* SwapExists autocommand may mess things up */\n\t\t\tif (curbuf != old_curbuf\n\t\t\t\t|| (using_b_ffname\n\t\t\t\t\t&& (old_b_ffname != curbuf->b_ffname))\n\t\t\t\t|| (using_b_fname\n\t\t\t\t\t && (old_b_fname != curbuf->b_fname)))\n\t\t\t{\n\t\t\t EMSG(_(e_auchangedbuf));\n\t\t\t return FAIL;\n\t\t\t}\n#endif\n\t\t }\n\t\t if (dir_of_file_exists(fname))\n\t\t\tfilemess(curbuf, sfname, (char_u *)_(\"[New File]\"), 0);\n\t\t else\n\t\t\tfilemess(curbuf, sfname,\n\t\t\t\t\t (char_u *)_(\"[New DIRECTORY]\"), 0);\n#ifdef FEAT_VIMINFO\n\t\t /* Even though this is a new file, it might have been\n\t\t * edited before and deleted. Get the old marks. */\n\t\t check_marks_read();\n#endif\n#ifdef FEAT_MBYTE\n\t\t /* Set forced 'fileencoding'. */\n\t\t if (eap != NULL)\n\t\t\tset_forced_fenc(eap);\n#endif\n#ifdef FEAT_AUTOCMD\n\t\t apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n#endif\n\t\t /* remember the current fileformat */\n\t\t save_file_ff(curbuf);\n\n#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)\n\t\t if (aborting()) /* autocmds may abort script processing */\n\t\t\treturn FAIL;\n#endif\n\t\t return OK;\t /* a new file is not an error */\n\t\t}\n\t\telse\n\t\t{\n\t\t filemess(curbuf, sfname, (char_u *)(\n# ifdef EFBIG\n\t\t\t (errno == EFBIG) ? _(\"[File too big]\") :\n# endif\n# ifdef EOVERFLOW\n\t\t\t (errno == EOVERFLOW) ? _(\"[File too big]\") :\n# endif\n\t\t\t\t\t\t_(\"[Permission Denied]\")), 0);\n\t\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t\t}\n\t }\n\n\treturn FAIL;\n }\n\n /*\n * Only set the 'ro' flag for readonly files the first time they are\n * loaded.\tHelp files always get readonly mode\n */\n if ((check_readonly && file_readonly) || curbuf->b_help)\n\tcurbuf->b_p_ro = TRUE;\n\n if (set_options)\n {\n\t/* Don't change 'eol' if reading from buffer as it will already be\n\t * correctly set when reading stdin. */\n\tif (!read_buffer)\n\t{\n\t curbuf->b_p_eol = TRUE;\n\t curbuf->b_start_eol = TRUE;\n\t}\n#ifdef FEAT_MBYTE\n\tcurbuf->b_p_bomb = FALSE;\n\tcurbuf->b_start_bomb = FALSE;\n#endif\n }\n\n /* Create a swap file now, so that other Vims are warned that we are\n * editing this file.\n * Don't do this for a \"nofile\" or \"nowrite\" buffer type. */\n#ifdef FEAT_QUICKFIX\n if (!bt_dontwrite(curbuf))\n#endif\n {\n\tcheck_need_swap(newfile);\n#ifdef FEAT_AUTOCMD\n\tif (!read_stdin && (curbuf != old_curbuf\n\t\t|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))\n\t\t|| (using_b_fname && (old_b_fname != curbuf->b_fname))))\n\t{\n\t EMSG(_(e_auchangedbuf));\n\t if (!read_buffer)\n\t\tclose(fd);\n\t return FAIL;\n\t}\n#endif\n#ifdef UNIX\n\t/* Set swap file protection bits after creating it. */\n\tif (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL\n\t\t\t && curbuf->b_ml.ml_mfp->mf_fname != NULL)\n\t{\n\t char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;\n\n\t /*\n\t * If the group-read bit is set but not the world-read bit, then\n\t * the group must be equal to the group of the original file. If\n\t * we can't make that happen then reset the group-read bit. This\n\t * avoids making the swap file readable to more users when the\n\t * primary group of the user is too permissive.\n\t */\n\t if ((swap_mode & 044) == 040)\n\t {\n\t\tstat_T\tswap_st;\n\n\t\tif (mch_stat((char *)swap_fname, &swap_st) >= 0\n\t\t\t&& st.st_gid != swap_st.st_gid\n\t\t\t&& fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)\n\t\t\t\t\t\t\t\t\t == -1)\n\t\t swap_mode &= 0600;\n\t }\n\n\t (void)mch_setperm(swap_fname, (long)swap_mode);\n\t}\n#endif\n }\n\n#if defined(HAS_SWAP_EXISTS_ACTION)\n /* If \"Quit\" selected at ATTENTION dialog, don't load the file */\n if (swap_exists_action == SEA_QUIT)\n {\n\tif (!read_buffer && !read_stdin)\n\t close(fd);\n\treturn FAIL;\n }\n#endif\n\n ++no_wait_return;\t /* don't wait for return yet */\n\n /*\n * Set '[ mark to the line above where the lines go (line 1 if zero).\n */\n curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);\n curbuf->b_op_start.col = 0;\n\n try_mac = (vim_strchr(p_ffs, 'm') != NULL);\n try_dos = (vim_strchr(p_ffs, 'd') != NULL);\n try_unix = (vim_strchr(p_ffs, 'x') != NULL);\n\n#ifdef FEAT_AUTOCMD\n if (!read_buffer)\n {\n\tint\tm = msg_scroll;\n\tint\tn = msg_scrolled;\n\n\t/*\n\t * The file must be closed again, the autocommands may want to change\n\t * the file before reading it.\n\t */\n\tif (!read_stdin)\n\t close(fd);\t\t/* ignore errors */\n\n\t/*\n\t * The output from the autocommands should not overwrite anything and\n\t * should not be overwritten: Set msg_scroll, restore its value if no\n\t * output was done.\n\t */\n\tmsg_scroll = TRUE;\n\tif (filtering)\n\t apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (read_stdin)\n\t apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (newfile)\n\t apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse\n\t apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap);\n\t/* autocommands may have changed it */\n\ttry_mac = (vim_strchr(p_ffs, 'm') != NULL);\n\ttry_dos = (vim_strchr(p_ffs, 'd') != NULL);\n\ttry_unix = (vim_strchr(p_ffs, 'x') != NULL);\n\n\tif (msg_scrolled == n)\n\t msg_scroll = m;\n\n#ifdef FEAT_EVAL\n\tif (aborting())\t /* autocmds may abort script processing */\n\t{\n\t --no_wait_return;\n\t msg_scroll = msg_save;\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t return FAIL;\n\t}\n#endif\n\t/*\n\t * Don't allow the autocommands to change the current buffer.\n\t * Try to re-open the file.\n\t *\n\t * Don't allow the autocommands to change the buffer name either\n\t * (cd for example) if it invalidates fname or sfname.\n\t */\n\tif (!read_stdin && (curbuf != old_curbuf\n\t\t|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))\n\t\t|| (using_b_fname && (old_b_fname != curbuf->b_fname))\n\t\t|| (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))\n\t{\n\t --no_wait_return;\n\t msg_scroll = msg_save;\n\t if (fd < 0)\n\t\tEMSG(_(\"E200: *ReadPre autocommands made the file unreadable\"));\n\t else\n\t\tEMSG(_(\"E201: *ReadPre autocommands must not change current buffer\"));\n\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t return FAIL;\n\t}\n }\n#endif /* FEAT_AUTOCMD */\n\n /* Autocommands may add lines to the file, need to check if it is empty */\n wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);\n\n if (!recoverymode && !filtering && !(flags & READ_DUMMY))\n {\n\t/*\n\t * Show the user that we are busy reading the input. Sometimes this\n\t * may take a while. When reading from stdin another program may\n\t * still be running, don't move the cursor to the last line, unless\n\t * always using the GUI.\n\t */\n\tif (read_stdin)\n\t{\n#ifndef ALWAYS_USE_GUI\n\t mch_msg(_(\"Vim: Reading from stdin...\\n\"));\n#endif\n#ifdef FEAT_GUI\n\t /* Also write a message in the GUI window, if there is one. */\n\t if (gui.in_use && !gui.dying && !gui.starting)\n\t {\n\t\tp = (char_u *)_(\"Reading from stdin...\");\n\t\tgui_write(p, (int)STRLEN(p));\n\t }\n#endif\n\t}\n\telse if (!read_buffer)\n\t filemess(curbuf, sfname, (char_u *)\"\", 0);\n }\n\n msg_scroll = FALSE;\t\t\t/* overwrite the file message */\n\n /*\n * Set linecnt now, before the \"retry\" caused by a wrong guess for\n * fileformat, and after the autocommands, which may change them.\n */\n linecnt = curbuf->b_ml.ml_line_count;\n\n#ifdef FEAT_MBYTE\n /* \"++bad=\" argument. */\n if (eap != NULL && eap->bad_char != 0)\n {\n\tbad_char_behavior = eap->bad_char;\n\tif (set_options)\n\t curbuf->b_bad_char = eap->bad_char;\n }\n else\n\tcurbuf->b_bad_char = 0;\n\n /*\n * Decide which 'encoding' to use or use first.\n */\n if (eap != NULL && eap->force_enc != 0)\n {\n\tfenc = enc_canonize(eap->cmd + eap->force_enc);\n\tfenc_alloced = TRUE;\n\tkeep_dest_enc = TRUE;\n }\n else if (curbuf->b_p_bin)\n {\n\tfenc = (char_u *)\"\";\t\t/* binary: don't convert */\n\tfenc_alloced = FALSE;\n }\n else if (curbuf->b_help)\n {\n\tchar_u\t firstline[80];\n\tint\t fc;\n\n\t/* Help files are either utf-8 or latin1. Try utf-8 first, if this\n\t * fails it must be latin1.\n\t * Always do this when 'encoding' is \"utf-8\". Otherwise only do\n\t * this when needed to avoid [converted] remarks all the time.\n\t * It is needed when the first line contains non-ASCII characters.\n\t * That is only in *.??x files. */\n\tfenc = (char_u *)\"latin1\";\n\tc = enc_utf8;\n\tif (!c && !read_stdin)\n\t{\n\t fc = fname[STRLEN(fname) - 1];\n\t if (TOLOWER_ASC(fc) == 'x')\n\t {\n\t\t/* Read the first line (and a bit more). Immediately rewind to\n\t\t * the start of the file. If the read() fails \"len\" is -1. */\n\t\tlen = read_eintr(fd, firstline, 80);\n\t\tvim_lseek(fd, (off_T)0L, SEEK_SET);\n\t\tfor (p = firstline; p < firstline + len; ++p)\n\t\t if (*p >= 0x80)\n\t\t {\n\t\t\tc = TRUE;\n\t\t\tbreak;\n\t\t }\n\t }\n\t}\n\n\tif (c)\n\t{\n\t fenc_next = fenc;\n\t fenc = (char_u *)\"utf-8\";\n\n\t /* When the file is utf-8 but a character doesn't fit in\n\t * 'encoding' don't retry. In help text editing utf-8 bytes\n\t * doesn't make sense. */\n\t if (!enc_utf8)\n\t\tkeep_dest_enc = TRUE;\n\t}\n\tfenc_alloced = FALSE;\n }\n else if (*p_fencs == NUL)\n {\n\tfenc = curbuf->b_p_fenc;\t/* use format from buffer */\n\tfenc_alloced = FALSE;\n }\n else\n {\n\tfenc_next = p_fencs;\t\t/* try items in 'fileencodings' */\n\tfenc = next_fenc(&fenc_next);\n\tfenc_alloced = TRUE;\n }\n#endif\n\n /*\n * Jump back here to retry reading the file in different ways.\n * Reasons to retry:\n * - encoding conversion failed: try another one from \"fenc_next\"\n * - BOM detected and fenc was set, need to setup conversion\n * - \"fileformat\" check failed: try another\n *\n * Variables set for special retry actions:\n * \"file_rewind\"\tRewind the file to start reading it again.\n * \"advance_fenc\"\tAdvance \"fenc\" using \"fenc_next\".\n * \"skip_read\"\tRe-use already read bytes (BOM detected).\n * \"did_iconv\"\ticonv() conversion failed, try 'charconvert'.\n * \"keep_fileformat\" Don't reset \"fileformat\".\n *\n * Other status indicators:\n * \"tmpname\"\tWhen != NULL did conversion with 'charconvert'.\n *\t\t\tOutput file has to be deleted afterwards.\n * \"iconv_fd\"\tWhen != -1 did conversion with iconv().\n */\nretry:\n\n if (file_rewind)\n {\n\tif (read_buffer)\n\t{\n\t read_buf_lnum = 1;\n\t read_buf_col = 0;\n\t}\n\telse if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)\n\t{\n\t /* Can't rewind the file, give up. */\n\t error = TRUE;\n\t goto failed;\n\t}\n\t/* Delete the previously read lines. */\n\twhile (lnum > from)\n\t ml_delete(lnum--, FALSE);\n\tfile_rewind = FALSE;\n#ifdef FEAT_MBYTE\n\tif (set_options)\n\t{\n\t curbuf->b_p_bomb = FALSE;\n\t curbuf->b_start_bomb = FALSE;\n\t}\n\tconv_error = 0;\n#endif\n }\n\n /*\n * When retrying with another \"fenc\" and the first time \"fileformat\"\n * will be reset.\n */\n if (keep_fileformat)\n\tkeep_fileformat = FALSE;\n else\n {\n\tif (eap != NULL && eap->force_ff != 0)\n\t{\n\t fileformat = get_fileformat_force(curbuf, eap);\n\t try_unix = try_dos = try_mac = FALSE;\n\t}\n\telse if (curbuf->b_p_bin)\n\t fileformat = EOL_UNIX;\t\t/* binary: use Unix format */\n\telse if (*p_ffs == NUL)\n\t fileformat = get_fileformat(curbuf);/* use format from buffer */\n\telse\n\t fileformat = EOL_UNKNOWN;\t\t/* detect from file */\n }\n\n#ifdef FEAT_MBYTE\n# ifdef USE_ICONV\n if (iconv_fd != (iconv_t)-1)\n {\n\t/* aborted conversion with iconv(), close the descriptor */\n\ticonv_close(iconv_fd);\n\ticonv_fd = (iconv_t)-1;\n }\n# endif\n\n if (advance_fenc)\n {\n\t/*\n\t * Try the next entry in 'fileencodings'.\n\t */\n\tadvance_fenc = FALSE;\n\n\tif (eap != NULL && eap->force_enc != 0)\n\t{\n\t /* Conversion given with \"++cc=\" wasn't possible, read\n\t * without conversion. */\n\t notconverted = TRUE;\n\t conv_error = 0;\n\t if (fenc_alloced)\n\t\tvim_free(fenc);\n\t fenc = (char_u *)\"\";\n\t fenc_alloced = FALSE;\n\t}\n\telse\n\t{\n\t if (fenc_alloced)\n\t\tvim_free(fenc);\n\t if (fenc_next != NULL)\n\t {\n\t\tfenc = next_fenc(&fenc_next);\n\t\tfenc_alloced = (fenc_next != NULL);\n\t }\n\t else\n\t {\n\t\tfenc = (char_u *)\"\";\n\t\tfenc_alloced = FALSE;\n\t }\n\t}\n\tif (tmpname != NULL)\n\t{\n\t mch_remove(tmpname);\t\t/* delete converted file */\n\t vim_free(tmpname);\n\t tmpname = NULL;\n\t}\n }\n\n /*\n * Conversion may be required when the encoding of the file is different\n * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.\n */\n fio_flags = 0;\n converted = need_conversion(fenc);\n if (converted)\n {\n\n\t/* \"ucs-bom\" means we need to check the first bytes of the file\n\t * for a BOM. */\n\tif (STRCMP(fenc, ENC_UCSBOM) == 0)\n\t fio_flags = FIO_UCSBOM;\n\n\t/*\n\t * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be\n\t * done. This is handled below after read(). Prepare the\n\t * fio_flags to avoid having to parse the string each time.\n\t * Also check for Unicode to Latin1 conversion, because iconv()\n\t * appears not to handle this correctly. This works just like\n\t * conversion to UTF-8 except how the resulting character is put in\n\t * the buffer.\n\t */\n\telse if (enc_utf8 || STRCMP(p_enc, \"latin1\") == 0)\n\t fio_flags = get_fio_flags(fenc);\n\n# ifdef WIN3264\n\t/*\n\t * Conversion from an MS-Windows codepage to UTF-8 or another codepage\n\t * is handled with MultiByteToWideChar().\n\t */\n\tif (fio_flags == 0)\n\t fio_flags = get_win_fio_flags(fenc);\n# endif\n\n# ifdef MACOS_CONVERT\n\t/* Conversion from Apple MacRoman to latin1 or UTF-8 */\n\tif (fio_flags == 0)\n\t fio_flags = get_mac_fio_flags(fenc);\n# endif\n\n# ifdef USE_ICONV\n\t/*\n\t * Try using iconv() if we can't convert internally.\n\t */\n\tif (fio_flags == 0\n# ifdef FEAT_EVAL\n\t\t&& !did_iconv\n# endif\n\t\t)\n\t iconv_fd = (iconv_t)my_iconv_open(\n\t\t\t\t enc_utf8 ? (char_u *)\"utf-8\" : p_enc, fenc);\n# endif\n\n# ifdef FEAT_EVAL\n\t/*\n\t * Use the 'charconvert' expression when conversion is required\n\t * and we can't do it internally or with iconv().\n\t */\n\tif (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL\n\t\t\t\t\t\t && !read_fifo\n# ifdef USE_ICONV\n\t\t\t\t\t\t && iconv_fd == (iconv_t)-1\n# endif\n\t\t)\n\t{\n# ifdef USE_ICONV\n\t did_iconv = FALSE;\n# endif\n\t /* Skip conversion when it's already done (retry for wrong\n\t * \"fileformat\"). */\n\t if (tmpname == NULL)\n\t {\n\t\ttmpname = readfile_charconvert(fname, fenc, &fd);\n\t\tif (tmpname == NULL)\n\t\t{\n\t\t /* Conversion failed. Try another one. */\n\t\t advance_fenc = TRUE;\n\t\t if (fd < 0)\n\t\t {\n\t\t\t/* Re-opening the original file failed! */\n\t\t\tEMSG(_(\"E202: Conversion made file unreadable!\"));\n\t\t\terror = TRUE;\n\t\t\tgoto failed;\n\t\t }\n\t\t goto retry;\n\t\t}\n\t }\n\t}\n\telse\n# endif\n\t{\n\t if (fio_flags == 0\n# ifdef USE_ICONV\n\t\t && iconv_fd == (iconv_t)-1\n# endif\n\t )\n\t {\n\t\t/* Conversion wanted but we can't.\n\t\t * Try the next conversion in 'fileencodings' */\n\t\tadvance_fenc = TRUE;\n\t\tgoto retry;\n\t }\n\t}\n }\n\n /* Set \"can_retry\" when it's possible to rewind the file and try with\n * another \"fenc\" value. It's FALSE when no other \"fenc\" to try, reading\n * stdin or fixed at a specific encoding. */\n can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);\n#endif\n\n if (!skip_read)\n {\n\tlinerest = 0;\n\tfilesize = 0;\n\tskip_count = lines_to_skip;\n\tread_count = lines_to_read;\n#ifdef FEAT_MBYTE\n\tconv_restlen = 0;\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\tread_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0\n\t\t\t\t && curbuf->b_ffname != NULL\n\t\t\t\t && curbuf->b_p_udf\n\t\t\t\t && !filtering\n\t\t\t\t && !read_fifo\n\t\t\t\t && !read_stdin\n\t\t\t\t && !read_buffer);\n\tif (read_undo_file)\n\t sha256_start(&sha_ctx);\n#endif\n#ifdef FEAT_CRYPT\n\tif (curbuf->b_cryptstate != NULL)\n\t{\n\t /* Need to free the state, but keep the key, don't want to ask for\n\t * it again. */\n\t crypt_free_state(curbuf->b_cryptstate);\n\t curbuf->b_cryptstate = NULL;\n\t}\n#endif\n }\n\n while (!error && !got_int)\n {\n\t/*\n\t * We allocate as much space for the file as we can get, plus\n\t * space for the old line plus room for one terminating NUL.\n\t * The amount is limited by the fact that read() only can read\n\t * upto max_unsigned characters (and other things).\n\t */\n#if VIM_SIZEOF_INT <= 2\n\tif (linerest >= 0x7ff0)\n\t{\n\t ++split;\n\t *ptr = NL;\t\t /* split line by inserting a NL */\n\t size = 1;\n\t}\n\telse\n#endif\n\t{\n\t if (!skip_read)\n\t {\n#if VIM_SIZEOF_INT > 2\n# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)\n\t\tsize = SSIZE_MAX;\t\t /* use max I/O size, 52K */\n# else\n\t\tsize = 0x10000L;\t\t /* use buffer >= 64K */\n# endif\n#else\n\t\tsize = 0x7ff0L - linerest;\t /* limit buffer to 32K */\n#endif\n\n\t\tfor ( ; size >= 10; size = (long)((long_u)size >> 1))\n\t\t{\n\t\t if ((new_buffer = lalloc((long_u)(size + linerest + 1),\n\t\t\t\t\t\t\t FALSE)) != NULL)\n\t\t\tbreak;\n\t\t}\n\t\tif (new_buffer == NULL)\n\t\t{\n\t\t do_outofmem_msg((long_u)(size * 2 + linerest + 1));\n\t\t error = TRUE;\n\t\t break;\n\t\t}\n\t\tif (linerest)\t/* copy characters from the previous buffer */\n\t\t mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);\n\t\tvim_free(buffer);\n\t\tbuffer = new_buffer;\n\t\tptr = buffer + linerest;\n\t\tline_start = buffer;\n\n#ifdef FEAT_MBYTE\n\t\t/* May need room to translate into.\n\t\t * For iconv() we don't really know the required space, use a\n\t\t * factor ICONV_MULT.\n\t\t * latin1 to utf-8: 1 byte becomes up to 2 bytes\n\t\t * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes\n\t\t * become up to 4 bytes, size must be multiple of 2\n\t\t * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be\n\t\t * multiple of 2\n\t\t * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be\n\t\t * multiple of 4 */\n\t\treal_size = (int)size;\n# ifdef USE_ICONV\n\t\tif (iconv_fd != (iconv_t)-1)\n\t\t size = size / ICONV_MULT;\n\t\telse\n# endif\n\t\t if (fio_flags & FIO_LATIN1)\n\t\t size = size / 2;\n\t\telse if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t size = (size * 2 / 3) & ~1;\n\t\telse if (fio_flags & FIO_UCS4)\n\t\t size = (size * 2 / 3) & ~3;\n\t\telse if (fio_flags == FIO_UCSBOM)\n\t\t size = size / ICONV_MULT;\t/* worst case */\n# ifdef WIN3264\n\t\telse if (fio_flags & FIO_CODEPAGE)\n\t\t size = size / ICONV_MULT;\t/* also worst case */\n# endif\n# ifdef MACOS_CONVERT\n\t\telse if (fio_flags & FIO_MACROMAN)\n\t\t size = size / ICONV_MULT;\t/* also worst case */\n# endif\n#endif\n\n#ifdef FEAT_MBYTE\n\t\tif (conv_restlen > 0)\n\t\t{\n\t\t /* Insert unconverted bytes from previous line. */\n\t\t mch_memmove(ptr, conv_rest, conv_restlen);\n\t\t ptr += conv_restlen;\n\t\t size -= conv_restlen;\n\t\t}\n#endif\n\n\t\tif (read_buffer)\n\t\t{\n\t\t /*\n\t\t * Read bytes from curbuf. Used for converting text read\n\t\t * from stdin.\n\t\t */\n\t\t if (read_buf_lnum > from)\n\t\t\tsize = 0;\n\t\t else\n\t\t {\n\t\t\tint\tn, ni;\n\t\t\tlong\ttlen;\n\n\t\t\ttlen = 0;\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t p = ml_get(read_buf_lnum) + read_buf_col;\n\t\t\t n = (int)STRLEN(p);\n\t\t\t if ((int)tlen + n + 1 > size)\n\t\t\t {\n\t\t\t\t/* Filled up to \"size\", append partial line.\n\t\t\t\t * Change NL to NUL to reverse the effect done\n\t\t\t\t * below. */\n\t\t\t\tn = (int)(size - tlen);\n\t\t\t\tfor (ni = 0; ni < n; ++ni)\n\t\t\t\t{\n\t\t\t\t if (p[ni] == NL)\n\t\t\t\t\tptr[tlen++] = NUL;\n\t\t\t\t else\n\t\t\t\t\tptr[tlen++] = p[ni];\n\t\t\t\t}\n\t\t\t\tread_buf_col += n;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\t/* Append whole line and new-line. Change NL\n\t\t\t\t * to NUL to reverse the effect done below. */\n\t\t\t\tfor (ni = 0; ni < n; ++ni)\n\t\t\t\t{\n\t\t\t\t if (p[ni] == NL)\n\t\t\t\t\tptr[tlen++] = NUL;\n\t\t\t\t else\n\t\t\t\t\tptr[tlen++] = p[ni];\n\t\t\t\t}\n\t\t\t\tptr[tlen++] = NL;\n\t\t\t\tread_buf_col = 0;\n\t\t\t\tif (++read_buf_lnum > from)\n\t\t\t\t{\n\t\t\t\t /* When the last line didn't have an\n\t\t\t\t * end-of-line don't add it now either. */\n\t\t\t\t if (!curbuf->b_p_eol)\n\t\t\t\t\t--tlen;\n\t\t\t\t size = tlen;\n\t\t\t\t break;\n\t\t\t\t}\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t /*\n\t\t * Read bytes from the file.\n\t\t */\n\t\t size = read_eintr(fd, ptr, size);\n\t\t}\n\n#ifdef FEAT_CRYPT\n\t\t/*\n\t\t * At start of file: Check for magic number of encryption.\n\t\t */\n\t\tif (filesize == 0 && size > 0)\n\t\t cryptkey = check_for_cryptkey(cryptkey, ptr, &size,\n\t\t\t\t\t\t &filesize, newfile, sfname,\n\t\t\t\t\t\t &did_ask_for_key);\n\t\t/*\n\t\t * Decrypt the read bytes. This is done before checking for\n\t\t * EOF because the crypt layer may be buffering.\n\t\t */\n\t\tif (cryptkey != NULL && curbuf->b_cryptstate != NULL\n\t\t\t\t\t\t\t\t && size > 0)\n\t\t{\n\t\t if (crypt_works_inplace(curbuf->b_cryptstate))\n\t\t {\n\t\t\tcrypt_decode_inplace(curbuf->b_cryptstate, ptr, size);\n\t\t }\n\t\t else\n\t\t {\n\t\t\tchar_u\t*newptr = NULL;\n\t\t\tint\tdecrypted_size;\n\n\t\t\tdecrypted_size = crypt_decode_alloc(\n\t\t\t\t curbuf->b_cryptstate, ptr, size, &newptr);\n\n\t\t\t/* If the crypt layer is buffering, not producing\n\t\t\t * anything yet, need to read more. */\n\t\t\tif (size > 0 && decrypted_size == 0)\n\t\t\t continue;\n\n\t\t\tif (linerest == 0)\n\t\t\t{\n\t\t\t /* Simple case: reuse returned buffer (may be\n\t\t\t * NULL, checked later). */\n\t\t\t new_buffer = newptr;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t long_u\tnew_size;\n\n\t\t\t /* Need new buffer to add bytes carried over. */\n\t\t\t new_size = (long_u)(decrypted_size + linerest + 1);\n\t\t\t new_buffer = lalloc(new_size, FALSE);\n\t\t\t if (new_buffer == NULL)\n\t\t\t {\n\t\t\t\tdo_outofmem_msg(new_size);\n\t\t\t\terror = TRUE;\n\t\t\t\tbreak;\n\t\t\t }\n\n\t\t\t mch_memmove(new_buffer, buffer, linerest);\n\t\t\t if (newptr != NULL)\n\t\t\t\tmch_memmove(new_buffer + linerest, newptr,\n\t\t\t\t\t\t\t decrypted_size);\n\t\t\t}\n\n\t\t\tif (new_buffer != NULL)\n\t\t\t{\n\t\t\t vim_free(buffer);\n\t\t\t buffer = new_buffer;\n\t\t\t new_buffer = NULL;\n\t\t\t line_start = buffer;\n\t\t\t ptr = buffer + linerest;\n\t\t\t}\n\t\t\tsize = decrypted_size;\n\t\t }\n\t\t}\n#endif\n\n\t\tif (size <= 0)\n\t\t{\n\t\t if (size < 0)\t\t /* read error */\n\t\t\terror = TRUE;\n#ifdef FEAT_MBYTE\n\t\t else if (conv_restlen > 0)\n\t\t {\n\t\t\t/*\n\t\t\t * Reached end-of-file but some trailing bytes could\n\t\t\t * not be converted. Truncated file?\n\t\t\t */\n\n\t\t\t/* When we did a conversion report an error. */\n\t\t\tif (fio_flags != 0\n# ifdef USE_ICONV\n\t\t\t\t|| iconv_fd != (iconv_t)-1\n# endif\n\t\t\t )\n\t\t\t{\n\t\t\t if (can_retry)\n\t\t\t\tgoto rewind_retry;\n\t\t\t if (conv_error == 0)\n\t\t\t\tconv_error = curbuf->b_ml.ml_line_count\n\t\t\t\t\t\t\t\t- linecnt + 1;\n\t\t\t}\n\t\t\t/* Remember the first linenr with an illegal byte */\n\t\t\telse if (illegal_byte == 0)\n\t\t\t illegal_byte = curbuf->b_ml.ml_line_count\n\t\t\t\t\t\t\t\t- linecnt + 1;\n\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t{\n\t\t\t *(ptr - conv_restlen) = NUL;\n\t\t\t conv_restlen = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t /* Replace the trailing bytes with the replacement\n\t\t\t * character if we were converting; if we weren't,\n\t\t\t * leave the UTF8 checking code to do it, as it\n\t\t\t * works slightly differently. */\n\t\t\t if (bad_char_behavior != BAD_KEEP && (fio_flags != 0\n# ifdef USE_ICONV\n\t\t\t\t || iconv_fd != (iconv_t)-1\n# endif\n\t\t\t ))\n\t\t\t {\n\t\t\t\twhile (conv_restlen > 0)\n\t\t\t\t{\n\t\t\t\t *(--ptr) = bad_char_behavior;\n\t\t\t\t --conv_restlen;\n\t\t\t\t}\n\t\t\t }\n\t\t\t fio_flags = 0;\t/* don't convert this */\n# ifdef USE_ICONV\n\t\t\t if (iconv_fd != (iconv_t)-1)\n\t\t\t {\n\t\t\t\ticonv_close(iconv_fd);\n\t\t\t\ticonv_fd = (iconv_t)-1;\n\t\t\t }\n# endif\n\t\t\t}\n\t\t }\n#endif\n\t\t}\n\t }\n\t skip_read = FALSE;\n\n#ifdef FEAT_MBYTE\n\t /*\n\t * At start of file (or after crypt magic number): Check for BOM.\n\t * Also check for a BOM for other Unicode encodings, but not after\n\t * converting with 'charconvert' or when a BOM has already been\n\t * found.\n\t */\n\t if ((filesize == 0\n# ifdef FEAT_CRYPT\n\t\t || (cryptkey != NULL\n\t\t\t&& filesize == crypt_get_header_len(\n\t\t\t\t\t\t crypt_get_method_nr(curbuf)))\n# endif\n\t\t )\n\t\t && (fio_flags == FIO_UCSBOM\n\t\t\t|| (!curbuf->b_p_bomb\n\t\t\t && tmpname == NULL\n\t\t\t && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))\n\t {\n\t\tchar_u\t*ccname;\n\t\tint\tblen;\n\n\t\t/* no BOM detection in a short file or in binary mode */\n\t\tif (size < 2 || curbuf->b_p_bin)\n\t\t ccname = NULL;\n\t\telse\n\t\t ccname = check_for_bom(ptr, size, &blen,\n\t\t fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));\n\t\tif (ccname != NULL)\n\t\t{\n\t\t /* Remove BOM from the text */\n\t\t filesize += blen;\n\t\t size -= blen;\n\t\t mch_memmove(ptr, ptr + blen, (size_t)size);\n\t\t if (set_options)\n\t\t {\n\t\t\tcurbuf->b_p_bomb = TRUE;\n\t\t\tcurbuf->b_start_bomb = TRUE;\n\t\t }\n\t\t}\n\n\t\tif (fio_flags == FIO_UCSBOM)\n\t\t{\n\t\t if (ccname == NULL)\n\t\t {\n\t\t\t/* No BOM detected: retry with next encoding. */\n\t\t\tadvance_fenc = TRUE;\n\t\t }\n\t\t else\n\t\t {\n\t\t\t/* BOM detected: set \"fenc\" and jump back */\n\t\t\tif (fenc_alloced)\n\t\t\t vim_free(fenc);\n\t\t\tfenc = ccname;\n\t\t\tfenc_alloced = FALSE;\n\t\t }\n\t\t /* retry reading without getting new bytes or rewinding */\n\t\t skip_read = TRUE;\n\t\t goto retry;\n\t\t}\n\t }\n\n\t /* Include not converted bytes. */\n\t ptr -= conv_restlen;\n\t size += conv_restlen;\n\t conv_restlen = 0;\n#endif\n\t /*\n\t * Break here for a read error or end-of-file.\n\t */\n\t if (size <= 0)\n\t\tbreak;\n\n#ifdef FEAT_MBYTE\n\n# ifdef USE_ICONV\n\t if (iconv_fd != (iconv_t)-1)\n\t {\n\t\t/*\n\t\t * Attempt conversion of the read bytes to 'encoding' using\n\t\t * iconv().\n\t\t */\n\t\tconst char\t*fromp;\n\t\tchar\t\t*top;\n\t\tsize_t\t\tfrom_size;\n\t\tsize_t\t\tto_size;\n\n\t\tfromp = (char *)ptr;\n\t\tfrom_size = size;\n\t\tptr += size;\n\t\ttop = (char *)ptr;\n\t\tto_size = real_size - size;\n\n\t\t/*\n\t\t * If there is conversion error or not enough room try using\n\t\t * another conversion. Except for when there is no\n\t\t * alternative (help files).\n\t\t */\n\t\twhile ((iconv(iconv_fd, (void *)&fromp, &from_size,\n\t\t\t\t\t\t\t &top, &to_size)\n\t\t\t == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)\n\t\t\t\t\t\t || from_size > CONV_RESTLEN)\n\t\t{\n\t\t if (can_retry)\n\t\t\tgoto rewind_retry;\n\t\t if (conv_error == 0)\n\t\t\tconv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t ptr, (char_u *)top);\n\n\t\t /* Deal with a bad byte and continue with the next. */\n\t\t ++fromp;\n\t\t --from_size;\n\t\t if (bad_char_behavior == BAD_KEEP)\n\t\t {\n\t\t\t*top++ = *(fromp - 1);\n\t\t\t--to_size;\n\t\t }\n\t\t else if (bad_char_behavior != BAD_DROP)\n\t\t {\n\t\t\t*top++ = bad_char_behavior;\n\t\t\t--to_size;\n\t\t }\n\t\t}\n\n\t\tif (from_size > 0)\n\t\t{\n\t\t /* Some remaining characters, keep them for the next\n\t\t * round. */\n\t\t mch_memmove(conv_rest, (char_u *)fromp, from_size);\n\t\t conv_restlen = (int)from_size;\n\t\t}\n\n\t\t/* move the linerest to before the converted characters */\n\t\tline_start = ptr - linerest;\n\t\tmch_memmove(line_start, buffer, (size_t)linerest);\n\t\tsize = (long)((char_u *)top - ptr);\n\t }\n# endif\n\n# ifdef WIN3264\n\t if (fio_flags & FIO_CODEPAGE)\n\t {\n\t\tchar_u\t*src, *dst;\n\t\tWCHAR\tucs2buf[3];\n\t\tint\tucs2len;\n\t\tint\tcodepage = FIO_GET_CP(fio_flags);\n\t\tint\tbytelen;\n\t\tint\tfound_bad;\n\t\tchar\treplstr[2];\n\n\t\t/*\n\t\t * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or\n\t\t * a codepage, using standard MS-Windows functions. This\n\t\t * requires two steps:\n\t\t * 1. convert from 'fileencoding' to ucs-2\n\t\t * 2. convert from ucs-2 to 'encoding'\n\t\t *\n\t\t * Because there may be illegal bytes AND an incomplete byte\n\t\t * sequence at the end, we may have to do the conversion one\n\t\t * character at a time to get it right.\n\t\t */\n\n\t\t/* Replacement string for WideCharToMultiByte(). */\n\t\tif (bad_char_behavior > 0)\n\t\t replstr[0] = bad_char_behavior;\n\t\telse\n\t\t replstr[0] = '?';\n\t\treplstr[1] = NUL;\n\n\t\t/*\n\t\t * Move the bytes to the end of the buffer, so that we have\n\t\t * room to put the result at the start.\n\t\t */\n\t\tsrc = ptr + real_size - size;\n\t\tmch_memmove(src, ptr, size);\n\n\t\t/*\n\t\t * Do the conversion.\n\t\t */\n\t\tdst = ptr;\n\t\tsize = size;\n\t\twhile (size > 0)\n\t\t{\n\t\t found_bad = FALSE;\n\n# ifdef CP_UTF8\t/* VC 4.1 doesn't define CP_UTF8 */\n\t\t if (codepage == CP_UTF8)\n\t\t {\n\t\t\t/* Handle CP_UTF8 input ourselves to be able to handle\n\t\t\t * trailing bytes properly.\n\t\t\t * Get one UTF-8 character from src. */\n\t\t\tbytelen = (int)utf_ptr2len_len(src, size);\n\t\t\tif (bytelen > size)\n\t\t\t{\n\t\t\t /* Only got some bytes of a character. Normally\n\t\t\t * it's put in \"conv_rest\", but if it's too long\n\t\t\t * deal with it as if they were illegal bytes. */\n\t\t\t if (bytelen <= CONV_RESTLEN)\n\t\t\t\tbreak;\n\n\t\t\t /* weird overlong byte sequence */\n\t\t\t bytelen = size;\n\t\t\t found_bad = TRUE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t int\t u8c = utf_ptr2char(src);\n\n\t\t\t if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))\n\t\t\t\tfound_bad = TRUE;\n\t\t\t ucs2buf[0] = u8c;\n\t\t\t ucs2len = 1;\n\t\t\t}\n\t\t }\n\t\t else\n# endif\n\t\t {\n\t\t\t/* We don't know how long the byte sequence is, try\n\t\t\t * from one to three bytes. */\n\t\t\tfor (bytelen = 1; bytelen <= size && bytelen <= 3;\n\t\t\t\t\t\t\t\t ++bytelen)\n\t\t\t{\n\t\t\t ucs2len = MultiByteToWideChar(codepage,\n\t\t\t\t\t\t\t MB_ERR_INVALID_CHARS,\n\t\t\t\t\t\t\t (LPCSTR)src, bytelen,\n\t\t\t\t\t\t\t\t ucs2buf, 3);\n\t\t\t if (ucs2len > 0)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ucs2len == 0)\n\t\t\t{\n\t\t\t /* If we have only one byte then it's probably an\n\t\t\t * incomplete byte sequence. Otherwise discard\n\t\t\t * one byte as a bad character. */\n\t\t\t if (size == 1)\n\t\t\t\tbreak;\n\t\t\t found_bad = TRUE;\n\t\t\t bytelen = 1;\n\t\t\t}\n\t\t }\n\n\t\t if (!found_bad)\n\t\t {\n\t\t\tint\ti;\n\n\t\t\t/* Convert \"ucs2buf[ucs2len]\" to 'enc' in \"dst\". */\n\t\t\tif (enc_utf8)\n\t\t\t{\n\t\t\t /* From UCS-2 to UTF-8. Cannot fail. */\n\t\t\t for (i = 0; i < ucs2len; ++i)\n\t\t\t\tdst += utf_char2bytes(ucs2buf[i], dst);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t BOOL\tbad = FALSE;\n\t\t\t int\t\tdstlen;\n\n\t\t\t /* From UCS-2 to \"enc_codepage\". If the\n\t\t\t * conversion uses the default character \"?\",\n\t\t\t * the data doesn't fit in this encoding. */\n\t\t\t dstlen = WideCharToMultiByte(enc_codepage, 0,\n\t\t\t\t (LPCWSTR)ucs2buf, ucs2len,\n\t\t\t\t (LPSTR)dst, (int)(src - dst),\n\t\t\t\t replstr, &bad);\n\t\t\t if (bad)\n\t\t\t\tfound_bad = TRUE;\n\t\t\t else\n\t\t\t\tdst += dstlen;\n\t\t\t}\n\t\t }\n\n\t\t if (found_bad)\n\t\t {\n\t\t\t/* Deal with bytes we can't convert. */\n\t\t\tif (can_retry)\n\t\t\t goto rewind_retry;\n\t\t\tif (conv_error == 0)\n\t\t\t conv_error = readfile_linenr(linecnt, ptr, dst);\n\t\t\tif (bad_char_behavior != BAD_DROP)\n\t\t\t{\n\t\t\t if (bad_char_behavior == BAD_KEEP)\n\t\t\t {\n\t\t\t\tmch_memmove(dst, src, bytelen);\n\t\t\t\tdst += bytelen;\n\t\t\t }\n\t\t\t else\n\t\t\t\t*dst++ = bad_char_behavior;\n\t\t\t}\n\t\t }\n\n\t\t src += bytelen;\n\t\t size -= bytelen;\n\t\t}\n\n\t\tif (size > 0)\n\t\t{\n\t\t /* An incomplete byte sequence remaining. */\n\t\t mch_memmove(conv_rest, src, size);\n\t\t conv_restlen = size;\n\t\t}\n\n\t\t/* The new size is equal to how much \"dst\" was advanced. */\n\t\tsize = (long)(dst - ptr);\n\t }\n\t else\n# endif\n# ifdef MACOS_CONVERT\n\t if (fio_flags & FIO_MACROMAN)\n\t {\n\t\t/*\n\t\t * Conversion from Apple MacRoman char encoding to UTF-8 or\n\t\t * latin1. This is in os_mac_conv.c.\n\t\t */\n\t\tif (macroman2enc(ptr, &size, real_size) == FAIL)\n\t\t goto rewind_retry;\n\t }\n\t else\n# endif\n\t if (fio_flags != 0)\n\t {\n\t\tint\tu8c;\n\t\tchar_u\t*dest;\n\t\tchar_u\t*tail = NULL;\n\n\t\t/*\n\t\t * \"enc_utf8\" set: Convert Unicode or Latin1 to UTF-8.\n\t\t * \"enc_utf8\" not set: Convert Unicode to Latin1.\n\t\t * Go from end to start through the buffer, because the number\n\t\t * of bytes may increase.\n\t\t * \"dest\" points to after where the UTF-8 bytes go, \"p\" points\n\t\t * to after the next character to convert.\n\t\t */\n\t\tdest = ptr + real_size;\n\t\tif (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)\n\t\t{\n\t\t p = ptr + size;\n\t\t if (fio_flags == FIO_UTF8)\n\t\t {\n\t\t\t/* Check for a trailing incomplete UTF-8 sequence */\n\t\t\ttail = ptr + size - 1;\n\t\t\twhile (tail > ptr && (*tail & 0xc0) == 0x80)\n\t\t\t --tail;\n\t\t\tif (tail + utf_byte2len(*tail) <= ptr + size)\n\t\t\t tail = NULL;\n\t\t\telse\n\t\t\t p = tail;\n\t\t }\n\t\t}\n\t\telse if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t{\n\t\t /* Check for a trailing byte */\n\t\t p = ptr + (size & ~1);\n\t\t if (size & 1)\n\t\t\ttail = p;\n\t\t if ((fio_flags & FIO_UTF16) && p > ptr)\n\t\t {\n\t\t\t/* Check for a trailing leading word */\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (*--p << 8);\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (*--p << 8);\n\t\t\t}\n\t\t\tif (u8c >= 0xd800 && u8c <= 0xdbff)\n\t\t\t tail = p;\n\t\t\telse\n\t\t\t p += 2;\n\t\t }\n\t\t}\n\t\telse /* FIO_UCS4 */\n\t\t{\n\t\t /* Check for trailing 1, 2 or 3 bytes */\n\t\t p = ptr + (size & ~3);\n\t\t if (size & 3)\n\t\t\ttail = p;\n\t\t}\n\n\t\t/* If there is a trailing incomplete sequence move it to\n\t\t * conv_rest[]. */\n\t\tif (tail != NULL)\n\t\t{\n\t\t conv_restlen = (int)((ptr + size) - tail);\n\t\t mch_memmove(conv_rest, (char_u *)tail, conv_restlen);\n\t\t size -= conv_restlen;\n\t\t}\n\n\n\t\twhile (p > ptr)\n\t\t{\n\t\t if (fio_flags & FIO_LATIN1)\n\t\t\tu8c = *--p;\n\t\t else if (fio_flags & (FIO_UCS2 | FIO_UTF16))\n\t\t {\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (*--p << 8);\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (*--p << 8);\n\t\t\t}\n\t\t\tif ((fio_flags & FIO_UTF16)\n\t\t\t\t\t && u8c >= 0xdc00 && u8c <= 0xdfff)\n\t\t\t{\n\t\t\t int u16c;\n\n\t\t\t if (p == ptr)\n\t\t\t {\n\t\t\t\t/* Missing leading word. */\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\n\t\t\t /* found second word of double-word, get the first\n\t\t\t * word and compute the resulting character */\n\t\t\t if (fio_flags & FIO_ENDIAN_L)\n\t\t\t {\n\t\t\t\tu16c = (*--p << 8);\n\t\t\t\tu16c += *--p;\n\t\t\t }\n\t\t\t else\n\t\t\t {\n\t\t\t\tu16c = *--p;\n\t\t\t\tu16c += (*--p << 8);\n\t\t\t }\n\t\t\t u8c = 0x10000 + ((u16c & 0x3ff) << 10)\n\t\t\t\t\t\t\t + (u8c & 0x3ff);\n\n\t\t\t /* Check if the word is indeed a leading word. */\n\t\t\t if (u16c < 0xd800 || u16c > 0xdbff)\n\t\t\t {\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t else if (fio_flags & FIO_UCS4)\n\t\t {\n\t\t\tif (fio_flags & FIO_ENDIAN_L)\n\t\t\t{\n\t\t\t u8c = (unsigned)*--p << 24;\n\t\t\t u8c += (unsigned)*--p << 16;\n\t\t\t u8c += (unsigned)*--p << 8;\n\t\t\t u8c += *--p;\n\t\t\t}\n\t\t\telse\t/* big endian */\n\t\t\t{\n\t\t\t u8c = *--p;\n\t\t\t u8c += (unsigned)*--p << 8;\n\t\t\t u8c += (unsigned)*--p << 16;\n\t\t\t u8c += (unsigned)*--p << 24;\n\t\t\t}\n\t\t }\n\t\t else /* UTF-8 */\n\t\t {\n\t\t\tif (*--p < 0x80)\n\t\t\t u8c = *p;\n\t\t\telse\n\t\t\t{\n\t\t\t len = utf_head_off(ptr, p);\n\t\t\t p -= len;\n\t\t\t u8c = utf_ptr2char(p);\n\t\t\t if (len == 0)\n\t\t\t {\n\t\t\t\t/* Not a valid UTF-8 character, retry with\n\t\t\t\t * another fenc when possible, otherwise just\n\t\t\t\t * report the error. */\n\t\t\t\tif (can_retry)\n\t\t\t\t goto rewind_retry;\n\t\t\t\tif (conv_error == 0)\n\t\t\t\t conv_error = readfile_linenr(linecnt,\n\t\t\t\t\t\t\t\t ptr, p);\n\t\t\t\tif (bad_char_behavior == BAD_DROP)\n\t\t\t\t continue;\n\t\t\t\tif (bad_char_behavior != BAD_KEEP)\n\t\t\t\t u8c = bad_char_behavior;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t if (enc_utf8)\t/* produce UTF-8 */\n\t\t {\n\t\t\tdest -= utf_char2len(u8c);\n\t\t\t(void)utf_char2bytes(u8c, dest);\n\t\t }\n\t\t else\t\t/* produce Latin1 */\n\t\t {\n\t\t\t--dest;\n\t\t\tif (u8c >= 0x100)\n\t\t\t{\n\t\t\t /* character doesn't fit in latin1, retry with\n\t\t\t * another fenc when possible, otherwise just\n\t\t\t * report the error. */\n\t\t\t if (can_retry)\n\t\t\t\tgoto rewind_retry;\n\t\t\t if (conv_error == 0)\n\t\t\t\tconv_error = readfile_linenr(linecnt, ptr, p);\n\t\t\t if (bad_char_behavior == BAD_DROP)\n\t\t\t\t++dest;\n\t\t\t else if (bad_char_behavior == BAD_KEEP)\n\t\t\t\t*dest = u8c;\n\t\t\t else if (eap != NULL && eap->bad_char != 0)\n\t\t\t\t*dest = bad_char_behavior;\n\t\t\t else\n\t\t\t\t*dest = 0xBF;\n\t\t\t}\n\t\t\telse\n\t\t\t *dest = u8c;\n\t\t }\n\t\t}\n\n\t\t/* move the linerest to before the converted characters */\n\t\tline_start = dest - linerest;\n\t\tmch_memmove(line_start, buffer, (size_t)linerest);\n\t\tsize = (long)((ptr + real_size) - dest);\n\t\tptr = dest;\n\t }\n\t else if (enc_utf8 && !curbuf->b_p_bin)\n\t {\n\t\tint incomplete_tail = FALSE;\n\n\t\t/* Reading UTF-8: Check if the bytes are valid UTF-8. */\n\t\tfor (p = ptr; ; ++p)\n\t\t{\n\t\t int\t todo = (int)((ptr + size) - p);\n\t\t int\t l;\n\n\t\t if (todo <= 0)\n\t\t\tbreak;\n\t\t if (*p >= 0x80)\n\t\t {\n\t\t\t/* A length of 1 means it's an illegal byte. Accept\n\t\t\t * an incomplete character at the end though, the next\n\t\t\t * read() will get the next bytes, we'll check it\n\t\t\t * then. */\n\t\t\tl = utf_ptr2len_len(p, todo);\n\t\t\tif (l > todo && !incomplete_tail)\n\t\t\t{\n\t\t\t /* Avoid retrying with a different encoding when\n\t\t\t * a truncated file is more likely, or attempting\n\t\t\t * to read the rest of an incomplete sequence when\n\t\t\t * we have already done so. */\n\t\t\t if (p > ptr || filesize > 0)\n\t\t\t\tincomplete_tail = TRUE;\n\t\t\t /* Incomplete byte sequence, move it to conv_rest[]\n\t\t\t * and try to read the rest of it, unless we've\n\t\t\t * already done so. */\n\t\t\t if (p > ptr)\n\t\t\t {\n\t\t\t\tconv_restlen = todo;\n\t\t\t\tmch_memmove(conv_rest, p, conv_restlen);\n\t\t\t\tsize -= conv_restlen;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}\n\t\t\tif (l == 1 || l > todo)\n\t\t\t{\n\t\t\t /* Illegal byte. If we can try another encoding\n\t\t\t * do that, unless at EOF where a truncated\n\t\t\t * file is more likely than a conversion error. */\n\t\t\t if (can_retry && !incomplete_tail)\n\t\t\t\tbreak;\n# ifdef USE_ICONV\n\t\t\t /* When we did a conversion report an error. */\n\t\t\t if (iconv_fd != (iconv_t)-1 && conv_error == 0)\n\t\t\t\tconv_error = readfile_linenr(linecnt, ptr, p);\n# endif\n\t\t\t /* Remember the first linenr with an illegal byte */\n\t\t\t if (conv_error == 0 && illegal_byte == 0)\n\t\t\t\tillegal_byte = readfile_linenr(linecnt, ptr, p);\n\n\t\t\t /* Drop, keep or replace the bad byte. */\n\t\t\t if (bad_char_behavior == BAD_DROP)\n\t\t\t {\n\t\t\t\tmch_memmove(p, p + 1, todo - 1);\n\t\t\t\t--p;\n\t\t\t\t--size;\n\t\t\t }\n\t\t\t else if (bad_char_behavior != BAD_KEEP)\n\t\t\t\t*p = bad_char_behavior;\n\t\t\t}\n\t\t\telse\n\t\t\t p += l - 1;\n\t\t }\n\t\t}\n\t\tif (p < ptr + size && !incomplete_tail)\n\t\t{\n\t\t /* Detected a UTF-8 error. */\nrewind_retry:\n\t\t /* Retry reading with another conversion. */\n# if defined(FEAT_EVAL) && defined(USE_ICONV)\n\t\t if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)\n\t\t\t/* iconv() failed, try 'charconvert' */\n\t\t\tdid_iconv = TRUE;\n\t\t else\n# endif\n\t\t\t/* use next item from 'fileencodings' */\n\t\t\tadvance_fenc = TRUE;\n\t\t file_rewind = TRUE;\n\t\t goto retry;\n\t\t}\n\t }\n#endif\n\n\t /* count the number of characters (after conversion!) */\n\t filesize += size;\n\n\t /*\n\t * when reading the first part of a file: guess EOL type\n\t */\n\t if (fileformat == EOL_UNKNOWN)\n\t {\n\t\t/* First try finding a NL, for Dos and Unix */\n\t\tif (try_dos || try_unix)\n\t\t{\n\t\t /* Reset the carriage return counter. */\n\t\t if (try_mac)\n\t\t\ttry_mac = 1;\n\n\t\t for (p = ptr; p < ptr + size; ++p)\n\t\t {\n\t\t\tif (*p == NL)\n\t\t\t{\n\t\t\t if (!try_unix\n\t\t\t\t || (try_dos && p > ptr && p[-1] == CAR))\n\t\t\t\tfileformat = EOL_DOS;\n\t\t\t else\n\t\t\t\tfileformat = EOL_UNIX;\n\t\t\t break;\n\t\t\t}\n\t\t\telse if (*p == CAR && try_mac)\n\t\t\t try_mac++;\n\t\t }\n\n\t\t /* Don't give in to EOL_UNIX if EOL_MAC is more likely */\n\t\t if (fileformat == EOL_UNIX && try_mac)\n\t\t {\n\t\t\t/* Need to reset the counters when retrying fenc. */\n\t\t\ttry_mac = 1;\n\t\t\ttry_unix = 1;\n\t\t\tfor (; p >= ptr && *p != CAR; p--)\n\t\t\t ;\n\t\t\tif (p >= ptr)\n\t\t\t{\n\t\t\t for (p = ptr; p < ptr + size; ++p)\n\t\t\t {\n\t\t\t\tif (*p == NL)\n\t\t\t\t try_unix++;\n\t\t\t\telse if (*p == CAR)\n\t\t\t\t try_mac++;\n\t\t\t }\n\t\t\t if (try_mac > try_unix)\n\t\t\t\tfileformat = EOL_MAC;\n\t\t\t}\n\t\t }\n\t\t else if (fileformat == EOL_UNKNOWN && try_mac == 1)\n\t\t\t/* Looking for CR but found no end-of-line markers at\n\t\t\t * all: use the default format. */\n\t\t\tfileformat = default_fileformat();\n\t\t}\n\n\t\t/* No NL found: may use Mac format */\n\t\tif (fileformat == EOL_UNKNOWN && try_mac)\n\t\t fileformat = EOL_MAC;\n\n\t\t/* Still nothing found? Use first format in 'ffs' */\n\t\tif (fileformat == EOL_UNKNOWN)\n\t\t fileformat = default_fileformat();\n\n\t\t/* if editing a new file: may set p_tx and p_ff */\n\t\tif (set_options)\n\t\t set_fileformat(fileformat, OPT_LOCAL);\n\t }\n\t}\n\n\t/*\n\t * This loop is executed once for every character read.\n\t * Keep it fast!\n\t */\n\tif (fileformat == EOL_MAC)\n\t{\n\t --ptr;\n\t while (++ptr, --size >= 0)\n\t {\n\t\t/* catch most common case first */\n\t\tif ((c = *ptr) != NUL && c != CAR && c != NL)\n\t\t continue;\n\t\tif (c == NUL)\n\t\t *ptr = NL;\t/* NULs are replaced by newlines! */\n\t\telse if (c == NL)\n\t\t *ptr = CAR;\t/* NLs are replaced by CRs! */\n\t\telse\n\t\t{\n\t\t if (skip_count == 0)\n\t\t {\n\t\t\t*ptr = NUL;\t /* end of line */\n\t\t\tlen = (colnr_T) (ptr - line_start + 1);\n\t\t\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t\t\t{\n\t\t\t error = TRUE;\n\t\t\t break;\n\t\t\t}\n#ifdef FEAT_PERSISTENT_UNDO\n\t\t\tif (read_undo_file)\n\t\t\t sha256_update(&sha_ctx, line_start, len);\n#endif\n\t\t\t++lnum;\n\t\t\tif (--read_count == 0)\n\t\t\t{\n\t\t\t error = TRUE;\t/* break loop */\n\t\t\t line_start = ptr;\t/* nothing left to write */\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t\t--skip_count;\n\t\t line_start = ptr + 1;\n\t\t}\n\t }\n\t}\n\telse\n\t{\n\t --ptr;\n\t while (++ptr, --size >= 0)\n\t {\n\t\tif ((c = *ptr) != NUL && c != NL) /* catch most common case */\n\t\t continue;\n\t\tif (c == NUL)\n\t\t *ptr = NL;\t/* NULs are replaced by newlines! */\n\t\telse\n\t\t{\n\t\t if (skip_count == 0)\n\t\t {\n\t\t\t*ptr = NUL;\t\t/* end of line */\n\t\t\tlen = (colnr_T)(ptr - line_start + 1);\n\t\t\tif (fileformat == EOL_DOS)\n\t\t\t{\n\t\t\t if (ptr > line_start && ptr[-1] == CAR)\n\t\t\t {\n\t\t\t\t/* remove CR before NL */\n\t\t\t\tptr[-1] = NUL;\n\t\t\t\t--len;\n\t\t\t }\n\t\t\t /*\n\t\t\t * Reading in Dos format, but no CR-LF found!\n\t\t\t * When 'fileformats' includes \"unix\", delete all\n\t\t\t * the lines read so far and start all over again.\n\t\t\t * Otherwise give an error message later.\n\t\t\t */\n\t\t\t else if (ff_error != EOL_DOS)\n\t\t\t {\n\t\t\t\tif ( try_unix\n\t\t\t\t && !read_stdin\n\t\t\t\t && (read_buffer\n\t\t\t\t\t|| vim_lseek(fd, (off_T)0L, SEEK_SET)\n\t\t\t\t\t\t\t\t\t == 0))\n\t\t\t\t{\n\t\t\t\t fileformat = EOL_UNIX;\n\t\t\t\t if (set_options)\n\t\t\t\t\tset_fileformat(EOL_UNIX, OPT_LOCAL);\n\t\t\t\t file_rewind = TRUE;\n\t\t\t\t keep_fileformat = TRUE;\n\t\t\t\t goto retry;\n\t\t\t\t}\n\t\t\t\tff_error = EOL_DOS;\n\t\t\t }\n\t\t\t}\n\t\t\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t\t\t{\n\t\t\t error = TRUE;\n\t\t\t break;\n\t\t\t}\n#ifdef FEAT_PERSISTENT_UNDO\n\t\t\tif (read_undo_file)\n\t\t\t sha256_update(&sha_ctx, line_start, len);\n#endif\n\t\t\t++lnum;\n\t\t\tif (--read_count == 0)\n\t\t\t{\n\t\t\t error = TRUE;\t /* break loop */\n\t\t\t line_start = ptr;\t/* nothing left to write */\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t\t--skip_count;\n\t\t line_start = ptr + 1;\n\t\t}\n\t }\n\t}\n\tlinerest = (long)(ptr - line_start);\n\tui_breakcheck();\n }\n\nfailed:\n /* not an error, max. number of lines reached */\n if (error && read_count == 0)\n\terror = FALSE;\n\n /*\n * If we get EOF in the middle of a line, note the fact and\n * complete the line ourselves.\n * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.\n */\n if (!error\n\t && !got_int\n\t && linerest != 0\n\t && !(!curbuf->b_p_bin\n\t\t&& fileformat == EOL_DOS\n\t\t&& *line_start == Ctrl_Z\n\t\t&& ptr == line_start + 1))\n {\n\t/* remember for when writing */\n\tif (set_options)\n\t curbuf->b_p_eol = FALSE;\n\t*ptr = NUL;\n\tlen = (colnr_T)(ptr - line_start + 1);\n\tif (ml_append(lnum, line_start, len, newfile) == FAIL)\n\t error = TRUE;\n\telse\n\t{\n#ifdef FEAT_PERSISTENT_UNDO\n\t if (read_undo_file)\n\t\tsha256_update(&sha_ctx, line_start, len);\n#endif\n\t read_no_eol_lnum = ++lnum;\n\t}\n }\n\n if (set_options)\n\tsave_file_ff(curbuf);\t\t/* remember the current file format */\n\n#ifdef FEAT_CRYPT\n if (curbuf->b_cryptstate != NULL)\n {\n\tcrypt_free_state(curbuf->b_cryptstate);\n\tcurbuf->b_cryptstate = NULL;\n }\n if (cryptkey != NULL && cryptkey != curbuf->b_p_key)\n\tcrypt_free_key(cryptkey);\n /* Don't set cryptkey to NULL, it's used below as a flag that\n * encryption was used. */\n#endif\n\n#ifdef FEAT_MBYTE\n /* If editing a new file: set 'fenc' for the current buffer.\n * Also for \":read ++edit file\". */\n if (set_options)\n\tset_string_option_direct((char_u *)\"fenc\", -1, fenc,\n\t\t\t\t\t\t OPT_FREE|OPT_LOCAL, 0);\n if (fenc_alloced)\n\tvim_free(fenc);\n# ifdef USE_ICONV\n if (iconv_fd != (iconv_t)-1)\n {\n\ticonv_close(iconv_fd);\n\ticonv_fd = (iconv_t)-1;\n }\n# endif\n#endif\n\n if (!read_buffer && !read_stdin)\n\tclose(fd);\t\t\t\t/* errors are ignored */\n#ifdef HAVE_FD_CLOEXEC\n else\n {\n\tint fdflags = fcntl(fd, F_GETFD);\n\tif (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)\n\t (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);\n }\n#endif\n vim_free(buffer);\n\n#ifdef HAVE_DUP\n if (read_stdin)\n {\n\t/* Use stderr for stdin, makes shell commands work. */\n\tclose(0);\n\tignored = dup(2);\n }\n#endif\n\n#ifdef FEAT_MBYTE\n if (tmpname != NULL)\n {\n\tmch_remove(tmpname);\t\t/* delete converted file */\n\tvim_free(tmpname);\n }\n#endif\n --no_wait_return;\t\t\t/* may wait for return now */\n\n /*\n * In recovery mode everything but autocommands is skipped.\n */\n if (!recoverymode)\n {\n\t/* need to delete the last line, which comes from the empty buffer */\n\tif (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))\n\t{\n#ifdef FEAT_NETBEANS_INTG\n\t netbeansFireChanges = 0;\n#endif\n\t ml_delete(curbuf->b_ml.ml_line_count, FALSE);\n#ifdef FEAT_NETBEANS_INTG\n\t netbeansFireChanges = 1;\n#endif\n\t --linecnt;\n\t}\n\tlinecnt = curbuf->b_ml.ml_line_count - linecnt;\n\tif (filesize == 0)\n\t linecnt = 0;\n\tif (newfile || read_buffer)\n\t{\n\t redraw_curbuf_later(NOT_VALID);\n#ifdef FEAT_DIFF\n\t /* After reading the text into the buffer the diff info needs to\n\t * be updated. */\n\t diff_invalidate(curbuf);\n#endif\n#ifdef FEAT_FOLDING\n\t /* All folds in the window are invalid now. Mark them for update\n\t * before triggering autocommands. */\n\t foldUpdateAll(curwin);\n#endif\n\t}\n\telse if (linecnt)\t\t/* appended at least one line */\n\t appended_lines_mark(from, linecnt);\n\n#ifndef ALWAYS_USE_GUI\n\t/*\n\t * If we were reading from the same terminal as where messages go,\n\t * the screen will have been messed up.\n\t * Switch on raw mode now and clear the screen.\n\t */\n\tif (read_stdin)\n\t{\n\t settmode(TMODE_RAW);\t/* set to raw mode */\n\t starttermcap();\n\t screenclear();\n\t}\n#endif\n\n\tif (got_int)\n\t{\n\t if (!(flags & READ_DUMMY))\n\t {\n\t\tfilemess(curbuf, sfname, (char_u *)_(e_interr), 0);\n\t\tif (newfile)\n\t\t curbuf->b_p_ro = TRUE;\t/* must use \"w!\" now */\n\t }\n\t msg_scroll = msg_save;\n#ifdef FEAT_VIMINFO\n\t check_marks_read();\n#endif\n\t return OK;\t\t/* an interrupt isn't really an error */\n\t}\n\n\tif (!filtering && !(flags & READ_DUMMY))\n\t{\n\t msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */\n\t c = FALSE;\n\n#ifdef UNIX\n# ifdef S_ISFIFO\n\t if (S_ISFIFO(perm))\t\t\t /* fifo or socket */\n\t {\n\t\tSTRCAT(IObuff, _(\"[fifo/socket]\"));\n\t\tc = TRUE;\n\t }\n# else\n# ifdef S_IFIFO\n\t if ((perm & S_IFMT) == S_IFIFO)\t /* fifo */\n\t {\n\t\tSTRCAT(IObuff, _(\"[fifo]\"));\n\t\tc = TRUE;\n\t }\n# endif\n# ifdef S_IFSOCK\n\t if ((perm & S_IFMT) == S_IFSOCK)\t /* or socket */\n\t {\n\t\tSTRCAT(IObuff, _(\"[socket]\"));\n\t\tc = TRUE;\n\t }\n# endif\n# endif\n# ifdef OPEN_CHR_FILES\n\t if (S_ISCHR(perm))\t\t\t /* or character special */\n\t {\n\t\tSTRCAT(IObuff, _(\"[character special]\"));\n\t\tc = TRUE;\n\t }\n# endif\n#endif\n\t if (curbuf->b_p_ro)\n\t {\n\t\tSTRCAT(IObuff, shortmess(SHM_RO) ? _(\"[RO]\") : _(\"[readonly]\"));\n\t\tc = TRUE;\n\t }\n\t if (read_no_eol_lnum)\n\t {\n\t\tmsg_add_eol();\n\t\tc = TRUE;\n\t }\n\t if (ff_error == EOL_DOS)\n\t {\n\t\tSTRCAT(IObuff, _(\"[CR missing]\"));\n\t\tc = TRUE;\n\t }\n\t if (split)\n\t {\n\t\tSTRCAT(IObuff, _(\"[long lines split]\"));\n\t\tc = TRUE;\n\t }\n#ifdef FEAT_MBYTE\n\t if (notconverted)\n\t {\n\t\tSTRCAT(IObuff, _(\"[NOT converted]\"));\n\t\tc = TRUE;\n\t }\n\t else if (converted)\n\t {\n\t\tSTRCAT(IObuff, _(\"[converted]\"));\n\t\tc = TRUE;\n\t }\n#endif\n#ifdef FEAT_CRYPT\n\t if (cryptkey != NULL)\n\t {\n\t\tcrypt_append_msg(curbuf);\n\t\tc = TRUE;\n\t }\n#endif\n#ifdef FEAT_MBYTE\n\t if (conv_error != 0)\n\t {\n\t\tsprintf((char *)IObuff + STRLEN(IObuff),\n\t\t _(\"[CONVERSION ERROR in line %ld]\"), (long)conv_error);\n\t\tc = TRUE;\n\t }\n\t else if (illegal_byte > 0)\n\t {\n\t\tsprintf((char *)IObuff + STRLEN(IObuff),\n\t\t\t _(\"[ILLEGAL BYTE in line %ld]\"), (long)illegal_byte);\n\t\tc = TRUE;\n\t }\n\t else\n#endif\n\t\tif (error)\n\t {\n\t\tSTRCAT(IObuff, _(\"[READ ERRORS]\"));\n\t\tc = TRUE;\n\t }\n\t if (msg_add_fileformat(fileformat))\n\t\tc = TRUE;\n#ifdef FEAT_CRYPT\n\t if (cryptkey != NULL)\n\t\tmsg_add_lines(c, (long)linecnt, filesize\n\t\t\t - crypt_get_header_len(crypt_get_method_nr(curbuf)));\n\t else\n#endif\n\t\tmsg_add_lines(c, (long)linecnt, filesize);\n\n\t vim_free(keep_msg);\n\t keep_msg = NULL;\n\t msg_scrolled_ign = TRUE;\n#ifdef ALWAYS_USE_GUI\n\t /* Don't show the message when reading stdin, it would end up in a\n\t * message box (which might be shown when exiting!) */\n\t if (read_stdin || read_buffer)\n\t\tp = msg_may_trunc(FALSE, IObuff);\n\t else\n#endif\n\t\tp = msg_trunc_attr(IObuff, FALSE, 0);\n\t if (read_stdin || read_buffer || restart_edit != 0\n\t\t || (msg_scrolled != 0 && !need_wait_return))\n\t\t/* Need to repeat the message after redrawing when:\n\t\t * - When reading from stdin (the screen will be cleared next).\n\t\t * - When restart_edit is set (otherwise there will be a delay\n\t\t * before redrawing).\n\t\t * - When the screen was scrolled but there is no wait-return\n\t\t * prompt. */\n\t\tset_keep_msg(p, 0);\n\t msg_scrolled_ign = FALSE;\n\t}\n\n\t/* with errors writing the file requires \":w!\" */\n\tif (newfile && (error\n#ifdef FEAT_MBYTE\n\t\t || conv_error != 0\n\t\t || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)\n#endif\n\t\t ))\n\t curbuf->b_p_ro = TRUE;\n\n\tu_clearline();\t /* cannot use \"U\" command after adding lines */\n\n\t/*\n\t * In Ex mode: cursor at last new line.\n\t * Otherwise: cursor at first new line.\n\t */\n\tif (exmode_active)\n\t curwin->w_cursor.lnum = from + linecnt;\n\telse\n\t curwin->w_cursor.lnum = from + 1;\n\tcheck_cursor_lnum();\n\tbeginline(BL_WHITE | BL_FIX);\t /* on first non-blank */\n\n\t/*\n\t * Set '[ and '] marks to the newly read lines.\n\t */\n\tcurbuf->b_op_start.lnum = from + 1;\n\tcurbuf->b_op_start.col = 0;\n\tcurbuf->b_op_end.lnum = from + linecnt;\n\tcurbuf->b_op_end.col = 0;\n\n#ifdef WIN32\n\t/*\n\t * Work around a weird problem: When a file has two links (only\n\t * possible on NTFS) and we write through one link, then stat() it\n\t * through the other link, the timestamp information may be wrong.\n\t * It's correct again after reading the file, thus reset the timestamp\n\t * here.\n\t */\n\tif (newfile && !read_stdin && !read_buffer\n\t\t\t\t\t && mch_stat((char *)fname, &st) >= 0)\n\t{\n\t buf_store_time(curbuf, &st, fname);\n\t curbuf->b_mtime_read = curbuf->b_mtime;\n\t}\n#endif\n }\n msg_scroll = msg_save;\n\n#ifdef FEAT_VIMINFO\n /*\n * Get the marks before executing autocommands, so they can be used there.\n */\n check_marks_read();\n#endif\n\n /*\n * We remember if the last line of the read didn't have\n * an eol even when 'binary' is off, to support turning 'fixeol' off,\n * or writing the read again with 'binary' on. The latter is required\n * for \":autocmd FileReadPost *.gz set bin|'[,']!gunzip\" to work.\n */\n curbuf->b_no_eol_lnum = read_no_eol_lnum;\n\n /* When reloading a buffer put the cursor at the first line that is\n * different. */\n if (flags & READ_KEEP_UNDO)\n\tu_find_first_changed();\n\n#ifdef FEAT_PERSISTENT_UNDO\n /*\n * When opening a new file locate undo info and read it.\n */\n if (read_undo_file)\n {\n\tchar_u\thash[UNDO_HASH_SIZE];\n\n\tsha256_finish(&sha_ctx, hash);\n\tu_read_undo(NULL, hash, fname);\n }\n#endif\n\n#ifdef FEAT_AUTOCMD\n if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))\n {\n\tint m = msg_scroll;\n\tint n = msg_scrolled;\n\n\t/* Save the fileformat now, otherwise the buffer will be considered\n\t * modified if the format/encoding was automatically detected. */\n\tif (set_options)\n\t save_file_ff(curbuf);\n\n\t/*\n\t * The output from the autocommands should not overwrite anything and\n\t * should not be overwritten: Set msg_scroll, restore its value if no\n\t * output was done.\n\t */\n\tmsg_scroll = TRUE;\n\tif (filtering)\n\t apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\telse if (newfile || (read_buffer && sfname != NULL))\n\t{\n\t apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,\n\t\t\t\t\t\t\t FALSE, curbuf, eap);\n\t if (!au_did_filetype && *curbuf->b_p_ft != NUL)\n\t\t/*\n\t\t * EVENT_FILETYPE was not triggered but the buffer already has a\n\t\t * filetype. Trigger EVENT_FILETYPE using the existing filetype.\n\t\t */\n\t\tapply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,\n\t\t\tTRUE, curbuf);\n\t}\n\telse\n\t apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,\n\t\t\t\t\t\t\t FALSE, NULL, eap);\n\tif (msg_scrolled == n)\n\t msg_scroll = m;\n# ifdef FEAT_EVAL\n\tif (aborting())\t /* autocmds may abort script processing */\n\t return FAIL;\n# endif\n }\n#endif\n\n if (recoverymode && error)\n\treturn FAIL;\n return OK;\n}", "project": "vim", "hash": 253046681285963764072266830667800150363, "size": 2538, "commit_id": "5a73e0ca54c77e067c3b12ea6f35e3e8681e8cf8", "message": "patch 8.0.1263: others can read the swap file if a user is careless\n\nProblem: Others can read the swap file if a user is careless with his\n primary group.\nSolution: If the group permission allows for reading but the world\n permissions doesn't, make sure the group is right.", "target": 0, "dataset": "other", "idx": 460737}
  941. {"func": "static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image,\n\t\t int oldproglen, struct jit_context *ctx, bool jmp_padding)\n{\n\tbool tail_call_reachable = bpf_prog->aux->tail_call_reachable;\n\tstruct bpf_insn *insn = bpf_prog->insnsi;\n\tbool callee_regs_used[4] = {};\n\tint insn_cnt = bpf_prog->len;\n\tbool tail_call_seen = false;\n\tbool seen_exit = false;\n\tu8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY];\n\tint i, cnt = 0, excnt = 0;\n\tint ilen, proglen = 0;\n\tu8 *prog = temp;\n\tint err;\n\n\tdetect_reg_usage(insn, insn_cnt, callee_regs_used,\n\t\t\t &tail_call_seen);\n\n\t/* tail call's presence in current prog implies it is reachable */\n\ttail_call_reachable |= tail_call_seen;\n\n\temit_prologue(&prog, bpf_prog->aux->stack_depth,\n\t\t bpf_prog_was_classic(bpf_prog), tail_call_reachable,\n\t\t bpf_prog->aux->func_idx != 0);\n\tpush_callee_regs(&prog, callee_regs_used);\n\n\tilen = prog - temp;\n\tif (image)\n\t\tmemcpy(image + proglen, temp, ilen);\n\tproglen += ilen;\n\taddrs[0] = proglen;\n\tprog = temp;\n\n\tfor (i = 1; i <= insn_cnt; i++, insn++) {\n\t\tconst s32 imm32 = insn->imm;\n\t\tu32 dst_reg = insn->dst_reg;\n\t\tu32 src_reg = insn->src_reg;\n\t\tu8 b2 = 0, b3 = 0;\n\t\tu8 *start_of_ldx;\n\t\ts64 jmp_offset;\n\t\tu8 jmp_cond;\n\t\tu8 *func;\n\t\tint nops;\n\n\t\tswitch (insn->code) {\n\t\t\t/* ALU */\n\t\tcase BPF_ALU | BPF_ADD | BPF_X:\n\t\tcase BPF_ALU | BPF_SUB | BPF_X:\n\t\tcase BPF_ALU | BPF_AND | BPF_X:\n\t\tcase BPF_ALU | BPF_OR | BPF_X:\n\t\tcase BPF_ALU | BPF_XOR | BPF_X:\n\t\tcase BPF_ALU64 | BPF_ADD | BPF_X:\n\t\tcase BPF_ALU64 | BPF_SUB | BPF_X:\n\t\tcase BPF_ALU64 | BPF_AND | BPF_X:\n\t\tcase BPF_ALU64 | BPF_OR | BPF_X:\n\t\tcase BPF_ALU64 | BPF_XOR | BPF_X:\n\t\t\tmaybe_emit_mod(&prog, dst_reg, src_reg,\n\t\t\t\t BPF_CLASS(insn->code) == BPF_ALU64);\n\t\t\tb2 = simple_alu_opcodes[BPF_OP(insn->code)];\n\t\t\tEMIT2(b2, add_2reg(0xC0, dst_reg, src_reg));\n\t\t\tbreak;\n\n\t\tcase BPF_ALU64 | BPF_MOV | BPF_X:\n\t\tcase BPF_ALU | BPF_MOV | BPF_X:\n\t\t\temit_mov_reg(&prog,\n\t\t\t\t BPF_CLASS(insn->code) == BPF_ALU64,\n\t\t\t\t dst_reg, src_reg);\n\t\t\tbreak;\n\n\t\t\t/* neg dst */\n\t\tcase BPF_ALU | BPF_NEG:\n\t\tcase BPF_ALU64 | BPF_NEG:\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\t\t\tEMIT2(0xF7, add_1reg(0xD8, dst_reg));\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_ADD | BPF_K:\n\t\tcase BPF_ALU | BPF_SUB | BPF_K:\n\t\tcase BPF_ALU | BPF_AND | BPF_K:\n\t\tcase BPF_ALU | BPF_OR | BPF_K:\n\t\tcase BPF_ALU | BPF_XOR | BPF_K:\n\t\tcase BPF_ALU64 | BPF_ADD | BPF_K:\n\t\tcase BPF_ALU64 | BPF_SUB | BPF_K:\n\t\tcase BPF_ALU64 | BPF_AND | BPF_K:\n\t\tcase BPF_ALU64 | BPF_OR | BPF_K:\n\t\tcase BPF_ALU64 | BPF_XOR | BPF_K:\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\n\t\t\t/*\n\t\t\t * b3 holds 'normal' opcode, b2 short form only valid\n\t\t\t * in case dst is eax/rax.\n\t\t\t */\n\t\t\tswitch (BPF_OP(insn->code)) {\n\t\t\tcase BPF_ADD:\n\t\t\t\tb3 = 0xC0;\n\t\t\t\tb2 = 0x05;\n\t\t\t\tbreak;\n\t\t\tcase BPF_SUB:\n\t\t\t\tb3 = 0xE8;\n\t\t\t\tb2 = 0x2D;\n\t\t\t\tbreak;\n\t\t\tcase BPF_AND:\n\t\t\t\tb3 = 0xE0;\n\t\t\t\tb2 = 0x25;\n\t\t\t\tbreak;\n\t\t\tcase BPF_OR:\n\t\t\t\tb3 = 0xC8;\n\t\t\t\tb2 = 0x0D;\n\t\t\t\tbreak;\n\t\t\tcase BPF_XOR:\n\t\t\t\tb3 = 0xF0;\n\t\t\t\tb2 = 0x35;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (is_imm8(imm32))\n\t\t\t\tEMIT3(0x83, add_1reg(b3, dst_reg), imm32);\n\t\t\telse if (is_axreg(dst_reg))\n\t\t\t\tEMIT1_off32(b2, imm32);\n\t\t\telse\n\t\t\t\tEMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32);\n\t\t\tbreak;\n\n\t\tcase BPF_ALU64 | BPF_MOV | BPF_K:\n\t\tcase BPF_ALU | BPF_MOV | BPF_K:\n\t\t\temit_mov_imm32(&prog, BPF_CLASS(insn->code) == BPF_ALU64,\n\t\t\t\t dst_reg, imm32);\n\t\t\tbreak;\n\n\t\tcase BPF_LD | BPF_IMM | BPF_DW:\n\t\t\temit_mov_imm64(&prog, dst_reg, insn[1].imm, insn[0].imm);\n\t\t\tinsn++;\n\t\t\ti++;\n\t\t\tbreak;\n\n\t\t\t/* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */\n\t\tcase BPF_ALU | BPF_MOD | BPF_X:\n\t\tcase BPF_ALU | BPF_DIV | BPF_X:\n\t\tcase BPF_ALU | BPF_MOD | BPF_K:\n\t\tcase BPF_ALU | BPF_DIV | BPF_K:\n\t\tcase BPF_ALU64 | BPF_MOD | BPF_X:\n\t\tcase BPF_ALU64 | BPF_DIV | BPF_X:\n\t\tcase BPF_ALU64 | BPF_MOD | BPF_K:\n\t\tcase BPF_ALU64 | BPF_DIV | BPF_K:\n\t\t\tEMIT1(0x50); /* push rax */\n\t\t\tEMIT1(0x52); /* push rdx */\n\n\t\t\tif (BPF_SRC(insn->code) == BPF_X)\n\t\t\t\t/* mov r11, src_reg */\n\t\t\t\tEMIT_mov(AUX_REG, src_reg);\n\t\t\telse\n\t\t\t\t/* mov r11, imm32 */\n\t\t\t\tEMIT3_off32(0x49, 0xC7, 0xC3, imm32);\n\n\t\t\t/* mov rax, dst_reg */\n\t\t\tEMIT_mov(BPF_REG_0, dst_reg);\n\n\t\t\t/*\n\t\t\t * xor edx, edx\n\t\t\t * equivalent to 'xor rdx, rdx', but one byte less\n\t\t\t */\n\t\t\tEMIT2(0x31, 0xd2);\n\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\t/* div r11 */\n\t\t\t\tEMIT3(0x49, 0xF7, 0xF3);\n\t\t\telse\n\t\t\t\t/* div r11d */\n\t\t\t\tEMIT3(0x41, 0xF7, 0xF3);\n\n\t\t\tif (BPF_OP(insn->code) == BPF_MOD)\n\t\t\t\t/* mov r11, rdx */\n\t\t\t\tEMIT3(0x49, 0x89, 0xD3);\n\t\t\telse\n\t\t\t\t/* mov r11, rax */\n\t\t\t\tEMIT3(0x49, 0x89, 0xC3);\n\n\t\t\tEMIT1(0x5A); /* pop rdx */\n\t\t\tEMIT1(0x58); /* pop rax */\n\n\t\t\t/* mov dst_reg, r11 */\n\t\t\tEMIT_mov(dst_reg, AUX_REG);\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_MUL | BPF_K:\n\t\tcase BPF_ALU | BPF_MUL | BPF_X:\n\t\tcase BPF_ALU64 | BPF_MUL | BPF_K:\n\t\tcase BPF_ALU64 | BPF_MUL | BPF_X:\n\t\t{\n\t\t\tbool is64 = BPF_CLASS(insn->code) == BPF_ALU64;\n\n\t\t\tif (dst_reg != BPF_REG_0)\n\t\t\t\tEMIT1(0x50); /* push rax */\n\t\t\tif (dst_reg != BPF_REG_3)\n\t\t\t\tEMIT1(0x52); /* push rdx */\n\n\t\t\t/* mov r11, dst_reg */\n\t\t\tEMIT_mov(AUX_REG, dst_reg);\n\n\t\t\tif (BPF_SRC(insn->code) == BPF_X)\n\t\t\t\temit_mov_reg(&prog, is64, BPF_REG_0, src_reg);\n\t\t\telse\n\t\t\t\temit_mov_imm32(&prog, is64, BPF_REG_0, imm32);\n\n\t\t\tif (is64)\n\t\t\t\tEMIT1(add_1mod(0x48, AUX_REG));\n\t\t\telse if (is_ereg(AUX_REG))\n\t\t\t\tEMIT1(add_1mod(0x40, AUX_REG));\n\t\t\t/* mul(q) r11 */\n\t\t\tEMIT2(0xF7, add_1reg(0xE0, AUX_REG));\n\n\t\t\tif (dst_reg != BPF_REG_3)\n\t\t\t\tEMIT1(0x5A); /* pop rdx */\n\t\t\tif (dst_reg != BPF_REG_0) {\n\t\t\t\t/* mov dst_reg, rax */\n\t\t\t\tEMIT_mov(dst_reg, BPF_REG_0);\n\t\t\t\tEMIT1(0x58); /* pop rax */\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\t/* Shifts */\n\t\tcase BPF_ALU | BPF_LSH | BPF_K:\n\t\tcase BPF_ALU | BPF_RSH | BPF_K:\n\t\tcase BPF_ALU | BPF_ARSH | BPF_K:\n\t\tcase BPF_ALU64 | BPF_LSH | BPF_K:\n\t\tcase BPF_ALU64 | BPF_RSH | BPF_K:\n\t\tcase BPF_ALU64 | BPF_ARSH | BPF_K:\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\n\t\t\tb3 = simple_alu_opcodes[BPF_OP(insn->code)];\n\t\t\tif (imm32 == 1)\n\t\t\t\tEMIT2(0xD1, add_1reg(b3, dst_reg));\n\t\t\telse\n\t\t\t\tEMIT3(0xC1, add_1reg(b3, dst_reg), imm32);\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_LSH | BPF_X:\n\t\tcase BPF_ALU | BPF_RSH | BPF_X:\n\t\tcase BPF_ALU | BPF_ARSH | BPF_X:\n\t\tcase BPF_ALU64 | BPF_LSH | BPF_X:\n\t\tcase BPF_ALU64 | BPF_RSH | BPF_X:\n\t\tcase BPF_ALU64 | BPF_ARSH | BPF_X:\n\n\t\t\t/* Check for bad case when dst_reg == rcx */\n\t\t\tif (dst_reg == BPF_REG_4) {\n\t\t\t\t/* mov r11, dst_reg */\n\t\t\t\tEMIT_mov(AUX_REG, dst_reg);\n\t\t\t\tdst_reg = AUX_REG;\n\t\t\t}\n\n\t\t\tif (src_reg != BPF_REG_4) { /* common case */\n\t\t\t\tEMIT1(0x51); /* push rcx */\n\n\t\t\t\t/* mov rcx, src_reg */\n\t\t\t\tEMIT_mov(BPF_REG_4, src_reg);\n\t\t\t}\n\n\t\t\t/* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\n\t\t\tb3 = simple_alu_opcodes[BPF_OP(insn->code)];\n\t\t\tEMIT2(0xD3, add_1reg(b3, dst_reg));\n\n\t\t\tif (src_reg != BPF_REG_4)\n\t\t\t\tEMIT1(0x59); /* pop rcx */\n\n\t\t\tif (insn->dst_reg == BPF_REG_4)\n\t\t\t\t/* mov dst_reg, r11 */\n\t\t\t\tEMIT_mov(insn->dst_reg, AUX_REG);\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_END | BPF_FROM_BE:\n\t\t\tswitch (imm32) {\n\t\t\tcase 16:\n\t\t\t\t/* Emit 'ror %ax, 8' to swap lower 2 bytes */\n\t\t\t\tEMIT1(0x66);\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT1(0x41);\n\t\t\t\tEMIT3(0xC1, add_1reg(0xC8, dst_reg), 8);\n\n\t\t\t\t/* Emit 'movzwl eax, ax' */\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT3(0x45, 0x0F, 0xB7);\n\t\t\t\telse\n\t\t\t\t\tEMIT2(0x0F, 0xB7);\n\t\t\t\tEMIT1(add_2reg(0xC0, dst_reg, dst_reg));\n\t\t\t\tbreak;\n\t\t\tcase 32:\n\t\t\t\t/* Emit 'bswap eax' to swap lower 4 bytes */\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT2(0x41, 0x0F);\n\t\t\t\telse\n\t\t\t\t\tEMIT1(0x0F);\n\t\t\t\tEMIT1(add_1reg(0xC8, dst_reg));\n\t\t\t\tbreak;\n\t\t\tcase 64:\n\t\t\t\t/* Emit 'bswap rax' to swap 8 bytes */\n\t\t\t\tEMIT3(add_1mod(0x48, dst_reg), 0x0F,\n\t\t\t\t add_1reg(0xC8, dst_reg));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_END | BPF_FROM_LE:\n\t\t\tswitch (imm32) {\n\t\t\tcase 16:\n\t\t\t\t/*\n\t\t\t\t * Emit 'movzwl eax, ax' to zero extend 16-bit\n\t\t\t\t * into 64 bit\n\t\t\t\t */\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT3(0x45, 0x0F, 0xB7);\n\t\t\t\telse\n\t\t\t\t\tEMIT2(0x0F, 0xB7);\n\t\t\t\tEMIT1(add_2reg(0xC0, dst_reg, dst_reg));\n\t\t\t\tbreak;\n\t\t\tcase 32:\n\t\t\t\t/* Emit 'mov eax, eax' to clear upper 32-bits */\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT1(0x45);\n\t\t\t\tEMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg));\n\t\t\t\tbreak;\n\t\t\tcase 64:\n\t\t\t\t/* nop */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\t/* ST: *(u8*)(dst_reg + off) = imm */\n\t\tcase BPF_ST | BPF_MEM | BPF_B:\n\t\t\tif (is_ereg(dst_reg))\n\t\t\t\tEMIT2(0x41, 0xC6);\n\t\t\telse\n\t\t\t\tEMIT1(0xC6);\n\t\t\tgoto st;\n\t\tcase BPF_ST | BPF_MEM | BPF_H:\n\t\t\tif (is_ereg(dst_reg))\n\t\t\t\tEMIT3(0x66, 0x41, 0xC7);\n\t\t\telse\n\t\t\t\tEMIT2(0x66, 0xC7);\n\t\t\tgoto st;\n\t\tcase BPF_ST | BPF_MEM | BPF_W:\n\t\t\tif (is_ereg(dst_reg))\n\t\t\t\tEMIT2(0x41, 0xC7);\n\t\t\telse\n\t\t\t\tEMIT1(0xC7);\n\t\t\tgoto st;\n\t\tcase BPF_ST | BPF_MEM | BPF_DW:\n\t\t\tEMIT2(add_1mod(0x48, dst_reg), 0xC7);\n\nst:\t\t\tif (is_imm8(insn->off))\n\t\t\t\tEMIT2(add_1reg(0x40, dst_reg), insn->off);\n\t\t\telse\n\t\t\t\tEMIT1_off32(add_1reg(0x80, dst_reg), insn->off);\n\n\t\t\tEMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code)));\n\t\t\tbreak;\n\n\t\t\t/* STX: *(u8*)(dst_reg + off) = src_reg */\n\t\tcase BPF_STX | BPF_MEM | BPF_B:\n\t\tcase BPF_STX | BPF_MEM | BPF_H:\n\t\tcase BPF_STX | BPF_MEM | BPF_W:\n\t\tcase BPF_STX | BPF_MEM | BPF_DW:\n\t\t\temit_stx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);\n\t\t\tbreak;\n\n\t\t\t/* LDX: dst_reg = *(u8*)(src_reg + off) */\n\t\tcase BPF_LDX | BPF_MEM | BPF_B:\n\t\tcase BPF_LDX | BPF_PROBE_MEM | BPF_B:\n\t\tcase BPF_LDX | BPF_MEM | BPF_H:\n\t\tcase BPF_LDX | BPF_PROBE_MEM | BPF_H:\n\t\tcase BPF_LDX | BPF_MEM | BPF_W:\n\t\tcase BPF_LDX | BPF_PROBE_MEM | BPF_W:\n\t\tcase BPF_LDX | BPF_MEM | BPF_DW:\n\t\tcase BPF_LDX | BPF_PROBE_MEM | BPF_DW:\n\t\t\tif (BPF_MODE(insn->code) == BPF_PROBE_MEM) {\n\t\t\t\t/* test src_reg, src_reg */\n\t\t\t\tmaybe_emit_mod(&prog, src_reg, src_reg, true); /* always 1 byte */\n\t\t\t\tEMIT2(0x85, add_2reg(0xC0, src_reg, src_reg));\n\t\t\t\t/* jne start_of_ldx */\n\t\t\t\tEMIT2(X86_JNE, 0);\n\t\t\t\t/* xor dst_reg, dst_reg */\n\t\t\t\temit_mov_imm32(&prog, false, dst_reg, 0);\n\t\t\t\t/* jmp byte_after_ldx */\n\t\t\t\tEMIT2(0xEB, 0);\n\n\t\t\t\t/* populate jmp_offset for JNE above */\n\t\t\t\ttemp[4] = prog - temp - 5 /* sizeof(test + jne) */;\n\t\t\t\tstart_of_ldx = prog;\n\t\t\t}\n\t\t\temit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);\n\t\t\tif (BPF_MODE(insn->code) == BPF_PROBE_MEM) {\n\t\t\t\tstruct exception_table_entry *ex;\n\t\t\t\tu8 *_insn = image + proglen;\n\t\t\t\ts64 delta;\n\n\t\t\t\t/* populate jmp_offset for JMP above */\n\t\t\t\tstart_of_ldx[-1] = prog - start_of_ldx;\n\n\t\t\t\tif (!bpf_prog->aux->extable)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif (excnt >= bpf_prog->aux->num_exentries) {\n\t\t\t\t\tpr_err(\"ex gen bug\\n\");\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\tex = &bpf_prog->aux->extable[excnt++];\n\n\t\t\t\tdelta = _insn - (u8 *)&ex->insn;\n\t\t\t\tif (!is_simm32(delta)) {\n\t\t\t\t\tpr_err(\"extable->insn doesn't fit into 32-bit\\n\");\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\tex->insn = delta;\n\n\t\t\t\tdelta = (u8 *)ex_handler_bpf - (u8 *)&ex->handler;\n\t\t\t\tif (!is_simm32(delta)) {\n\t\t\t\t\tpr_err(\"extable->handler doesn't fit into 32-bit\\n\");\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\tex->handler = delta;\n\n\t\t\t\tif (dst_reg > BPF_REG_9) {\n\t\t\t\t\tpr_err(\"verifier error\\n\");\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Compute size of x86 insn and its target dest x86 register.\n\t\t\t\t * ex_handler_bpf() will use lower 8 bits to adjust\n\t\t\t\t * pt_regs->ip to jump over this x86 instruction\n\t\t\t\t * and upper bits to figure out which pt_regs to zero out.\n\t\t\t\t * End result: x86 insn \"mov rbx, qword ptr [rax+0x14]\"\n\t\t\t\t * of 4 bytes will be ignored and rbx will be zero inited.\n\t\t\t\t */\n\t\t\t\tex->fixup = (prog - temp) | (reg2pt_regs[dst_reg] << 8);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BPF_STX | BPF_ATOMIC | BPF_W:\n\t\tcase BPF_STX | BPF_ATOMIC | BPF_DW:\n\t\t\tif (insn->imm == (BPF_AND | BPF_FETCH) ||\n\t\t\t insn->imm == (BPF_OR | BPF_FETCH) ||\n\t\t\t insn->imm == (BPF_XOR | BPF_FETCH)) {\n\t\t\t\tu8 *branch_target;\n\t\t\t\tbool is64 = BPF_SIZE(insn->code) == BPF_DW;\n\t\t\t\tu32 real_src_reg = src_reg;\n\n\t\t\t\t/*\n\t\t\t\t * Can't be implemented with a single x86 insn.\n\t\t\t\t * Need to do a CMPXCHG loop.\n\t\t\t\t */\n\n\t\t\t\t/* Will need RAX as a CMPXCHG operand so save R0 */\n\t\t\t\temit_mov_reg(&prog, true, BPF_REG_AX, BPF_REG_0);\n\t\t\t\tif (src_reg == BPF_REG_0)\n\t\t\t\t\treal_src_reg = BPF_REG_AX;\n\n\t\t\t\tbranch_target = prog;\n\t\t\t\t/* Load old value */\n\t\t\t\temit_ldx(&prog, BPF_SIZE(insn->code),\n\t\t\t\t\t BPF_REG_0, dst_reg, insn->off);\n\t\t\t\t/*\n\t\t\t\t * Perform the (commutative) operation locally,\n\t\t\t\t * put the result in the AUX_REG.\n\t\t\t\t */\n\t\t\t\temit_mov_reg(&prog, is64, AUX_REG, BPF_REG_0);\n\t\t\t\tmaybe_emit_mod(&prog, AUX_REG, real_src_reg, is64);\n\t\t\t\tEMIT2(simple_alu_opcodes[BPF_OP(insn->imm)],\n\t\t\t\t add_2reg(0xC0, AUX_REG, real_src_reg));\n\t\t\t\t/* Attempt to swap in new value */\n\t\t\t\terr = emit_atomic(&prog, BPF_CMPXCHG,\n\t\t\t\t\t\t dst_reg, AUX_REG, insn->off,\n\t\t\t\t\t\t BPF_SIZE(insn->code));\n\t\t\t\tif (WARN_ON(err))\n\t\t\t\t\treturn err;\n\t\t\t\t/*\n\t\t\t\t * ZF tells us whether we won the race. If it's\n\t\t\t\t * cleared we need to try again.\n\t\t\t\t */\n\t\t\t\tEMIT2(X86_JNE, -(prog - branch_target) - 2);\n\t\t\t\t/* Return the pre-modification value */\n\t\t\t\temit_mov_reg(&prog, is64, real_src_reg, BPF_REG_0);\n\t\t\t\t/* Restore R0 after clobbering RAX */\n\t\t\t\temit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_AX);\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\terr = emit_atomic(&prog, insn->imm, dst_reg, src_reg,\n\t\t\t\t\t\t insn->off, BPF_SIZE(insn->code));\n\t\t\tif (err)\n\t\t\t\treturn err;\n\t\t\tbreak;\n\n\t\t\t/* call */\n\t\tcase BPF_JMP | BPF_CALL:\n\t\t\tfunc = (u8 *) __bpf_call_base + imm32;\n\t\t\tif (tail_call_reachable) {\n\t\t\t\tEMIT3_off32(0x48, 0x8B, 0x85,\n\t\t\t\t\t -(bpf_prog->aux->stack_depth + 8));\n\t\t\t\tif (!imm32 || emit_call(&prog, func, image + addrs[i - 1] + 7))\n\t\t\t\t\treturn -EINVAL;\n\t\t\t} else {\n\t\t\t\tif (!imm32 || emit_call(&prog, func, image + addrs[i - 1]))\n\t\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BPF_JMP | BPF_TAIL_CALL:\n\t\t\tif (imm32)\n\t\t\t\temit_bpf_tail_call_direct(&bpf_prog->aux->poke_tab[imm32 - 1],\n\t\t\t\t\t\t\t &prog, addrs[i], image,\n\t\t\t\t\t\t\t callee_regs_used,\n\t\t\t\t\t\t\t bpf_prog->aux->stack_depth);\n\t\t\telse\n\t\t\t\temit_bpf_tail_call_indirect(&prog,\n\t\t\t\t\t\t\t callee_regs_used,\n\t\t\t\t\t\t\t bpf_prog->aux->stack_depth);\n\t\t\tbreak;\n\n\t\t\t/* cond jump */\n\t\tcase BPF_JMP | BPF_JEQ | BPF_X:\n\t\tcase BPF_JMP | BPF_JNE | BPF_X:\n\t\tcase BPF_JMP | BPF_JGT | BPF_X:\n\t\tcase BPF_JMP | BPF_JLT | BPF_X:\n\t\tcase BPF_JMP | BPF_JGE | BPF_X:\n\t\tcase BPF_JMP | BPF_JLE | BPF_X:\n\t\tcase BPF_JMP | BPF_JSGT | BPF_X:\n\t\tcase BPF_JMP | BPF_JSLT | BPF_X:\n\t\tcase BPF_JMP | BPF_JSGE | BPF_X:\n\t\tcase BPF_JMP | BPF_JSLE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JEQ | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JNE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JGT | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JLT | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JGE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JLE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSGT | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSLT | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSGE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSLE | BPF_X:\n\t\t\t/* cmp dst_reg, src_reg */\n\t\t\tmaybe_emit_mod(&prog, dst_reg, src_reg,\n\t\t\t\t BPF_CLASS(insn->code) == BPF_JMP);\n\t\t\tEMIT2(0x39, add_2reg(0xC0, dst_reg, src_reg));\n\t\t\tgoto emit_cond_jmp;\n\n\t\tcase BPF_JMP | BPF_JSET | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSET | BPF_X:\n\t\t\t/* test dst_reg, src_reg */\n\t\t\tmaybe_emit_mod(&prog, dst_reg, src_reg,\n\t\t\t\t BPF_CLASS(insn->code) == BPF_JMP);\n\t\t\tEMIT2(0x85, add_2reg(0xC0, dst_reg, src_reg));\n\t\t\tgoto emit_cond_jmp;\n\n\t\tcase BPF_JMP | BPF_JSET | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSET | BPF_K:\n\t\t\t/* test dst_reg, imm32 */\n\t\t\tif (BPF_CLASS(insn->code) == BPF_JMP)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\t\t\tEMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);\n\t\t\tgoto emit_cond_jmp;\n\n\t\tcase BPF_JMP | BPF_JEQ | BPF_K:\n\t\tcase BPF_JMP | BPF_JNE | BPF_K:\n\t\tcase BPF_JMP | BPF_JGT | BPF_K:\n\t\tcase BPF_JMP | BPF_JLT | BPF_K:\n\t\tcase BPF_JMP | BPF_JGE | BPF_K:\n\t\tcase BPF_JMP | BPF_JLE | BPF_K:\n\t\tcase BPF_JMP | BPF_JSGT | BPF_K:\n\t\tcase BPF_JMP | BPF_JSLT | BPF_K:\n\t\tcase BPF_JMP | BPF_JSGE | BPF_K:\n\t\tcase BPF_JMP | BPF_JSLE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JEQ | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JNE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JGT | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JLT | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JGE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JLE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSGT | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSLT | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSGE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSLE | BPF_K:\n\t\t\t/* test dst_reg, dst_reg to save one extra byte */\n\t\t\tif (imm32 == 0) {\n\t\t\t\tmaybe_emit_mod(&prog, dst_reg, dst_reg,\n\t\t\t\t\t BPF_CLASS(insn->code) == BPF_JMP);\n\t\t\t\tEMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));\n\t\t\t\tgoto emit_cond_jmp;\n\t\t\t}\n\n\t\t\t/* cmp dst_reg, imm8/32 */\n\t\t\tif (BPF_CLASS(insn->code) == BPF_JMP)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\n\t\t\tif (is_imm8(imm32))\n\t\t\t\tEMIT3(0x83, add_1reg(0xF8, dst_reg), imm32);\n\t\t\telse\n\t\t\t\tEMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32);\n\nemit_cond_jmp:\t\t/* Convert BPF opcode to x86 */\n\t\t\tswitch (BPF_OP(insn->code)) {\n\t\t\tcase BPF_JEQ:\n\t\t\t\tjmp_cond = X86_JE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSET:\n\t\t\tcase BPF_JNE:\n\t\t\t\tjmp_cond = X86_JNE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JGT:\n\t\t\t\t/* GT is unsigned '>', JA in x86 */\n\t\t\t\tjmp_cond = X86_JA;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JLT:\n\t\t\t\t/* LT is unsigned '<', JB in x86 */\n\t\t\t\tjmp_cond = X86_JB;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JGE:\n\t\t\t\t/* GE is unsigned '>=', JAE in x86 */\n\t\t\t\tjmp_cond = X86_JAE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JLE:\n\t\t\t\t/* LE is unsigned '<=', JBE in x86 */\n\t\t\t\tjmp_cond = X86_JBE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSGT:\n\t\t\t\t/* Signed '>', GT in x86 */\n\t\t\t\tjmp_cond = X86_JG;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSLT:\n\t\t\t\t/* Signed '<', LT in x86 */\n\t\t\t\tjmp_cond = X86_JL;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSGE:\n\t\t\t\t/* Signed '>=', GE in x86 */\n\t\t\t\tjmp_cond = X86_JGE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSLE:\n\t\t\t\t/* Signed '<=', LE in x86 */\n\t\t\t\tjmp_cond = X86_JLE;\n\t\t\t\tbreak;\n\t\t\tdefault: /* to silence GCC warning */\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\tjmp_offset = addrs[i + insn->off] - addrs[i];\n\t\t\tif (is_imm8(jmp_offset)) {\n\t\t\t\tif (jmp_padding) {\n\t\t\t\t\t/* To keep the jmp_offset valid, the extra bytes are\n\t\t\t\t\t * padded before the jump insn, so we substract the\n\t\t\t\t\t * 2 bytes of jmp_cond insn from INSN_SZ_DIFF.\n\t\t\t\t\t *\n\t\t\t\t\t * If the previous pass already emits an imm8\n\t\t\t\t\t * jmp_cond, then this BPF insn won't shrink, so\n\t\t\t\t\t * \"nops\" is 0.\n\t\t\t\t\t *\n\t\t\t\t\t * On the other hand, if the previous pass emits an\n\t\t\t\t\t * imm32 jmp_cond, the extra 4 bytes(*) is padded to\n\t\t\t\t\t * keep the image from shrinking further.\n\t\t\t\t\t *\n\t\t\t\t\t * (*) imm32 jmp_cond is 6 bytes, and imm8 jmp_cond\n\t\t\t\t\t * is 2 bytes, so the size difference is 4 bytes.\n\t\t\t\t\t */\n\t\t\t\t\tnops = INSN_SZ_DIFF - 2;\n\t\t\t\t\tif (nops != 0 && nops != 4) {\n\t\t\t\t\t\tpr_err(\"unexpected jmp_cond padding: %d bytes\\n\",\n\t\t\t\t\t\t nops);\n\t\t\t\t\t\treturn -EFAULT;\n\t\t\t\t\t}\n\t\t\t\t\tcnt += emit_nops(&prog, nops);\n\t\t\t\t}\n\t\t\t\tEMIT2(jmp_cond, jmp_offset);\n\t\t\t} else if (is_simm32(jmp_offset)) {\n\t\t\t\tEMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset);\n\t\t\t} else {\n\t\t\t\tpr_err(\"cond_jmp gen bug %llx\\n\", jmp_offset);\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase BPF_JMP | BPF_JA:\n\t\t\tif (insn->off == -1)\n\t\t\t\t/* -1 jmp instructions will always jump\n\t\t\t\t * backwards two bytes. Explicitly handling\n\t\t\t\t * this case avoids wasting too many passes\n\t\t\t\t * when there are long sequences of replaced\n\t\t\t\t * dead code.\n\t\t\t\t */\n\t\t\t\tjmp_offset = -2;\n\t\t\telse\n\t\t\t\tjmp_offset = addrs[i + insn->off] - addrs[i];\n\n\t\t\tif (!jmp_offset) {\n\t\t\t\t/*\n\t\t\t\t * If jmp_padding is enabled, the extra nops will\n\t\t\t\t * be inserted. Otherwise, optimize out nop jumps.\n\t\t\t\t */\n\t\t\t\tif (jmp_padding) {\n\t\t\t\t\t/* There are 3 possible conditions.\n\t\t\t\t\t * (1) This BPF_JA is already optimized out in\n\t\t\t\t\t * the previous run, so there is no need\n\t\t\t\t\t * to pad any extra byte (0 byte).\n\t\t\t\t\t * (2) The previous pass emits an imm8 jmp,\n\t\t\t\t\t * so we pad 2 bytes to match the previous\n\t\t\t\t\t * insn size.\n\t\t\t\t\t * (3) Similarly, the previous pass emits an\n\t\t\t\t\t * imm32 jmp, and 5 bytes is padded.\n\t\t\t\t\t */\n\t\t\t\t\tnops = INSN_SZ_DIFF;\n\t\t\t\t\tif (nops != 0 && nops != 2 && nops != 5) {\n\t\t\t\t\t\tpr_err(\"unexpected nop jump padding: %d bytes\\n\",\n\t\t\t\t\t\t nops);\n\t\t\t\t\t\treturn -EFAULT;\n\t\t\t\t\t}\n\t\t\t\t\tcnt += emit_nops(&prog, nops);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\nemit_jmp:\n\t\t\tif (is_imm8(jmp_offset)) {\n\t\t\t\tif (jmp_padding) {\n\t\t\t\t\t/* To avoid breaking jmp_offset, the extra bytes\n\t\t\t\t\t * are padded before the actual jmp insn, so\n\t\t\t\t\t * 2 bytes is substracted from INSN_SZ_DIFF.\n\t\t\t\t\t *\n\t\t\t\t\t * If the previous pass already emits an imm8\n\t\t\t\t\t * jmp, there is nothing to pad (0 byte).\n\t\t\t\t\t *\n\t\t\t\t\t * If it emits an imm32 jmp (5 bytes) previously\n\t\t\t\t\t * and now an imm8 jmp (2 bytes), then we pad\n\t\t\t\t\t * (5 - 2 = 3) bytes to stop the image from\n\t\t\t\t\t * shrinking further.\n\t\t\t\t\t */\n\t\t\t\t\tnops = INSN_SZ_DIFF - 2;\n\t\t\t\t\tif (nops != 0 && nops != 3) {\n\t\t\t\t\t\tpr_err(\"unexpected jump padding: %d bytes\\n\",\n\t\t\t\t\t\t nops);\n\t\t\t\t\t\treturn -EFAULT;\n\t\t\t\t\t}\n\t\t\t\t\tcnt += emit_nops(&prog, INSN_SZ_DIFF - 2);\n\t\t\t\t}\n\t\t\t\tEMIT2(0xEB, jmp_offset);\n\t\t\t} else if (is_simm32(jmp_offset)) {\n\t\t\t\tEMIT1_off32(0xE9, jmp_offset);\n\t\t\t} else {\n\t\t\t\tpr_err(\"jmp gen bug %llx\\n\", jmp_offset);\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BPF_JMP | BPF_EXIT:\n\t\t\tif (seen_exit) {\n\t\t\t\tjmp_offset = ctx->cleanup_addr - addrs[i];\n\t\t\t\tgoto emit_jmp;\n\t\t\t}\n\t\t\tseen_exit = true;\n\t\t\t/* Update cleanup_addr */\n\t\t\tctx->cleanup_addr = proglen;\n\t\t\tpop_callee_regs(&prog, callee_regs_used);\n\t\t\tEMIT1(0xC9); /* leave */\n\t\t\tEMIT1(0xC3); /* ret */\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/*\n\t\t\t * By design x86-64 JIT should support all BPF instructions.\n\t\t\t * This error will be seen if new instruction was added\n\t\t\t * to the interpreter, but not to the JIT, or if there is\n\t\t\t * junk in bpf_prog.\n\t\t\t */\n\t\t\tpr_err(\"bpf_jit: unknown opcode %02x\\n\", insn->code);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tilen = prog - temp;\n\t\tif (ilen > BPF_MAX_INSN_SIZE) {\n\t\t\tpr_err(\"bpf_jit: fatal insn size error\\n\");\n\t\t\treturn -EFAULT;\n\t\t}\n\n\t\tif (image) {\n\t\t\tif (unlikely(proglen + ilen > oldproglen)) {\n\t\t\t\tpr_err(\"bpf_jit: fatal error\\n\");\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\tmemcpy(image + proglen, temp, ilen);\n\t\t}\n\t\tproglen += ilen;\n\t\taddrs[i] = proglen;\n\t\tprog = temp;\n\t}\n\n\tif (image && excnt != bpf_prog->aux->num_exentries) {\n\t\tpr_err(\"extable is not populated\\n\");\n\t\treturn -EFAULT;\n\t}\n\treturn proglen;\n}", "project": "linux", "hash": 176161434758084402194530235503098784254, "size": 814, "commit_id": "e4d4d456436bfb2fe412ee2cd489f7658449b098", "message": "bpf, x86: Validate computation of branch displacements for x86-64\n\nThe branch displacement logic in the BPF JIT compilers for x86 assumes\nthat, for any generated branch instruction, the distance cannot\nincrease between optimization passes.\n\nBut this assumption can be violated due to how the distances are\ncomputed. Specifically, whenever a backward branch is processed in\ndo_jit(), the distance is computed by subtracting the positions in the\nmachine code from different optimization passes. This is because part\nof addrs[] is already updated for the current optimization pass, before\nthe branch instruction is visited.\n\nAnd so the optimizer can expand blocks of machine code in some cases.\n\nThis can confuse the optimizer logic, where it assumes that a fixed\npoint has been reached for all machine code blocks once the total\nprogram size stops changing. And then the JIT compiler can output\nabnormal machine code containing incorrect branch displacements.\n\nTo mitigate this issue, we assert that a fixed point is reached while\npopulating the output image. This rejects any problematic programs.\nThe issue affects both x86-32 and x86-64. We mitigate separately to\nease backporting.\n\nSigned-off-by: Piotr Krysiuk <piotras@gmail.com>\nReviewed-by: Daniel Borkmann <daniel@iogearbox.net>\nSigned-off-by: Daniel Borkmann <daniel@iogearbox.net>", "target": 1, "dataset": "other", "idx": 212767}
  942. {"func": "static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image,\n\t\t int oldproglen, struct jit_context *ctx, bool jmp_padding)\n{\n\tbool tail_call_reachable = bpf_prog->aux->tail_call_reachable;\n\tstruct bpf_insn *insn = bpf_prog->insnsi;\n\tbool callee_regs_used[4] = {};\n\tint insn_cnt = bpf_prog->len;\n\tbool tail_call_seen = false;\n\tbool seen_exit = false;\n\tu8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY];\n\tint i, cnt = 0, excnt = 0;\n\tint ilen, proglen = 0;\n\tu8 *prog = temp;\n\tint err;\n\n\tdetect_reg_usage(insn, insn_cnt, callee_regs_used,\n\t\t\t &tail_call_seen);\n\n\t/* tail call's presence in current prog implies it is reachable */\n\ttail_call_reachable |= tail_call_seen;\n\n\temit_prologue(&prog, bpf_prog->aux->stack_depth,\n\t\t bpf_prog_was_classic(bpf_prog), tail_call_reachable,\n\t\t bpf_prog->aux->func_idx != 0);\n\tpush_callee_regs(&prog, callee_regs_used);\n\n\tilen = prog - temp;\n\tif (image)\n\t\tmemcpy(image + proglen, temp, ilen);\n\tproglen += ilen;\n\taddrs[0] = proglen;\n\tprog = temp;\n\n\tfor (i = 1; i <= insn_cnt; i++, insn++) {\n\t\tconst s32 imm32 = insn->imm;\n\t\tu32 dst_reg = insn->dst_reg;\n\t\tu32 src_reg = insn->src_reg;\n\t\tu8 b2 = 0, b3 = 0;\n\t\tu8 *start_of_ldx;\n\t\ts64 jmp_offset;\n\t\tu8 jmp_cond;\n\t\tu8 *func;\n\t\tint nops;\n\n\t\tswitch (insn->code) {\n\t\t\t/* ALU */\n\t\tcase BPF_ALU | BPF_ADD | BPF_X:\n\t\tcase BPF_ALU | BPF_SUB | BPF_X:\n\t\tcase BPF_ALU | BPF_AND | BPF_X:\n\t\tcase BPF_ALU | BPF_OR | BPF_X:\n\t\tcase BPF_ALU | BPF_XOR | BPF_X:\n\t\tcase BPF_ALU64 | BPF_ADD | BPF_X:\n\t\tcase BPF_ALU64 | BPF_SUB | BPF_X:\n\t\tcase BPF_ALU64 | BPF_AND | BPF_X:\n\t\tcase BPF_ALU64 | BPF_OR | BPF_X:\n\t\tcase BPF_ALU64 | BPF_XOR | BPF_X:\n\t\t\tmaybe_emit_mod(&prog, dst_reg, src_reg,\n\t\t\t\t BPF_CLASS(insn->code) == BPF_ALU64);\n\t\t\tb2 = simple_alu_opcodes[BPF_OP(insn->code)];\n\t\t\tEMIT2(b2, add_2reg(0xC0, dst_reg, src_reg));\n\t\t\tbreak;\n\n\t\tcase BPF_ALU64 | BPF_MOV | BPF_X:\n\t\tcase BPF_ALU | BPF_MOV | BPF_X:\n\t\t\temit_mov_reg(&prog,\n\t\t\t\t BPF_CLASS(insn->code) == BPF_ALU64,\n\t\t\t\t dst_reg, src_reg);\n\t\t\tbreak;\n\n\t\t\t/* neg dst */\n\t\tcase BPF_ALU | BPF_NEG:\n\t\tcase BPF_ALU64 | BPF_NEG:\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\t\t\tEMIT2(0xF7, add_1reg(0xD8, dst_reg));\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_ADD | BPF_K:\n\t\tcase BPF_ALU | BPF_SUB | BPF_K:\n\t\tcase BPF_ALU | BPF_AND | BPF_K:\n\t\tcase BPF_ALU | BPF_OR | BPF_K:\n\t\tcase BPF_ALU | BPF_XOR | BPF_K:\n\t\tcase BPF_ALU64 | BPF_ADD | BPF_K:\n\t\tcase BPF_ALU64 | BPF_SUB | BPF_K:\n\t\tcase BPF_ALU64 | BPF_AND | BPF_K:\n\t\tcase BPF_ALU64 | BPF_OR | BPF_K:\n\t\tcase BPF_ALU64 | BPF_XOR | BPF_K:\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\n\t\t\t/*\n\t\t\t * b3 holds 'normal' opcode, b2 short form only valid\n\t\t\t * in case dst is eax/rax.\n\t\t\t */\n\t\t\tswitch (BPF_OP(insn->code)) {\n\t\t\tcase BPF_ADD:\n\t\t\t\tb3 = 0xC0;\n\t\t\t\tb2 = 0x05;\n\t\t\t\tbreak;\n\t\t\tcase BPF_SUB:\n\t\t\t\tb3 = 0xE8;\n\t\t\t\tb2 = 0x2D;\n\t\t\t\tbreak;\n\t\t\tcase BPF_AND:\n\t\t\t\tb3 = 0xE0;\n\t\t\t\tb2 = 0x25;\n\t\t\t\tbreak;\n\t\t\tcase BPF_OR:\n\t\t\t\tb3 = 0xC8;\n\t\t\t\tb2 = 0x0D;\n\t\t\t\tbreak;\n\t\t\tcase BPF_XOR:\n\t\t\t\tb3 = 0xF0;\n\t\t\t\tb2 = 0x35;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (is_imm8(imm32))\n\t\t\t\tEMIT3(0x83, add_1reg(b3, dst_reg), imm32);\n\t\t\telse if (is_axreg(dst_reg))\n\t\t\t\tEMIT1_off32(b2, imm32);\n\t\t\telse\n\t\t\t\tEMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32);\n\t\t\tbreak;\n\n\t\tcase BPF_ALU64 | BPF_MOV | BPF_K:\n\t\tcase BPF_ALU | BPF_MOV | BPF_K:\n\t\t\temit_mov_imm32(&prog, BPF_CLASS(insn->code) == BPF_ALU64,\n\t\t\t\t dst_reg, imm32);\n\t\t\tbreak;\n\n\t\tcase BPF_LD | BPF_IMM | BPF_DW:\n\t\t\temit_mov_imm64(&prog, dst_reg, insn[1].imm, insn[0].imm);\n\t\t\tinsn++;\n\t\t\ti++;\n\t\t\tbreak;\n\n\t\t\t/* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */\n\t\tcase BPF_ALU | BPF_MOD | BPF_X:\n\t\tcase BPF_ALU | BPF_DIV | BPF_X:\n\t\tcase BPF_ALU | BPF_MOD | BPF_K:\n\t\tcase BPF_ALU | BPF_DIV | BPF_K:\n\t\tcase BPF_ALU64 | BPF_MOD | BPF_X:\n\t\tcase BPF_ALU64 | BPF_DIV | BPF_X:\n\t\tcase BPF_ALU64 | BPF_MOD | BPF_K:\n\t\tcase BPF_ALU64 | BPF_DIV | BPF_K:\n\t\t\tEMIT1(0x50); /* push rax */\n\t\t\tEMIT1(0x52); /* push rdx */\n\n\t\t\tif (BPF_SRC(insn->code) == BPF_X)\n\t\t\t\t/* mov r11, src_reg */\n\t\t\t\tEMIT_mov(AUX_REG, src_reg);\n\t\t\telse\n\t\t\t\t/* mov r11, imm32 */\n\t\t\t\tEMIT3_off32(0x49, 0xC7, 0xC3, imm32);\n\n\t\t\t/* mov rax, dst_reg */\n\t\t\tEMIT_mov(BPF_REG_0, dst_reg);\n\n\t\t\t/*\n\t\t\t * xor edx, edx\n\t\t\t * equivalent to 'xor rdx, rdx', but one byte less\n\t\t\t */\n\t\t\tEMIT2(0x31, 0xd2);\n\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\t/* div r11 */\n\t\t\t\tEMIT3(0x49, 0xF7, 0xF3);\n\t\t\telse\n\t\t\t\t/* div r11d */\n\t\t\t\tEMIT3(0x41, 0xF7, 0xF3);\n\n\t\t\tif (BPF_OP(insn->code) == BPF_MOD)\n\t\t\t\t/* mov r11, rdx */\n\t\t\t\tEMIT3(0x49, 0x89, 0xD3);\n\t\t\telse\n\t\t\t\t/* mov r11, rax */\n\t\t\t\tEMIT3(0x49, 0x89, 0xC3);\n\n\t\t\tEMIT1(0x5A); /* pop rdx */\n\t\t\tEMIT1(0x58); /* pop rax */\n\n\t\t\t/* mov dst_reg, r11 */\n\t\t\tEMIT_mov(dst_reg, AUX_REG);\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_MUL | BPF_K:\n\t\tcase BPF_ALU | BPF_MUL | BPF_X:\n\t\tcase BPF_ALU64 | BPF_MUL | BPF_K:\n\t\tcase BPF_ALU64 | BPF_MUL | BPF_X:\n\t\t{\n\t\t\tbool is64 = BPF_CLASS(insn->code) == BPF_ALU64;\n\n\t\t\tif (dst_reg != BPF_REG_0)\n\t\t\t\tEMIT1(0x50); /* push rax */\n\t\t\tif (dst_reg != BPF_REG_3)\n\t\t\t\tEMIT1(0x52); /* push rdx */\n\n\t\t\t/* mov r11, dst_reg */\n\t\t\tEMIT_mov(AUX_REG, dst_reg);\n\n\t\t\tif (BPF_SRC(insn->code) == BPF_X)\n\t\t\t\temit_mov_reg(&prog, is64, BPF_REG_0, src_reg);\n\t\t\telse\n\t\t\t\temit_mov_imm32(&prog, is64, BPF_REG_0, imm32);\n\n\t\t\tif (is64)\n\t\t\t\tEMIT1(add_1mod(0x48, AUX_REG));\n\t\t\telse if (is_ereg(AUX_REG))\n\t\t\t\tEMIT1(add_1mod(0x40, AUX_REG));\n\t\t\t/* mul(q) r11 */\n\t\t\tEMIT2(0xF7, add_1reg(0xE0, AUX_REG));\n\n\t\t\tif (dst_reg != BPF_REG_3)\n\t\t\t\tEMIT1(0x5A); /* pop rdx */\n\t\t\tif (dst_reg != BPF_REG_0) {\n\t\t\t\t/* mov dst_reg, rax */\n\t\t\t\tEMIT_mov(dst_reg, BPF_REG_0);\n\t\t\t\tEMIT1(0x58); /* pop rax */\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t\t/* Shifts */\n\t\tcase BPF_ALU | BPF_LSH | BPF_K:\n\t\tcase BPF_ALU | BPF_RSH | BPF_K:\n\t\tcase BPF_ALU | BPF_ARSH | BPF_K:\n\t\tcase BPF_ALU64 | BPF_LSH | BPF_K:\n\t\tcase BPF_ALU64 | BPF_RSH | BPF_K:\n\t\tcase BPF_ALU64 | BPF_ARSH | BPF_K:\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\n\t\t\tb3 = simple_alu_opcodes[BPF_OP(insn->code)];\n\t\t\tif (imm32 == 1)\n\t\t\t\tEMIT2(0xD1, add_1reg(b3, dst_reg));\n\t\t\telse\n\t\t\t\tEMIT3(0xC1, add_1reg(b3, dst_reg), imm32);\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_LSH | BPF_X:\n\t\tcase BPF_ALU | BPF_RSH | BPF_X:\n\t\tcase BPF_ALU | BPF_ARSH | BPF_X:\n\t\tcase BPF_ALU64 | BPF_LSH | BPF_X:\n\t\tcase BPF_ALU64 | BPF_RSH | BPF_X:\n\t\tcase BPF_ALU64 | BPF_ARSH | BPF_X:\n\n\t\t\t/* Check for bad case when dst_reg == rcx */\n\t\t\tif (dst_reg == BPF_REG_4) {\n\t\t\t\t/* mov r11, dst_reg */\n\t\t\t\tEMIT_mov(AUX_REG, dst_reg);\n\t\t\t\tdst_reg = AUX_REG;\n\t\t\t}\n\n\t\t\tif (src_reg != BPF_REG_4) { /* common case */\n\t\t\t\tEMIT1(0x51); /* push rcx */\n\n\t\t\t\t/* mov rcx, src_reg */\n\t\t\t\tEMIT_mov(BPF_REG_4, src_reg);\n\t\t\t}\n\n\t\t\t/* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */\n\t\t\tif (BPF_CLASS(insn->code) == BPF_ALU64)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\n\t\t\tb3 = simple_alu_opcodes[BPF_OP(insn->code)];\n\t\t\tEMIT2(0xD3, add_1reg(b3, dst_reg));\n\n\t\t\tif (src_reg != BPF_REG_4)\n\t\t\t\tEMIT1(0x59); /* pop rcx */\n\n\t\t\tif (insn->dst_reg == BPF_REG_4)\n\t\t\t\t/* mov dst_reg, r11 */\n\t\t\t\tEMIT_mov(insn->dst_reg, AUX_REG);\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_END | BPF_FROM_BE:\n\t\t\tswitch (imm32) {\n\t\t\tcase 16:\n\t\t\t\t/* Emit 'ror %ax, 8' to swap lower 2 bytes */\n\t\t\t\tEMIT1(0x66);\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT1(0x41);\n\t\t\t\tEMIT3(0xC1, add_1reg(0xC8, dst_reg), 8);\n\n\t\t\t\t/* Emit 'movzwl eax, ax' */\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT3(0x45, 0x0F, 0xB7);\n\t\t\t\telse\n\t\t\t\t\tEMIT2(0x0F, 0xB7);\n\t\t\t\tEMIT1(add_2reg(0xC0, dst_reg, dst_reg));\n\t\t\t\tbreak;\n\t\t\tcase 32:\n\t\t\t\t/* Emit 'bswap eax' to swap lower 4 bytes */\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT2(0x41, 0x0F);\n\t\t\t\telse\n\t\t\t\t\tEMIT1(0x0F);\n\t\t\t\tEMIT1(add_1reg(0xC8, dst_reg));\n\t\t\t\tbreak;\n\t\t\tcase 64:\n\t\t\t\t/* Emit 'bswap rax' to swap 8 bytes */\n\t\t\t\tEMIT3(add_1mod(0x48, dst_reg), 0x0F,\n\t\t\t\t add_1reg(0xC8, dst_reg));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BPF_ALU | BPF_END | BPF_FROM_LE:\n\t\t\tswitch (imm32) {\n\t\t\tcase 16:\n\t\t\t\t/*\n\t\t\t\t * Emit 'movzwl eax, ax' to zero extend 16-bit\n\t\t\t\t * into 64 bit\n\t\t\t\t */\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT3(0x45, 0x0F, 0xB7);\n\t\t\t\telse\n\t\t\t\t\tEMIT2(0x0F, 0xB7);\n\t\t\t\tEMIT1(add_2reg(0xC0, dst_reg, dst_reg));\n\t\t\t\tbreak;\n\t\t\tcase 32:\n\t\t\t\t/* Emit 'mov eax, eax' to clear upper 32-bits */\n\t\t\t\tif (is_ereg(dst_reg))\n\t\t\t\t\tEMIT1(0x45);\n\t\t\t\tEMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg));\n\t\t\t\tbreak;\n\t\t\tcase 64:\n\t\t\t\t/* nop */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\t/* ST: *(u8*)(dst_reg + off) = imm */\n\t\tcase BPF_ST | BPF_MEM | BPF_B:\n\t\t\tif (is_ereg(dst_reg))\n\t\t\t\tEMIT2(0x41, 0xC6);\n\t\t\telse\n\t\t\t\tEMIT1(0xC6);\n\t\t\tgoto st;\n\t\tcase BPF_ST | BPF_MEM | BPF_H:\n\t\t\tif (is_ereg(dst_reg))\n\t\t\t\tEMIT3(0x66, 0x41, 0xC7);\n\t\t\telse\n\t\t\t\tEMIT2(0x66, 0xC7);\n\t\t\tgoto st;\n\t\tcase BPF_ST | BPF_MEM | BPF_W:\n\t\t\tif (is_ereg(dst_reg))\n\t\t\t\tEMIT2(0x41, 0xC7);\n\t\t\telse\n\t\t\t\tEMIT1(0xC7);\n\t\t\tgoto st;\n\t\tcase BPF_ST | BPF_MEM | BPF_DW:\n\t\t\tEMIT2(add_1mod(0x48, dst_reg), 0xC7);\n\nst:\t\t\tif (is_imm8(insn->off))\n\t\t\t\tEMIT2(add_1reg(0x40, dst_reg), insn->off);\n\t\t\telse\n\t\t\t\tEMIT1_off32(add_1reg(0x80, dst_reg), insn->off);\n\n\t\t\tEMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code)));\n\t\t\tbreak;\n\n\t\t\t/* STX: *(u8*)(dst_reg + off) = src_reg */\n\t\tcase BPF_STX | BPF_MEM | BPF_B:\n\t\tcase BPF_STX | BPF_MEM | BPF_H:\n\t\tcase BPF_STX | BPF_MEM | BPF_W:\n\t\tcase BPF_STX | BPF_MEM | BPF_DW:\n\t\t\temit_stx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);\n\t\t\tbreak;\n\n\t\t\t/* LDX: dst_reg = *(u8*)(src_reg + off) */\n\t\tcase BPF_LDX | BPF_MEM | BPF_B:\n\t\tcase BPF_LDX | BPF_PROBE_MEM | BPF_B:\n\t\tcase BPF_LDX | BPF_MEM | BPF_H:\n\t\tcase BPF_LDX | BPF_PROBE_MEM | BPF_H:\n\t\tcase BPF_LDX | BPF_MEM | BPF_W:\n\t\tcase BPF_LDX | BPF_PROBE_MEM | BPF_W:\n\t\tcase BPF_LDX | BPF_MEM | BPF_DW:\n\t\tcase BPF_LDX | BPF_PROBE_MEM | BPF_DW:\n\t\t\tif (BPF_MODE(insn->code) == BPF_PROBE_MEM) {\n\t\t\t\t/* test src_reg, src_reg */\n\t\t\t\tmaybe_emit_mod(&prog, src_reg, src_reg, true); /* always 1 byte */\n\t\t\t\tEMIT2(0x85, add_2reg(0xC0, src_reg, src_reg));\n\t\t\t\t/* jne start_of_ldx */\n\t\t\t\tEMIT2(X86_JNE, 0);\n\t\t\t\t/* xor dst_reg, dst_reg */\n\t\t\t\temit_mov_imm32(&prog, false, dst_reg, 0);\n\t\t\t\t/* jmp byte_after_ldx */\n\t\t\t\tEMIT2(0xEB, 0);\n\n\t\t\t\t/* populate jmp_offset for JNE above */\n\t\t\t\ttemp[4] = prog - temp - 5 /* sizeof(test + jne) */;\n\t\t\t\tstart_of_ldx = prog;\n\t\t\t}\n\t\t\temit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);\n\t\t\tif (BPF_MODE(insn->code) == BPF_PROBE_MEM) {\n\t\t\t\tstruct exception_table_entry *ex;\n\t\t\t\tu8 *_insn = image + proglen;\n\t\t\t\ts64 delta;\n\n\t\t\t\t/* populate jmp_offset for JMP above */\n\t\t\t\tstart_of_ldx[-1] = prog - start_of_ldx;\n\n\t\t\t\tif (!bpf_prog->aux->extable)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif (excnt >= bpf_prog->aux->num_exentries) {\n\t\t\t\t\tpr_err(\"ex gen bug\\n\");\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\tex = &bpf_prog->aux->extable[excnt++];\n\n\t\t\t\tdelta = _insn - (u8 *)&ex->insn;\n\t\t\t\tif (!is_simm32(delta)) {\n\t\t\t\t\tpr_err(\"extable->insn doesn't fit into 32-bit\\n\");\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\tex->insn = delta;\n\n\t\t\t\tdelta = (u8 *)ex_handler_bpf - (u8 *)&ex->handler;\n\t\t\t\tif (!is_simm32(delta)) {\n\t\t\t\t\tpr_err(\"extable->handler doesn't fit into 32-bit\\n\");\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\tex->handler = delta;\n\n\t\t\t\tif (dst_reg > BPF_REG_9) {\n\t\t\t\t\tpr_err(\"verifier error\\n\");\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Compute size of x86 insn and its target dest x86 register.\n\t\t\t\t * ex_handler_bpf() will use lower 8 bits to adjust\n\t\t\t\t * pt_regs->ip to jump over this x86 instruction\n\t\t\t\t * and upper bits to figure out which pt_regs to zero out.\n\t\t\t\t * End result: x86 insn \"mov rbx, qword ptr [rax+0x14]\"\n\t\t\t\t * of 4 bytes will be ignored and rbx will be zero inited.\n\t\t\t\t */\n\t\t\t\tex->fixup = (prog - temp) | (reg2pt_regs[dst_reg] << 8);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BPF_STX | BPF_ATOMIC | BPF_W:\n\t\tcase BPF_STX | BPF_ATOMIC | BPF_DW:\n\t\t\tif (insn->imm == (BPF_AND | BPF_FETCH) ||\n\t\t\t insn->imm == (BPF_OR | BPF_FETCH) ||\n\t\t\t insn->imm == (BPF_XOR | BPF_FETCH)) {\n\t\t\t\tu8 *branch_target;\n\t\t\t\tbool is64 = BPF_SIZE(insn->code) == BPF_DW;\n\t\t\t\tu32 real_src_reg = src_reg;\n\n\t\t\t\t/*\n\t\t\t\t * Can't be implemented with a single x86 insn.\n\t\t\t\t * Need to do a CMPXCHG loop.\n\t\t\t\t */\n\n\t\t\t\t/* Will need RAX as a CMPXCHG operand so save R0 */\n\t\t\t\temit_mov_reg(&prog, true, BPF_REG_AX, BPF_REG_0);\n\t\t\t\tif (src_reg == BPF_REG_0)\n\t\t\t\t\treal_src_reg = BPF_REG_AX;\n\n\t\t\t\tbranch_target = prog;\n\t\t\t\t/* Load old value */\n\t\t\t\temit_ldx(&prog, BPF_SIZE(insn->code),\n\t\t\t\t\t BPF_REG_0, dst_reg, insn->off);\n\t\t\t\t/*\n\t\t\t\t * Perform the (commutative) operation locally,\n\t\t\t\t * put the result in the AUX_REG.\n\t\t\t\t */\n\t\t\t\temit_mov_reg(&prog, is64, AUX_REG, BPF_REG_0);\n\t\t\t\tmaybe_emit_mod(&prog, AUX_REG, real_src_reg, is64);\n\t\t\t\tEMIT2(simple_alu_opcodes[BPF_OP(insn->imm)],\n\t\t\t\t add_2reg(0xC0, AUX_REG, real_src_reg));\n\t\t\t\t/* Attempt to swap in new value */\n\t\t\t\terr = emit_atomic(&prog, BPF_CMPXCHG,\n\t\t\t\t\t\t dst_reg, AUX_REG, insn->off,\n\t\t\t\t\t\t BPF_SIZE(insn->code));\n\t\t\t\tif (WARN_ON(err))\n\t\t\t\t\treturn err;\n\t\t\t\t/*\n\t\t\t\t * ZF tells us whether we won the race. If it's\n\t\t\t\t * cleared we need to try again.\n\t\t\t\t */\n\t\t\t\tEMIT2(X86_JNE, -(prog - branch_target) - 2);\n\t\t\t\t/* Return the pre-modification value */\n\t\t\t\temit_mov_reg(&prog, is64, real_src_reg, BPF_REG_0);\n\t\t\t\t/* Restore R0 after clobbering RAX */\n\t\t\t\temit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_AX);\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\terr = emit_atomic(&prog, insn->imm, dst_reg, src_reg,\n\t\t\t\t\t\t insn->off, BPF_SIZE(insn->code));\n\t\t\tif (err)\n\t\t\t\treturn err;\n\t\t\tbreak;\n\n\t\t\t/* call */\n\t\tcase BPF_JMP | BPF_CALL:\n\t\t\tfunc = (u8 *) __bpf_call_base + imm32;\n\t\t\tif (tail_call_reachable) {\n\t\t\t\tEMIT3_off32(0x48, 0x8B, 0x85,\n\t\t\t\t\t -(bpf_prog->aux->stack_depth + 8));\n\t\t\t\tif (!imm32 || emit_call(&prog, func, image + addrs[i - 1] + 7))\n\t\t\t\t\treturn -EINVAL;\n\t\t\t} else {\n\t\t\t\tif (!imm32 || emit_call(&prog, func, image + addrs[i - 1]))\n\t\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BPF_JMP | BPF_TAIL_CALL:\n\t\t\tif (imm32)\n\t\t\t\temit_bpf_tail_call_direct(&bpf_prog->aux->poke_tab[imm32 - 1],\n\t\t\t\t\t\t\t &prog, addrs[i], image,\n\t\t\t\t\t\t\t callee_regs_used,\n\t\t\t\t\t\t\t bpf_prog->aux->stack_depth);\n\t\t\telse\n\t\t\t\temit_bpf_tail_call_indirect(&prog,\n\t\t\t\t\t\t\t callee_regs_used,\n\t\t\t\t\t\t\t bpf_prog->aux->stack_depth);\n\t\t\tbreak;\n\n\t\t\t/* cond jump */\n\t\tcase BPF_JMP | BPF_JEQ | BPF_X:\n\t\tcase BPF_JMP | BPF_JNE | BPF_X:\n\t\tcase BPF_JMP | BPF_JGT | BPF_X:\n\t\tcase BPF_JMP | BPF_JLT | BPF_X:\n\t\tcase BPF_JMP | BPF_JGE | BPF_X:\n\t\tcase BPF_JMP | BPF_JLE | BPF_X:\n\t\tcase BPF_JMP | BPF_JSGT | BPF_X:\n\t\tcase BPF_JMP | BPF_JSLT | BPF_X:\n\t\tcase BPF_JMP | BPF_JSGE | BPF_X:\n\t\tcase BPF_JMP | BPF_JSLE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JEQ | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JNE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JGT | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JLT | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JGE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JLE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSGT | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSLT | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSGE | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSLE | BPF_X:\n\t\t\t/* cmp dst_reg, src_reg */\n\t\t\tmaybe_emit_mod(&prog, dst_reg, src_reg,\n\t\t\t\t BPF_CLASS(insn->code) == BPF_JMP);\n\t\t\tEMIT2(0x39, add_2reg(0xC0, dst_reg, src_reg));\n\t\t\tgoto emit_cond_jmp;\n\n\t\tcase BPF_JMP | BPF_JSET | BPF_X:\n\t\tcase BPF_JMP32 | BPF_JSET | BPF_X:\n\t\t\t/* test dst_reg, src_reg */\n\t\t\tmaybe_emit_mod(&prog, dst_reg, src_reg,\n\t\t\t\t BPF_CLASS(insn->code) == BPF_JMP);\n\t\t\tEMIT2(0x85, add_2reg(0xC0, dst_reg, src_reg));\n\t\t\tgoto emit_cond_jmp;\n\n\t\tcase BPF_JMP | BPF_JSET | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSET | BPF_K:\n\t\t\t/* test dst_reg, imm32 */\n\t\t\tif (BPF_CLASS(insn->code) == BPF_JMP)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\t\t\tEMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);\n\t\t\tgoto emit_cond_jmp;\n\n\t\tcase BPF_JMP | BPF_JEQ | BPF_K:\n\t\tcase BPF_JMP | BPF_JNE | BPF_K:\n\t\tcase BPF_JMP | BPF_JGT | BPF_K:\n\t\tcase BPF_JMP | BPF_JLT | BPF_K:\n\t\tcase BPF_JMP | BPF_JGE | BPF_K:\n\t\tcase BPF_JMP | BPF_JLE | BPF_K:\n\t\tcase BPF_JMP | BPF_JSGT | BPF_K:\n\t\tcase BPF_JMP | BPF_JSLT | BPF_K:\n\t\tcase BPF_JMP | BPF_JSGE | BPF_K:\n\t\tcase BPF_JMP | BPF_JSLE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JEQ | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JNE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JGT | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JLT | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JGE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JLE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSGT | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSLT | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSGE | BPF_K:\n\t\tcase BPF_JMP32 | BPF_JSLE | BPF_K:\n\t\t\t/* test dst_reg, dst_reg to save one extra byte */\n\t\t\tif (imm32 == 0) {\n\t\t\t\tmaybe_emit_mod(&prog, dst_reg, dst_reg,\n\t\t\t\t\t BPF_CLASS(insn->code) == BPF_JMP);\n\t\t\t\tEMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));\n\t\t\t\tgoto emit_cond_jmp;\n\t\t\t}\n\n\t\t\t/* cmp dst_reg, imm8/32 */\n\t\t\tif (BPF_CLASS(insn->code) == BPF_JMP)\n\t\t\t\tEMIT1(add_1mod(0x48, dst_reg));\n\t\t\telse if (is_ereg(dst_reg))\n\t\t\t\tEMIT1(add_1mod(0x40, dst_reg));\n\n\t\t\tif (is_imm8(imm32))\n\t\t\t\tEMIT3(0x83, add_1reg(0xF8, dst_reg), imm32);\n\t\t\telse\n\t\t\t\tEMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32);\n\nemit_cond_jmp:\t\t/* Convert BPF opcode to x86 */\n\t\t\tswitch (BPF_OP(insn->code)) {\n\t\t\tcase BPF_JEQ:\n\t\t\t\tjmp_cond = X86_JE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSET:\n\t\t\tcase BPF_JNE:\n\t\t\t\tjmp_cond = X86_JNE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JGT:\n\t\t\t\t/* GT is unsigned '>', JA in x86 */\n\t\t\t\tjmp_cond = X86_JA;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JLT:\n\t\t\t\t/* LT is unsigned '<', JB in x86 */\n\t\t\t\tjmp_cond = X86_JB;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JGE:\n\t\t\t\t/* GE is unsigned '>=', JAE in x86 */\n\t\t\t\tjmp_cond = X86_JAE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JLE:\n\t\t\t\t/* LE is unsigned '<=', JBE in x86 */\n\t\t\t\tjmp_cond = X86_JBE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSGT:\n\t\t\t\t/* Signed '>', GT in x86 */\n\t\t\t\tjmp_cond = X86_JG;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSLT:\n\t\t\t\t/* Signed '<', LT in x86 */\n\t\t\t\tjmp_cond = X86_JL;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSGE:\n\t\t\t\t/* Signed '>=', GE in x86 */\n\t\t\t\tjmp_cond = X86_JGE;\n\t\t\t\tbreak;\n\t\t\tcase BPF_JSLE:\n\t\t\t\t/* Signed '<=', LE in x86 */\n\t\t\t\tjmp_cond = X86_JLE;\n\t\t\t\tbreak;\n\t\t\tdefault: /* to silence GCC warning */\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\tjmp_offset = addrs[i + insn->off] - addrs[i];\n\t\t\tif (is_imm8(jmp_offset)) {\n\t\t\t\tif (jmp_padding) {\n\t\t\t\t\t/* To keep the jmp_offset valid, the extra bytes are\n\t\t\t\t\t * padded before the jump insn, so we substract the\n\t\t\t\t\t * 2 bytes of jmp_cond insn from INSN_SZ_DIFF.\n\t\t\t\t\t *\n\t\t\t\t\t * If the previous pass already emits an imm8\n\t\t\t\t\t * jmp_cond, then this BPF insn won't shrink, so\n\t\t\t\t\t * \"nops\" is 0.\n\t\t\t\t\t *\n\t\t\t\t\t * On the other hand, if the previous pass emits an\n\t\t\t\t\t * imm32 jmp_cond, the extra 4 bytes(*) is padded to\n\t\t\t\t\t * keep the image from shrinking further.\n\t\t\t\t\t *\n\t\t\t\t\t * (*) imm32 jmp_cond is 6 bytes, and imm8 jmp_cond\n\t\t\t\t\t * is 2 bytes, so the size difference is 4 bytes.\n\t\t\t\t\t */\n\t\t\t\t\tnops = INSN_SZ_DIFF - 2;\n\t\t\t\t\tif (nops != 0 && nops != 4) {\n\t\t\t\t\t\tpr_err(\"unexpected jmp_cond padding: %d bytes\\n\",\n\t\t\t\t\t\t nops);\n\t\t\t\t\t\treturn -EFAULT;\n\t\t\t\t\t}\n\t\t\t\t\tcnt += emit_nops(&prog, nops);\n\t\t\t\t}\n\t\t\t\tEMIT2(jmp_cond, jmp_offset);\n\t\t\t} else if (is_simm32(jmp_offset)) {\n\t\t\t\tEMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset);\n\t\t\t} else {\n\t\t\t\tpr_err(\"cond_jmp gen bug %llx\\n\", jmp_offset);\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase BPF_JMP | BPF_JA:\n\t\t\tif (insn->off == -1)\n\t\t\t\t/* -1 jmp instructions will always jump\n\t\t\t\t * backwards two bytes. Explicitly handling\n\t\t\t\t * this case avoids wasting too many passes\n\t\t\t\t * when there are long sequences of replaced\n\t\t\t\t * dead code.\n\t\t\t\t */\n\t\t\t\tjmp_offset = -2;\n\t\t\telse\n\t\t\t\tjmp_offset = addrs[i + insn->off] - addrs[i];\n\n\t\t\tif (!jmp_offset) {\n\t\t\t\t/*\n\t\t\t\t * If jmp_padding is enabled, the extra nops will\n\t\t\t\t * be inserted. Otherwise, optimize out nop jumps.\n\t\t\t\t */\n\t\t\t\tif (jmp_padding) {\n\t\t\t\t\t/* There are 3 possible conditions.\n\t\t\t\t\t * (1) This BPF_JA is already optimized out in\n\t\t\t\t\t * the previous run, so there is no need\n\t\t\t\t\t * to pad any extra byte (0 byte).\n\t\t\t\t\t * (2) The previous pass emits an imm8 jmp,\n\t\t\t\t\t * so we pad 2 bytes to match the previous\n\t\t\t\t\t * insn size.\n\t\t\t\t\t * (3) Similarly, the previous pass emits an\n\t\t\t\t\t * imm32 jmp, and 5 bytes is padded.\n\t\t\t\t\t */\n\t\t\t\t\tnops = INSN_SZ_DIFF;\n\t\t\t\t\tif (nops != 0 && nops != 2 && nops != 5) {\n\t\t\t\t\t\tpr_err(\"unexpected nop jump padding: %d bytes\\n\",\n\t\t\t\t\t\t nops);\n\t\t\t\t\t\treturn -EFAULT;\n\t\t\t\t\t}\n\t\t\t\t\tcnt += emit_nops(&prog, nops);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\nemit_jmp:\n\t\t\tif (is_imm8(jmp_offset)) {\n\t\t\t\tif (jmp_padding) {\n\t\t\t\t\t/* To avoid breaking jmp_offset, the extra bytes\n\t\t\t\t\t * are padded before the actual jmp insn, so\n\t\t\t\t\t * 2 bytes is substracted from INSN_SZ_DIFF.\n\t\t\t\t\t *\n\t\t\t\t\t * If the previous pass already emits an imm8\n\t\t\t\t\t * jmp, there is nothing to pad (0 byte).\n\t\t\t\t\t *\n\t\t\t\t\t * If it emits an imm32 jmp (5 bytes) previously\n\t\t\t\t\t * and now an imm8 jmp (2 bytes), then we pad\n\t\t\t\t\t * (5 - 2 = 3) bytes to stop the image from\n\t\t\t\t\t * shrinking further.\n\t\t\t\t\t */\n\t\t\t\t\tnops = INSN_SZ_DIFF - 2;\n\t\t\t\t\tif (nops != 0 && nops != 3) {\n\t\t\t\t\t\tpr_err(\"unexpected jump padding: %d bytes\\n\",\n\t\t\t\t\t\t nops);\n\t\t\t\t\t\treturn -EFAULT;\n\t\t\t\t\t}\n\t\t\t\t\tcnt += emit_nops(&prog, INSN_SZ_DIFF - 2);\n\t\t\t\t}\n\t\t\t\tEMIT2(0xEB, jmp_offset);\n\t\t\t} else if (is_simm32(jmp_offset)) {\n\t\t\t\tEMIT1_off32(0xE9, jmp_offset);\n\t\t\t} else {\n\t\t\t\tpr_err(\"jmp gen bug %llx\\n\", jmp_offset);\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BPF_JMP | BPF_EXIT:\n\t\t\tif (seen_exit) {\n\t\t\t\tjmp_offset = ctx->cleanup_addr - addrs[i];\n\t\t\t\tgoto emit_jmp;\n\t\t\t}\n\t\t\tseen_exit = true;\n\t\t\t/* Update cleanup_addr */\n\t\t\tctx->cleanup_addr = proglen;\n\t\t\tpop_callee_regs(&prog, callee_regs_used);\n\t\t\tEMIT1(0xC9); /* leave */\n\t\t\tEMIT1(0xC3); /* ret */\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/*\n\t\t\t * By design x86-64 JIT should support all BPF instructions.\n\t\t\t * This error will be seen if new instruction was added\n\t\t\t * to the interpreter, but not to the JIT, or if there is\n\t\t\t * junk in bpf_prog.\n\t\t\t */\n\t\t\tpr_err(\"bpf_jit: unknown opcode %02x\\n\", insn->code);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tilen = prog - temp;\n\t\tif (ilen > BPF_MAX_INSN_SIZE) {\n\t\t\tpr_err(\"bpf_jit: fatal insn size error\\n\");\n\t\t\treturn -EFAULT;\n\t\t}\n\n\t\tif (image) {\n\t\t\t/*\n\t\t\t * When populating the image, assert that:\n\t\t\t *\n\t\t\t * i) We do not write beyond the allocated space, and\n\t\t\t * ii) addrs[i] did not change from the prior run, in order\n\t\t\t * to validate assumptions made for computing branch\n\t\t\t * displacements.\n\t\t\t */\n\t\t\tif (unlikely(proglen + ilen > oldproglen ||\n\t\t\t\t proglen + ilen != addrs[i])) {\n\t\t\t\tpr_err(\"bpf_jit: fatal error\\n\");\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\tmemcpy(image + proglen, temp, ilen);\n\t\t}\n\t\tproglen += ilen;\n\t\taddrs[i] = proglen;\n\t\tprog = temp;\n\t}\n\n\tif (image && excnt != bpf_prog->aux->num_exentries) {\n\t\tpr_err(\"extable is not populated\\n\");\n\t\treturn -EFAULT;\n\t}\n\treturn proglen;\n}", "project": "linux", "hash": 188508326208408747512908522230061011678, "size": 823, "commit_id": "e4d4d456436bfb2fe412ee2cd489f7658449b098", "message": "bpf, x86: Validate computation of branch displacements for x86-64\n\nThe branch displacement logic in the BPF JIT compilers for x86 assumes\nthat, for any generated branch instruction, the distance cannot\nincrease between optimization passes.\n\nBut this assumption can be violated due to how the distances are\ncomputed. Specifically, whenever a backward branch is processed in\ndo_jit(), the distance is computed by subtracting the positions in the\nmachine code from different optimization passes. This is because part\nof addrs[] is already updated for the current optimization pass, before\nthe branch instruction is visited.\n\nAnd so the optimizer can expand blocks of machine code in some cases.\n\nThis can confuse the optimizer logic, where it assumes that a fixed\npoint has been reached for all machine code blocks once the total\nprogram size stops changing. And then the JIT compiler can output\nabnormal machine code containing incorrect branch displacements.\n\nTo mitigate this issue, we assert that a fixed point is reached while\npopulating the output image. This rejects any problematic programs.\nThe issue affects both x86-32 and x86-64. We mitigate separately to\nease backporting.\n\nSigned-off-by: Piotr Krysiuk <piotras@gmail.com>\nReviewed-by: Daniel Borkmann <daniel@iogearbox.net>\nSigned-off-by: Daniel Borkmann <daniel@iogearbox.net>", "target": 0, "dataset": "other", "idx": 461582}
  943. {"func": "void rsi_mac80211_detach(struct rsi_hw *adapter)\n{\n\tstruct ieee80211_hw *hw = adapter->hw;\n\tenum nl80211_band band;\n\n\tif (hw) {\n\t\tieee80211_stop_queues(hw);\n\t\tieee80211_unregister_hw(hw);\n\t\tieee80211_free_hw(hw);\n\t}\n\n\tfor (band = 0; band < NUM_NL80211_BANDS; band++) {\n\t\tstruct ieee80211_supported_band *sband =\n\t\t\t\t\t&adapter->sbands[band];\n\n\t\tkfree(sband->channels);\n\t}\n\n#ifdef CONFIG_RSI_DEBUGFS\n\trsi_remove_dbgfs(adapter);\n\tkfree(adapter->dfsentry);\n#endif\n}", "project": "linux", "hash": 236883142955445427225930806435433027313, "size": 23, "commit_id": "abd39c6ded9db53aa44c2540092bdd5fb6590fa8", "message": "rsi: add fix for crash during assertions\n\nObserved crash in some scenarios when assertion has occurred,\nthis is because hw structure is freed and is tried to get\naccessed in some functions where null check is already\npresent. So, avoided the crash by making the hw to NULL after\nfreeing.\n\nSigned-off-by: Sanjay Konduri <sanjay.konduri@redpinesignals.com>\nSigned-off-by: Sushant Kumar Mishra <sushant.mishra@redpinesignals.com>\nSigned-off-by: Kalle Valo <kvalo@codeaurora.org>", "target": 1, "dataset": "other", "idx": 212771}
  944. {"func": "void rsi_mac80211_detach(struct rsi_hw *adapter)\n{\n\tstruct ieee80211_hw *hw = adapter->hw;\n\tenum nl80211_band band;\n\n\tif (hw) {\n\t\tieee80211_stop_queues(hw);\n\t\tieee80211_unregister_hw(hw);\n\t\tieee80211_free_hw(hw);\n\t\tadapter->hw = NULL;\n\t}\n\n\tfor (band = 0; band < NUM_NL80211_BANDS; band++) {\n\t\tstruct ieee80211_supported_band *sband =\n\t\t\t\t\t&adapter->sbands[band];\n\n\t\tkfree(sband->channels);\n\t}\n\n#ifdef CONFIG_RSI_DEBUGFS\n\trsi_remove_dbgfs(adapter);\n\tkfree(adapter->dfsentry);\n#endif\n}", "project": "linux", "hash": 10029051295079005700052093461301549026, "size": 24, "commit_id": "abd39c6ded9db53aa44c2540092bdd5fb6590fa8", "message": "rsi: add fix for crash during assertions\n\nObserved crash in some scenarios when assertion has occurred,\nthis is because hw structure is freed and is tried to get\naccessed in some functions where null check is already\npresent. So, avoided the crash by making the hw to NULL after\nfreeing.\n\nSigned-off-by: Sanjay Konduri <sanjay.konduri@redpinesignals.com>\nSigned-off-by: Sushant Kumar Mishra <sushant.mishra@redpinesignals.com>\nSigned-off-by: Kalle Valo <kvalo@codeaurora.org>", "target": 0, "dataset": "other", "idx": 461627}
  945. {"func": "PHP_FUNCTION( msgfmt_parse_message )\n{\n\tUChar *spattern = NULL;\n\tint spattern_len = 0;\n\tchar *pattern = NULL;\n\tsize_t pattern_len = 0;\n\tconst char *slocale = NULL;\n\tsize_t slocale_len = 0;\n\tchar *source = NULL;\n\tsize_t src_len = 0;\n\tMessageFormatter_object mf;\n\tMessageFormatter_object *mfo = &mf;\n\n\t/* Parse parameters. */\n\tif( zend_parse_parameters( ZEND_NUM_ARGS(), \"sss\",\n\t\t &slocale, &slocale_len, &pattern, &pattern_len, &source, &src_len ) == FAILURE )\n\t{\n\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t\t\t\"msgfmt_parse_message: unable to parse input params\", 0 );\n\n\t\tRETURN_FALSE;\n\t}\n\n\tmemset(mfo, 0, sizeof(*mfo));\n\tmsgformat_data_init(&mfo->mf_data);\n\n\tif(pattern && pattern_len) {\n\t\tintl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo));\n\t\tif( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) )\n\t\t{\n\t\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t\t\t\t\"msgfmt_parse_message: error converting pattern to UTF-16\", 0 );\n\t\t\tRETURN_FALSE;\n\t\t}\n\t} else {\n\t\tspattern_len = 0;\n\t\tspattern = NULL;\n\t}\n\n\tif(slocale_len == 0) {\n\t\tslocale = intl_locale_get_default();\n\t}\n\n#ifdef MSG_FORMAT_QUOTE_APOS\n\tif(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) {\n\t\tintl_error_set( NULL, U_INVALID_FORMAT_ERROR,\n\t\t\t\"msgfmt_parse_message: error converting pattern to quote-friendly format\", 0 );\n\t\tRETURN_FALSE;\n\t}\n#endif\n\n\t/* Create an ICU message formatter. */\n\tMSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo));\n\tif(spattern && spattern_len) {\n\t\tefree(spattern);\n\t}\n\tINTL_METHOD_CHECK_STATUS(mfo, \"Creating message formatter failed\");\n\n\tmsgfmt_do_parse(mfo, source, src_len, return_value);\n\n\t/* drop the temporary formatter */\n\tmsgformat_data_free(&mfo->mf_data);\n}", "project": "php-src", "hash": 6806426083657384091418405807666534217, "size": 63, "commit_id": "95c4564f939c916538579ef63602a3cd31941c51", "message": "Fixed bug #73473: Stack Buffer Overflow in msgfmt_parse_message", "target": 1, "dataset": "other", "idx": 212820}
  946. {"func": "PHP_FUNCTION( msgfmt_parse_message )\n{\n\tUChar *spattern = NULL;\n\tint spattern_len = 0;\n\tchar *pattern = NULL;\n\tsize_t pattern_len = 0;\n\tconst char *slocale = NULL;\n\tsize_t slocale_len = 0;\n\tchar *source = NULL;\n\tsize_t src_len = 0;\n\tMessageFormatter_object mf;\n\tMessageFormatter_object *mfo = &mf;\n\n\t/* Parse parameters. */\n\tif( zend_parse_parameters( ZEND_NUM_ARGS(), \"sss\",\n\t\t &slocale, &slocale_len, &pattern, &pattern_len, &source, &src_len ) == FAILURE )\n\t{\n\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t\t\t\"msgfmt_parse_message: unable to parse input params\", 0 );\n\n\t\tRETURN_FALSE;\n\t}\n\n\tINTL_CHECK_LOCALE_LEN(slocale_len);\n\tmemset(mfo, 0, sizeof(*mfo));\n\tmsgformat_data_init(&mfo->mf_data);\n\n\tif(pattern && pattern_len) {\n\t\tintl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo));\n\t\tif( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) )\n\t\t{\n\t\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t\t\t\t\"msgfmt_parse_message: error converting pattern to UTF-16\", 0 );\n\t\t\tRETURN_FALSE;\n\t\t}\n\t} else {\n\t\tspattern_len = 0;\n\t\tspattern = NULL;\n\t}\n\n\tif(slocale_len == 0) {\n\t\tslocale = intl_locale_get_default();\n\t}\n\n#ifdef MSG_FORMAT_QUOTE_APOS\n\tif(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) {\n\t\tintl_error_set( NULL, U_INVALID_FORMAT_ERROR,\n\t\t\t\"msgfmt_parse_message: error converting pattern to quote-friendly format\", 0 );\n\t\tRETURN_FALSE;\n\t}\n#endif\n\n\t/* Create an ICU message formatter. */\n\tMSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo));\n\tif(spattern && spattern_len) {\n\t\tefree(spattern);\n\t}\n\tINTL_METHOD_CHECK_STATUS(mfo, \"Creating message formatter failed\");\n\n\tmsgfmt_do_parse(mfo, source, src_len, return_value);\n\n\t/* drop the temporary formatter */\n\tmsgformat_data_free(&mfo->mf_data);\n}", "project": "php-src", "hash": 91908387484897166366489060678294896561, "size": 64, "commit_id": "95c4564f939c916538579ef63602a3cd31941c51", "message": "Fixed bug #73473: Stack Buffer Overflow in msgfmt_parse_message", "target": 0, "dataset": "other", "idx": 462287}
  947. {"func": "writepid (const char* pidfile, pid_t pid)\n{\n\tFILE* f;\n\n\tif ((f = fopen(pidfile, \"w\")) == NULL ) {\n\t\tlog_err(\"cannot open pidfile %s: %s\", \n\t\t\tpidfile, strerror(errno));\n\t\treturn;\n\t}\n\tif(fprintf(f, \"%lu\\n\", (unsigned long)pid) < 0) {\n\t\tlog_err(\"cannot write to pidfile %s: %s\", \n\t\t\tpidfile, strerror(errno));\n\t}\n\tfclose(f);\n}", "project": "unbound", "hash": 81315826788429169272585727489229965045, "size": 15, "commit_id": "ad387832979b6ce4c93f64fe706301cd7d034e87", "message": "- Fix for #303 CVE-2020-28935 : Fix that symlink does not interfere\n with chown of pidfile.", "target": 1, "dataset": "other", "idx": 212821}
  948. {"func": "writepid (const char* pidfile, pid_t pid)\n{\n\tint fd;\n\tchar pidbuf[32];\n\tsize_t count = 0;\n\tsnprintf(pidbuf, sizeof(pidbuf), \"%lu\\n\", (unsigned long)pid);\n\n\tif((fd = open(pidfile, O_WRONLY | O_CREAT | O_TRUNC\n#ifdef O_NOFOLLOW\n\t\t| O_NOFOLLOW\n#endif\n\t\t, 0644)) == -1) {\n\t\tlog_err(\"cannot open pidfile %s: %s\", \n\t\t\tpidfile, strerror(errno));\n\t\treturn;\n\t}\n\twhile(count < strlen(pidbuf)) {\n\t\tssize_t r = write(fd, pidbuf+count, strlen(pidbuf)-count);\n\t\tif(r == -1) {\n\t\t\tif(errno == EAGAIN || errno == EINTR)\n\t\t\t\tcontinue;\n\t\t\tlog_err(\"cannot write to pidfile %s: %s\",\n\t\t\t\tpidfile, strerror(errno));\n\t\t\tbreak;\n\t\t}\n\t\tcount += r;\n\t}\n\tclose(fd);\n}", "project": "unbound", "hash": 307992336681835740844480617769066838283, "size": 29, "commit_id": "ad387832979b6ce4c93f64fe706301cd7d034e87", "message": "- Fix for #303 CVE-2020-28935 : Fix that symlink does not interfere\n with chown of pidfile.", "target": 0, "dataset": "other", "idx": 462294}
  949. {"func": "static int dw_spi_transfer_one(struct spi_controller *master,\n\t\tstruct spi_device *spi, struct spi_transfer *transfer)\n{\n\tstruct dw_spi *dws = spi_controller_get_devdata(master);\n\tstruct chip_data *chip = spi_get_ctldata(spi);\n\tu8 imask = 0;\n\tu16 txlevel = 0;\n\tu32 cr0;\n\tint ret;\n\n\tdws->dma_mapped = 0;\n\n\tdws->tx = (void *)transfer->tx_buf;\n\tdws->tx_end = dws->tx + transfer->len;\n\tdws->rx = transfer->rx_buf;\n\tdws->rx_end = dws->rx + transfer->len;\n\tdws->len = transfer->len;\n\n\tspi_enable_chip(dws, 0);\n\n\t/* Handle per transfer options for bpw and speed */\n\tif (transfer->speed_hz != dws->current_freq) {\n\t\tif (transfer->speed_hz != chip->speed_hz) {\n\t\t\t/* clk_div doesn't support odd number */\n\t\t\tchip->clk_div = (DIV_ROUND_UP(dws->max_freq, transfer->speed_hz) + 1) & 0xfffe;\n\t\t\tchip->speed_hz = transfer->speed_hz;\n\t\t}\n\t\tdws->current_freq = transfer->speed_hz;\n\t\tspi_set_clk(dws, chip->clk_div);\n\t}\n\n\tdws->n_bytes = DIV_ROUND_UP(transfer->bits_per_word, BITS_PER_BYTE);\n\tdws->dma_width = DIV_ROUND_UP(transfer->bits_per_word, BITS_PER_BYTE);\n\n\t/* Default SPI mode is SCPOL = 0, SCPH = 0 */\n\tcr0 = (transfer->bits_per_word - 1)\n\t\t| (chip->type << SPI_FRF_OFFSET)\n\t\t| ((((spi->mode & SPI_CPOL) ? 1 : 0) << SPI_SCOL_OFFSET) |\n\t\t\t(((spi->mode & SPI_CPHA) ? 1 : 0) << SPI_SCPH_OFFSET))\n\t\t| (chip->tmode << SPI_TMOD_OFFSET);\n\n\t/*\n\t * Adjust transfer mode if necessary. Requires platform dependent\n\t * chipselect mechanism.\n\t */\n\tif (chip->cs_control) {\n\t\tif (dws->rx && dws->tx)\n\t\t\tchip->tmode = SPI_TMOD_TR;\n\t\telse if (dws->rx)\n\t\t\tchip->tmode = SPI_TMOD_RO;\n\t\telse\n\t\t\tchip->tmode = SPI_TMOD_TO;\n\n\t\tcr0 &= ~SPI_TMOD_MASK;\n\t\tcr0 |= (chip->tmode << SPI_TMOD_OFFSET);\n\t}\n\n\tdw_writel(dws, DW_SPI_CTRL0, cr0);\n\n\t/* Check if current transfer is a DMA transaction */\n\tif (master->can_dma && master->can_dma(master, spi, transfer))\n\t\tdws->dma_mapped = master->cur_msg_mapped;\n\n\t/* For poll mode just disable all interrupts */\n\tspi_mask_intr(dws, 0xff);\n\n\t/*\n\t * Interrupt mode\n\t * we only need set the TXEI IRQ, as TX/RX always happen syncronizely\n\t */\n\tif (dws->dma_mapped) {\n\t\tret = dws->dma_ops->dma_setup(dws, transfer);\n\t\tif (ret < 0) {\n\t\t\tspi_enable_chip(dws, 1);\n\t\t\treturn ret;\n\t\t}\n\t} else if (!chip->poll_mode) {\n\t\ttxlevel = min_t(u16, dws->fifo_len / 2, dws->len / dws->n_bytes);\n\t\tdw_writel(dws, DW_SPI_TXFLTR, txlevel);\n\n\t\t/* Set the interrupt mask */\n\t\timask |= SPI_INT_TXEI | SPI_INT_TXOI |\n\t\t\t SPI_INT_RXUI | SPI_INT_RXOI;\n\t\tspi_umask_intr(dws, imask);\n\n\t\tdws->transfer_handler = interrupt_transfer;\n\t}\n\n\tspi_enable_chip(dws, 1);\n\n\tif (dws->dma_mapped) {\n\t\tret = dws->dma_ops->dma_transfer(dws, transfer);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t}\n\n\tif (chip->poll_mode)\n\t\treturn poll_transfer(dws);\n\n\treturn 1;\n}", "project": "linux", "hash": 191752239953234250352277066792734233491, "size": 101, "commit_id": "19b61392c5a852b4e8a0bf35aecb969983c5932d", "message": "spi: spi-dw: Add lock protect dw_spi rx/tx to prevent concurrent calls\n\ndw_spi_irq() and dw_spi_transfer_one concurrent calls.\n\nI find a panic in dw_writer(): txw = *(u8 *)(dws->tx), when dw->tx==null,\ndw->len==4, and dw->tx_end==1.\n\nWhen tpm driver's message overtime dw_spi_irq() and dw_spi_transfer_one\nmay concurrent visit dw_spi, so I think dw_spi structure lack of protection.\n\nOtherwise dw_spi_transfer_one set dw rx/tx buffer and then open irq,\nstore dw rx/tx instructions and other cores handle irq load dw rx/tx\ninstructions may out of order.\n\n\t[ 1025.321302] Call trace:\n\t...\n\t[ 1025.321319] __crash_kexec+0x98/0x148\n\t[ 1025.321323] panic+0x17c/0x314\n\t[ 1025.321329] die+0x29c/0x2e8\n\t[ 1025.321334] die_kernel_fault+0x68/0x78\n\t[ 1025.321337] __do_kernel_fault+0x90/0xb0\n\t[ 1025.321346] do_page_fault+0x88/0x500\n\t[ 1025.321347] do_translation_fault+0xa8/0xb8\n\t[ 1025.321349] do_mem_abort+0x68/0x118\n\t[ 1025.321351] el1_da+0x20/0x8c\n\t[ 1025.321362] dw_writer+0xc8/0xd0\n\t[ 1025.321364] interrupt_transfer+0x60/0x110\n\t[ 1025.321365] dw_spi_irq+0x48/0x70\n\t...\n\nSigned-off-by: wuxu.wu <wuxu.wu@huawei.com>\nLink: https://lore.kernel.org/r/1577849981-31489-1-git-send-email-wuxu.wu@huawei.com\nSigned-off-by: Mark Brown <broonie@kernel.org>", "target": 1, "dataset": "other", "idx": 212837}
  950. {"func": "static int dw_spi_transfer_one(struct spi_controller *master,\n\t\tstruct spi_device *spi, struct spi_transfer *transfer)\n{\n\tstruct dw_spi *dws = spi_controller_get_devdata(master);\n\tstruct chip_data *chip = spi_get_ctldata(spi);\n\tunsigned long flags;\n\tu8 imask = 0;\n\tu16 txlevel = 0;\n\tu32 cr0;\n\tint ret;\n\n\tdws->dma_mapped = 0;\n\tspin_lock_irqsave(&dws->buf_lock, flags);\n\tdws->tx = (void *)transfer->tx_buf;\n\tdws->tx_end = dws->tx + transfer->len;\n\tdws->rx = transfer->rx_buf;\n\tdws->rx_end = dws->rx + transfer->len;\n\tdws->len = transfer->len;\n\tspin_unlock_irqrestore(&dws->buf_lock, flags);\n\n\tspi_enable_chip(dws, 0);\n\n\t/* Handle per transfer options for bpw and speed */\n\tif (transfer->speed_hz != dws->current_freq) {\n\t\tif (transfer->speed_hz != chip->speed_hz) {\n\t\t\t/* clk_div doesn't support odd number */\n\t\t\tchip->clk_div = (DIV_ROUND_UP(dws->max_freq, transfer->speed_hz) + 1) & 0xfffe;\n\t\t\tchip->speed_hz = transfer->speed_hz;\n\t\t}\n\t\tdws->current_freq = transfer->speed_hz;\n\t\tspi_set_clk(dws, chip->clk_div);\n\t}\n\n\tdws->n_bytes = DIV_ROUND_UP(transfer->bits_per_word, BITS_PER_BYTE);\n\tdws->dma_width = DIV_ROUND_UP(transfer->bits_per_word, BITS_PER_BYTE);\n\n\t/* Default SPI mode is SCPOL = 0, SCPH = 0 */\n\tcr0 = (transfer->bits_per_word - 1)\n\t\t| (chip->type << SPI_FRF_OFFSET)\n\t\t| ((((spi->mode & SPI_CPOL) ? 1 : 0) << SPI_SCOL_OFFSET) |\n\t\t\t(((spi->mode & SPI_CPHA) ? 1 : 0) << SPI_SCPH_OFFSET))\n\t\t| (chip->tmode << SPI_TMOD_OFFSET);\n\n\t/*\n\t * Adjust transfer mode if necessary. Requires platform dependent\n\t * chipselect mechanism.\n\t */\n\tif (chip->cs_control) {\n\t\tif (dws->rx && dws->tx)\n\t\t\tchip->tmode = SPI_TMOD_TR;\n\t\telse if (dws->rx)\n\t\t\tchip->tmode = SPI_TMOD_RO;\n\t\telse\n\t\t\tchip->tmode = SPI_TMOD_TO;\n\n\t\tcr0 &= ~SPI_TMOD_MASK;\n\t\tcr0 |= (chip->tmode << SPI_TMOD_OFFSET);\n\t}\n\n\tdw_writel(dws, DW_SPI_CTRL0, cr0);\n\n\t/* Check if current transfer is a DMA transaction */\n\tif (master->can_dma && master->can_dma(master, spi, transfer))\n\t\tdws->dma_mapped = master->cur_msg_mapped;\n\n\t/* For poll mode just disable all interrupts */\n\tspi_mask_intr(dws, 0xff);\n\n\t/*\n\t * Interrupt mode\n\t * we only need set the TXEI IRQ, as TX/RX always happen syncronizely\n\t */\n\tif (dws->dma_mapped) {\n\t\tret = dws->dma_ops->dma_setup(dws, transfer);\n\t\tif (ret < 0) {\n\t\t\tspi_enable_chip(dws, 1);\n\t\t\treturn ret;\n\t\t}\n\t} else if (!chip->poll_mode) {\n\t\ttxlevel = min_t(u16, dws->fifo_len / 2, dws->len / dws->n_bytes);\n\t\tdw_writel(dws, DW_SPI_TXFLTR, txlevel);\n\n\t\t/* Set the interrupt mask */\n\t\timask |= SPI_INT_TXEI | SPI_INT_TXOI |\n\t\t\t SPI_INT_RXUI | SPI_INT_RXOI;\n\t\tspi_umask_intr(dws, imask);\n\n\t\tdws->transfer_handler = interrupt_transfer;\n\t}\n\n\tspi_enable_chip(dws, 1);\n\n\tif (dws->dma_mapped) {\n\t\tret = dws->dma_ops->dma_transfer(dws, transfer);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t}\n\n\tif (chip->poll_mode)\n\t\treturn poll_transfer(dws);\n\n\treturn 1;\n}", "project": "linux", "hash": 323360310926930360690361021045187060996, "size": 103, "commit_id": "19b61392c5a852b4e8a0bf35aecb969983c5932d", "message": "spi: spi-dw: Add lock protect dw_spi rx/tx to prevent concurrent calls\n\ndw_spi_irq() and dw_spi_transfer_one concurrent calls.\n\nI find a panic in dw_writer(): txw = *(u8 *)(dws->tx), when dw->tx==null,\ndw->len==4, and dw->tx_end==1.\n\nWhen tpm driver's message overtime dw_spi_irq() and dw_spi_transfer_one\nmay concurrent visit dw_spi, so I think dw_spi structure lack of protection.\n\nOtherwise dw_spi_transfer_one set dw rx/tx buffer and then open irq,\nstore dw rx/tx instructions and other cores handle irq load dw rx/tx\ninstructions may out of order.\n\n\t[ 1025.321302] Call trace:\n\t...\n\t[ 1025.321319] __crash_kexec+0x98/0x148\n\t[ 1025.321323] panic+0x17c/0x314\n\t[ 1025.321329] die+0x29c/0x2e8\n\t[ 1025.321334] die_kernel_fault+0x68/0x78\n\t[ 1025.321337] __do_kernel_fault+0x90/0xb0\n\t[ 1025.321346] do_page_fault+0x88/0x500\n\t[ 1025.321347] do_translation_fault+0xa8/0xb8\n\t[ 1025.321349] do_mem_abort+0x68/0x118\n\t[ 1025.321351] el1_da+0x20/0x8c\n\t[ 1025.321362] dw_writer+0xc8/0xd0\n\t[ 1025.321364] interrupt_transfer+0x60/0x110\n\t[ 1025.321365] dw_spi_irq+0x48/0x70\n\t...\n\nSigned-off-by: wuxu.wu <wuxu.wu@huawei.com>\nLink: https://lore.kernel.org/r/1577849981-31489-1-git-send-email-wuxu.wu@huawei.com\nSigned-off-by: Mark Brown <broonie@kernel.org>", "target": 0, "dataset": "other", "idx": 462461}
  951. {"func": "INLINE void gdi_RectToCRgn(const HGDI_RECT rect, INT32* x, INT32* y, INT32* w, INT32* h)\n{\n\t*x = rect->left;\n\t*y = rect->top;\n\t*w = rect->right - rect->left + 1;\n\t*h = rect->bottom - rect->top + 1;\n}", "project": "FreeRDP", "hash": 15598217798169870623186526285570205870, "size": 7, "commit_id": "ce21b9d7ecd967e0bc98ed31a6b3757848aa6c9e", "message": "Fix CVE-2020-11523: clamp invalid rectangles to size 0\n\nThanks to Sunglin and HuanGMz from Knownsec 404", "target": 1, "dataset": "other", "idx": 212839}
  952. {"func": "INLINE void gdi_RectToRgn(HGDI_RECT rect, HGDI_RGN rgn)\n{\n\trgn->x = rect->left;\n\trgn->y = rect->top;\n\trgn->w = rect->right - rect->left + 1;\n\trgn->h = rect->bottom - rect->top + 1;\n}", "project": "FreeRDP", "hash": 282322436390722434711482192909845070013, "size": 7, "commit_id": "ce21b9d7ecd967e0bc98ed31a6b3757848aa6c9e", "message": "Fix CVE-2020-11523: clamp invalid rectangles to size 0\n\nThanks to Sunglin and HuanGMz from Knownsec 404", "target": 0, "dataset": "other", "idx": 462482}
  953. {"func": "_gnutls_x509_dn_to_string(const char *oid, void *value,\n\t\t\t int value_size, gnutls_datum_t * str)\n{\n\tconst struct oid_to_string *oentry;\n\tint ret;\n\tgnutls_datum_t tmp;\n\tsize_t size;\n\n\tif (value == NULL || value_size <= 0) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INVALID_REQUEST;\n\t}\n\n\toentry = get_oid_entry(oid);\n\tif (oentry == NULL) {\t/* unknown OID -> hex */\n unknown_oid:\n\t\tstr->size = value_size * 2 + 2;\n\t\tstr->data = gnutls_malloc(str->size);\n\t\tif (str->data == NULL)\n\t\t\treturn gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);\n\n\t\tsize = str->size;\n\t\tret = data2hex(value, value_size, str->data, &size);\n\t\tif (ret < 0) {\n\t\t\tgnutls_assert();\n\t\t\tgnutls_free(str->data);\n\t\t\treturn ret;\n\t\t}\n\t\tstr->size = size;\n\t\treturn 0;\n\t}\n\n\tif (oentry->asn_desc != NULL) {\t/* complex */\n\t\tret =\n\t\t decode_complex_string(oentry, value, value_size, &tmp);\n\t\tif (ret < 0) {\n\t\t\t/* we failed decoding -> handle it as unknown OID */\n\t\t\tgoto unknown_oid;\n\t\t}\n\t} else {\n\t\tret =\n\t\t _gnutls_x509_decode_string(oentry->etype, value,\n\t\t\t\t\t value_size, &tmp, 0);\n\t\tif (ret < 0) {\n\t\t\t/* we failed decoding -> handle it as unknown OID */\n\t\t\tgoto unknown_oid;\n\t\t}\n\t}\n\n\tret = str_escape(&tmp, str);\n\t_gnutls_free_datum(&tmp);\n\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\treturn 0;\n}", "project": "gnutls", "hash": 264692986559165841563862292253464619100, "size": 57, "commit_id": "272854367efc130fbd4f1a51840d80c630214e12", "message": "Reset the output value on error in _gnutls_x509_dn_to_string()\n\nReported by Kurt Roeckx.", "target": 1, "dataset": "other", "idx": 212884}
  954. {"func": "_gnutls_x509_dn_to_string(const char *oid, void *value,\n\t\t\t int value_size, gnutls_datum_t * str)\n{\n\tconst struct oid_to_string *oentry;\n\tint ret;\n\tgnutls_datum_t tmp;\n\tsize_t size;\n\n\tif (value == NULL || value_size <= 0) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INVALID_REQUEST;\n\t}\n\n\toentry = get_oid_entry(oid);\n\tif (oentry == NULL) {\t/* unknown OID -> hex */\n unknown_oid:\n\t\tstr->size = value_size * 2 + 2;\n\t\tstr->data = gnutls_malloc(str->size);\n\t\tif (str->data == NULL)\n\t\t\treturn gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);\n\n\t\tsize = str->size;\n\t\tret = data2hex(value, value_size, str->data, &size);\n\t\tif (ret < 0) {\n\t\t\tgnutls_assert();\n\t\t\tgnutls_free(str->data);\n\t\t\tstr->data = NULL;\n\t\t\treturn ret;\n\t\t}\n\t\tstr->size = size;\n\t\treturn 0;\n\t}\n\n\tif (oentry->asn_desc != NULL) {\t/* complex */\n\t\tret =\n\t\t decode_complex_string(oentry, value, value_size, &tmp);\n\t\tif (ret < 0) {\n\t\t\t/* we failed decoding -> handle it as unknown OID */\n\t\t\tgoto unknown_oid;\n\t\t}\n\t} else {\n\t\tret =\n\t\t _gnutls_x509_decode_string(oentry->etype, value,\n\t\t\t\t\t value_size, &tmp, 0);\n\t\tif (ret < 0) {\n\t\t\t/* we failed decoding -> handle it as unknown OID */\n\t\t\tgoto unknown_oid;\n\t\t}\n\t}\n\n\tret = str_escape(&tmp, str);\n\t_gnutls_free_datum(&tmp);\n\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\treturn 0;\n}", "project": "gnutls", "hash": 163417149612341670448441181123820076841, "size": 58, "commit_id": "272854367efc130fbd4f1a51840d80c630214e12", "message": "Reset the output value on error in _gnutls_x509_dn_to_string()\n\nReported by Kurt Roeckx.", "target": 0, "dataset": "other", "idx": 462706}
  955. {"func": "static const char *GetMagickPropertyLetter(const ImageInfo *image_info,\n Image *image,const char letter)\n{\n char\n value[MaxTextExtent];\n\n const char\n *string;\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 *value='\\0';\n string=(char *) NULL;\n switch (letter)\n {\n case 'b':\n {\n /*\n Image size read in - in bytes.\n */\n (void) FormatMagickSize(image->extent,MagickFalse,value);\n if (image->extent == 0)\n (void) FormatMagickSize(GetBlobSize(image),MagickFalse,value);\n break;\n }\n case 'c':\n {\n /*\n Image comment property - empty string by default.\n */\n string=GetImageProperty(image,\"comment\");\n if (string == (const char *) NULL)\n string=\"\";\n break;\n }\n case 'd':\n {\n /*\n Directory component of filename.\n */\n GetPathComponent(image->magick_filename,HeadPath,value);\n if (*value == '\\0')\n string=\"\";\n break;\n }\n case 'e':\n {\n /*\n Filename extension (suffix) of image file.\n */\n GetPathComponent(image->magick_filename,ExtensionPath,value);\n if (*value == '\\0')\n string=\"\";\n break;\n }\n case 'f':\n {\n /*\n Filename without directory component.\n */\n GetPathComponent(image->magick_filename,TailPath,value);\n if (*value == '\\0')\n string=\"\";\n break;\n }\n case 'g':\n {\n /*\n Image geometry, canvas and offset %Wx%H+%X+%Y.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20gx%.20g%+.20g%+.20g\",\n (double) image->page.width,(double) image->page.height,\n (double) image->page.x,(double) image->page.y);\n break;\n }\n case 'h':\n {\n /*\n Image height (current).\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n (image->rows != 0 ? image->rows : image->magick_rows));\n break;\n }\n case 'i':\n {\n /*\n Filename last used for image (read or write).\n */\n string=image->filename;\n break;\n }\n case 'k':\n {\n /*\n Number of unique colors.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n GetNumberColors(image,(FILE *) NULL,&image->exception));\n break;\n }\n case 'l':\n {\n /*\n Image label property - empty string by default.\n */\n string=GetImageProperty(image,\"label\");\n if (string == (const char *) NULL)\n string=\"\";\n break;\n }\n case 'm':\n {\n /*\n Image format (file magick).\n */\n string=image->magick;\n break;\n }\n case 'n':\n {\n /*\n Number of images in the list.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n GetImageListLength(image));\n break;\n }\n case 'o':\n {\n /*\n Output Filename - for delegate use only\n */\n string=image_info->filename;\n break;\n }\n case 'p':\n {\n /*\n Image index in current image list -- As 'n' OBSOLETE.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n GetImageIndexInList(image));\n break;\n }\n case 'q':\n {\n /*\n Quantum depth of image in memory.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n MAGICKCORE_QUANTUM_DEPTH);\n break;\n }\n case 'r':\n {\n ColorspaceType\n colorspace;\n\n /*\n Image storage class and colorspace.\n */\n colorspace=image->colorspace;\n if ((image->columns != 0) && (image->rows != 0) &&\n (SetImageGray(image,&image->exception) != MagickFalse))\n colorspace=GRAYColorspace;\n (void) FormatLocaleString(value,MaxTextExtent,\"%s %s %s\",\n CommandOptionToMnemonic(MagickClassOptions,(ssize_t)\n image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions,\n (ssize_t) colorspace),image->matte != MagickFalse ? \"Matte\" : \"\" );\n break;\n }\n case 's':\n {\n /*\n Image scene number.\n */\n if (image_info->number_scenes != 0)\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image_info->scene);\n else\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->scene);\n break;\n }\n case 't':\n {\n /*\n Base filename without directory or extension.\n */\n GetPathComponent(image->magick_filename,BasePath,value);\n break;\n }\n case 'u':\n {\n /*\n Unique filename.\n */\n string=image_info->unique;\n break;\n }\n case 'w':\n {\n /*\n Image width (current).\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n (image->columns != 0 ? image->columns : image->magick_columns));\n break;\n }\n case 'x':\n {\n /*\n Image horizontal resolution.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",\n fabs(image->x_resolution) > MagickEpsilon ? image->x_resolution : 72.0);\n break;\n }\n case 'y':\n {\n /*\n Image vertical resolution.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",\n fabs(image->y_resolution) > MagickEpsilon ? image->y_resolution : 72.0);\n break;\n }\n case 'z':\n {\n /*\n Image depth.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->depth);\n break;\n }\n case 'A':\n {\n /*\n Image alpha channel.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%s\",\n CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte));\n break;\n }\n case 'B':\n {\n /*\n Image size read in - in bytes.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->extent);\n if (image->extent == 0)\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n GetBlobSize(image));\n break;\n }\n case 'C':\n {\n /*\n Image compression method.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%s\",\n CommandOptionToMnemonic(MagickCompressOptions,(ssize_t)\n image->compression));\n break;\n }\n case 'D':\n {\n /*\n Image dispose method.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%s\",\n CommandOptionToMnemonic(MagickDisposeOptions,(ssize_t) image->dispose));\n break;\n }\n case 'F':\n {\n const char\n *q;\n\n register char\n *p;\n\n static char\n whitelist[] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 \"\n \"$-_.+!*'(),{}|\\\\^~[]`\\\"><#%;/?:@&=\";\n\n /*\n Magick filename (sanitized) - filename given incl. coder & read mods.\n */\n (void) CopyMagickString(value,image->magick_filename,MaxTextExtent);\n p=value;\n q=value+strlen(value);\n for (p+=strspn(p,whitelist); p != q; p+=strspn(p,whitelist))\n *p='_';\n break;\n }\n case 'G':\n {\n /*\n Image size as geometry = \"%wx%h\".\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20gx%.20g\",(double)\n image->magick_columns,(double) image->magick_rows);\n break;\n }\n case 'H':\n {\n /*\n Layer canvas height.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->page.height);\n break;\n }\n case 'M':\n {\n /*\n Magick filename - filename given incl. coder & read mods.\n */\n string=image->magick_filename;\n break;\n }\n case 'O':\n {\n /*\n Layer canvas offset with sign = \"+%X+%Y\".\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%+ld%+ld\",(long)\n image->page.x,(long) image->page.y);\n break;\n }\n case 'P':\n {\n /*\n Layer canvas page size = \"%Wx%H\".\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20gx%.20g\",(double)\n image->page.width,(double) image->page.height);\n break;\n }\n case 'Q':\n {\n /*\n Image compression quality.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n (image->quality == 0 ? 92 : image->quality));\n break;\n }\n case 'S':\n {\n /*\n Image scenes.\n */\n if (image_info->number_scenes == 0)\n string=\"2147483647\";\n else\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image_info->scene+image_info->number_scenes);\n break;\n }\n case 'T':\n {\n /*\n Image time delay for animations.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->delay);\n break;\n }\n case 'U':\n {\n /*\n Image resolution units.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%s\",\n CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t)\n image->units));\n break;\n }\n case 'W':\n {\n /*\n Layer canvas width.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->page.width);\n break;\n }\n case 'X':\n {\n /*\n Layer canvas X offset.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%+.20g\",(double)\n image->page.x);\n break;\n }\n case 'Y':\n {\n /*\n Layer canvas Y offset.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%+.20g\",(double)\n image->page.y);\n break;\n }\n case 'Z':\n {\n /*\n Zero filename.\n */\n string=image_info->zero;\n break;\n }\n case '@':\n {\n RectangleInfo\n page;\n\n /*\n Image bounding box.\n */\n page=GetImageBoundingBox(image,&image->exception);\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20gx%.20g%+.20g%+.20g\",\n (double) page.width,(double) page.height,(double) page.x,(double)\n page.y);\n break;\n }\n case '#':\n {\n /*\n Image signature.\n */\n if ((image->columns != 0) && (image->rows != 0))\n (void) SignatureImage(image);\n string=GetImageProperty(image,\"signature\");\n break;\n }\n case '%':\n {\n /*\n Percent escaped.\n */\n string=\"%\";\n break;\n }\n }\n if (*value != '\\0')\n string=value;\n if (string != (char *) NULL)\n {\n (void) SetImageArtifact(image,\"get-property\",string);\n return(GetImageArtifact(image,\"get-property\"));\n }\n return((char *) NULL);\n}", "project": "ImageMagick6", "hash": 81789685423307343026163762196655100181, "size": 463, "commit_id": "5bf7ff59c8ada957d6a681a0a2cc29f3813ad4bc", "message": "https://github.com/ImageMagick/ImageMagick/issues/1225", "target": 1, "dataset": "other", "idx": 212909}
  956. {"func": "static const char *GetMagickPropertyLetter(const ImageInfo *image_info,\n Image *image,const char letter)\n{\n#define WarnNoImageInfoReturn(format,arg) \\\n if (image_info == (ImageInfo *) NULL ) { \\\n (void) ThrowMagickException(&image->exception,GetMagickModule(), \\\n OptionWarning,\"NoImageInfoForProperty\",format,arg); \\\n return((const char *) NULL); \\\n }\n\n char\n value[MaxTextExtent];\n\n const char\n *string;\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 *value='\\0';\n string=(char *) NULL;\n switch (letter)\n {\n case 'b':\n {\n /*\n Image size read in - in bytes.\n */\n (void) FormatMagickSize(image->extent,MagickFalse,value);\n if (image->extent == 0)\n (void) FormatMagickSize(GetBlobSize(image),MagickFalse,value);\n break;\n }\n case 'c':\n {\n /*\n Image comment property - empty string by default.\n */\n string=GetImageProperty(image,\"comment\");\n if (string == (const char *) NULL)\n string=\"\";\n break;\n }\n case 'd':\n {\n /*\n Directory component of filename.\n */\n GetPathComponent(image->magick_filename,HeadPath,value);\n if (*value == '\\0')\n string=\"\";\n break;\n }\n case 'e':\n {\n /*\n Filename extension (suffix) of image file.\n */\n GetPathComponent(image->magick_filename,ExtensionPath,value);\n if (*value == '\\0')\n string=\"\";\n break;\n }\n case 'f':\n {\n /*\n Filename without directory component.\n */\n GetPathComponent(image->magick_filename,TailPath,value);\n if (*value == '\\0')\n string=\"\";\n break;\n }\n case 'g':\n {\n /*\n Image geometry, canvas and offset %Wx%H+%X+%Y.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20gx%.20g%+.20g%+.20g\",\n (double) image->page.width,(double) image->page.height,\n (double) image->page.x,(double) image->page.y);\n break;\n }\n case 'h':\n {\n /*\n Image height (current).\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n (image->rows != 0 ? image->rows : image->magick_rows));\n break;\n }\n case 'i':\n {\n /*\n Filename last used for image (read or write).\n */\n string=image->filename;\n break;\n }\n case 'k':\n {\n /*\n Number of unique colors.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n GetNumberColors(image,(FILE *) NULL,&image->exception));\n break;\n }\n case 'l':\n {\n /*\n Image label property - empty string by default.\n */\n string=GetImageProperty(image,\"label\");\n if (string == (const char *) NULL)\n string=\"\";\n break;\n }\n case 'm':\n {\n /*\n Image format (file magick).\n */\n string=image->magick;\n break;\n }\n case 'n':\n {\n /*\n Number of images in the list.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n GetImageListLength(image));\n break;\n }\n case 'o':\n {\n /*\n Output Filename - for delegate use only\n */\n WarnNoImageInfoReturn(\"\\\"%%%c\\\"\",letter);\n string=image_info->filename;\n break;\n }\n case 'p':\n {\n /*\n Image index in current image list -- As 'n' OBSOLETE.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n GetImageIndexInList(image));\n break;\n }\n case 'q':\n {\n /*\n Quantum depth of image in memory.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n MAGICKCORE_QUANTUM_DEPTH);\n break;\n }\n case 'r':\n {\n ColorspaceType\n colorspace;\n\n /*\n Image storage class and colorspace.\n */\n colorspace=image->colorspace;\n if ((image->columns != 0) && (image->rows != 0) &&\n (SetImageGray(image,&image->exception) != MagickFalse))\n colorspace=GRAYColorspace;\n (void) FormatLocaleString(value,MaxTextExtent,\"%s %s %s\",\n CommandOptionToMnemonic(MagickClassOptions,(ssize_t)\n image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions,\n (ssize_t) colorspace),image->matte != MagickFalse ? \"Matte\" : \"\" );\n break;\n }\n case 's':\n {\n /*\n Image scene number.\n */\n WarnNoImageInfoReturn(\"\\\"%%%c\\\"\",letter);\n if (image_info->number_scenes != 0)\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image_info->scene);\n else\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->scene);\n break;\n }\n case 't':\n {\n /*\n Base filename without directory or extension.\n */\n GetPathComponent(image->magick_filename,BasePath,value);\n break;\n }\n case 'u':\n {\n /*\n Unique filename.\n */\n WarnNoImageInfoReturn(\"\\\"%%%c\\\"\",letter);\n string=image_info->unique;\n break;\n }\n case 'w':\n {\n /*\n Image width (current).\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n (image->columns != 0 ? image->columns : image->magick_columns));\n break;\n }\n case 'x':\n {\n /*\n Image horizontal resolution.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",\n fabs(image->x_resolution) > MagickEpsilon ? image->x_resolution : 72.0);\n break;\n }\n case 'y':\n {\n /*\n Image vertical resolution.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",\n fabs(image->y_resolution) > MagickEpsilon ? image->y_resolution : 72.0);\n break;\n }\n case 'z':\n {\n /*\n Image depth.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->depth);\n break;\n }\n case 'A':\n {\n /*\n Image alpha channel.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%s\",\n CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte));\n break;\n }\n case 'B':\n {\n /*\n Image size read in - in bytes.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->extent);\n if (image->extent == 0)\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n GetBlobSize(image));\n break;\n }\n case 'C':\n {\n /*\n Image compression method.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%s\",\n CommandOptionToMnemonic(MagickCompressOptions,(ssize_t)\n image->compression));\n break;\n }\n case 'D':\n {\n /*\n Image dispose method.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%s\",\n CommandOptionToMnemonic(MagickDisposeOptions,(ssize_t) image->dispose));\n break;\n }\n case 'F':\n {\n const char\n *q;\n\n register char\n *p;\n\n static char\n whitelist[] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 \"\n \"$-_.+!*'(),{}|\\\\^~[]`\\\"><#%;/?:@&=\";\n\n /*\n Magick filename (sanitized) - filename given incl. coder & read mods.\n */\n (void) CopyMagickString(value,image->magick_filename,MaxTextExtent);\n p=value;\n q=value+strlen(value);\n for (p+=strspn(p,whitelist); p != q; p+=strspn(p,whitelist))\n *p='_';\n break;\n }\n case 'G':\n {\n /*\n Image size as geometry = \"%wx%h\".\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20gx%.20g\",(double)\n image->magick_columns,(double) image->magick_rows);\n break;\n }\n case 'H':\n {\n /*\n Layer canvas height.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->page.height);\n break;\n }\n case 'M':\n {\n /*\n Magick filename - filename given incl. coder & read mods.\n */\n string=image->magick_filename;\n break;\n }\n case 'O':\n {\n /*\n Layer canvas offset with sign = \"+%X+%Y\".\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%+ld%+ld\",(long)\n image->page.x,(long) image->page.y);\n break;\n }\n case 'P':\n {\n /*\n Layer canvas page size = \"%Wx%H\".\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20gx%.20g\",(double)\n image->page.width,(double) image->page.height);\n break;\n }\n case 'Q':\n {\n /*\n Image compression quality.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n (image->quality == 0 ? 92 : image->quality));\n break;\n }\n case 'S':\n {\n /*\n Image scenes.\n */\n WarnNoImageInfoReturn(\"\\\"%%%c\\\"\",letter);\n if (image_info->number_scenes == 0)\n string=\"2147483647\";\n else\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image_info->scene+image_info->number_scenes);\n break;\n }\n case 'T':\n {\n /*\n Image time delay for animations.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->delay);\n break;\n }\n case 'U':\n {\n /*\n Image resolution units.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%s\",\n CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t)\n image->units));\n break;\n }\n case 'W':\n {\n /*\n Layer canvas width.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20g\",(double)\n image->page.width);\n break;\n }\n case 'X':\n {\n /*\n Layer canvas X offset.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%+.20g\",(double)\n image->page.x);\n break;\n }\n case 'Y':\n {\n /*\n Layer canvas Y offset.\n */\n (void) FormatLocaleString(value,MaxTextExtent,\"%+.20g\",(double)\n image->page.y);\n break;\n }\n case 'Z':\n {\n /*\n Zero filename.\n */\n WarnNoImageInfoReturn(\"\\\"%%%c\\\"\",letter);\n string=image_info->zero;\n break;\n }\n case '@':\n {\n RectangleInfo\n page;\n\n /*\n Image bounding box.\n */\n page=GetImageBoundingBox(image,&image->exception);\n (void) FormatLocaleString(value,MaxTextExtent,\"%.20gx%.20g%+.20g%+.20g\",\n (double) page.width,(double) page.height,(double) page.x,(double)\n page.y);\n break;\n }\n case '#':\n {\n /*\n Image signature.\n */\n if ((image->columns != 0) && (image->rows != 0))\n (void) SignatureImage(image);\n string=GetImageProperty(image,\"signature\");\n break;\n }\n case '%':\n {\n /*\n Percent escaped.\n */\n string=\"%\";\n break;\n }\n }\n if (*value != '\\0')\n string=value;\n if (string != (char *) NULL)\n {\n (void) SetImageArtifact(image,\"get-property\",string);\n return(GetImageArtifact(image,\"get-property\"));\n }\n return((char *) NULL);\n}", "project": "ImageMagick6", "hash": 207668242379766768614404100976312119040, "size": 475, "commit_id": "5bf7ff59c8ada957d6a681a0a2cc29f3813ad4bc", "message": "https://github.com/ImageMagick/ImageMagick/issues/1225", "target": 0, "dataset": "other", "idx": 462960}
  957. {"func": "formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)\n{\n Buffer save;\n char *p;\n int spos, epos, rows, c_rows, pos, col = 0;\n Line *l;\n\n copyBuffer(&save, buf);\n gotoLine(buf, a->start.line);\n switch (form->type) {\n case FORM_TEXTAREA:\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n#endif\t\t\t\t/* MENU_SELECT */\n\tspos = a->start.pos;\n\tepos = a->end.pos;\n\tbreak;\n default:\n\tspos = a->start.pos + 1;\n\tepos = a->end.pos - 1;\n }\n switch (form->type) {\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n\tif (spos >= buf->currentLine->len || spos < 0)\n\t break;\n\tif (form->checked)\n\t buf->currentLine->lineBuf[spos] = '*';\n\telse\n\t buf->currentLine->lineBuf[spos] = ' ';\n\tbreak;\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_TEXTAREA:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n\tif (form->type == FORM_SELECT) {\n\t p = form->label->ptr;\n\t updateSelectOption(form, form->select_option);\n\t}\n\telse\n#endif\t\t\t\t/* MENU_SELECT */\n\t{\n\t if (!form->value)\n\t\tbreak;\n\t p = form->value->ptr;\n\t}\n\tl = buf->currentLine;\n\tif (!l)\n\t break;\n\tif (form->type == FORM_TEXTAREA) {\n\t int n = a->y - buf->currentLine->linenumber;\n\t if (n > 0)\n\t\tfor (; l && n; l = l->prev, n--) ;\n\t else if (n < 0)\n\t\tfor (; l && n; l = l->prev, n++) ;\n\t if (!l)\n\t\tbreak;\n\t}\n\trows = form->rows ? form->rows : 1;\n\tcol = COLPOS(l, a->start.pos);\n\tfor (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {\n\t if (rows > 1) {\n\t\tpos = columnPos(l, col);\n\t\ta = retrieveAnchor(buf->formitem, l->linenumber, pos);\n\t\tif (a == NULL)\n\t\t break;\n\t\tspos = a->start.pos;\n\t\tepos = a->end.pos;\n\t }\n\t if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0)\n\t\tbreak;\n\t pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,\n\t\t\t\t rows > 1,\n\t\t\t\t form->type == FORM_INPUT_PASSWORD);\n\t if (pos != epos) {\n\t\tshiftAnchorPosition(buf->href, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->name, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->img, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->formitem, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t }\n\t}\n\tbreak;\n }\n copyBuffer(buf, &save);\n arrangeLine(buf);\n}", "project": "w3m", "hash": 15956644405726083189492084201505214654, "size": 97, "commit_id": "e2c7ecec6f9b730ad3c9bf8c8df9212970f183d7", "message": "Prevent dereference near-null pointer in formUpdateBuffer\n\nBug-Debian: https://github.com/tats/w3m/issues/35", "target": 1, "dataset": "other", "idx": 212915}
  958. {"func": "formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)\n{\n Buffer save;\n char *p;\n int spos, epos, rows, c_rows, pos, col = 0;\n Line *l;\n\n copyBuffer(&save, buf);\n gotoLine(buf, a->start.line);\n switch (form->type) {\n case FORM_TEXTAREA:\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n#endif\t\t\t\t/* MENU_SELECT */\n\tspos = a->start.pos;\n\tepos = a->end.pos;\n\tbreak;\n default:\n\tspos = a->start.pos + 1;\n\tepos = a->end.pos - 1;\n }\n switch (form->type) {\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n\tif (buf->currentLine == NULL ||\n\t spos >= buf->currentLine->len || spos < 0)\n\t break;\n\tif (form->checked)\n\t buf->currentLine->lineBuf[spos] = '*';\n\telse\n\t buf->currentLine->lineBuf[spos] = ' ';\n\tbreak;\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_TEXTAREA:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n\tif (form->type == FORM_SELECT) {\n\t p = form->label->ptr;\n\t updateSelectOption(form, form->select_option);\n\t}\n\telse\n#endif\t\t\t\t/* MENU_SELECT */\n\t{\n\t if (!form->value)\n\t\tbreak;\n\t p = form->value->ptr;\n\t}\n\tl = buf->currentLine;\n\tif (!l)\n\t break;\n\tif (form->type == FORM_TEXTAREA) {\n\t int n = a->y - buf->currentLine->linenumber;\n\t if (n > 0)\n\t\tfor (; l && n; l = l->prev, n--) ;\n\t else if (n < 0)\n\t\tfor (; l && n; l = l->prev, n++) ;\n\t if (!l)\n\t\tbreak;\n\t}\n\trows = form->rows ? form->rows : 1;\n\tcol = COLPOS(l, a->start.pos);\n\tfor (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {\n\t if (rows > 1) {\n\t\tpos = columnPos(l, col);\n\t\ta = retrieveAnchor(buf->formitem, l->linenumber, pos);\n\t\tif (a == NULL)\n\t\t break;\n\t\tspos = a->start.pos;\n\t\tepos = a->end.pos;\n\t }\n\t if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0)\n\t\tbreak;\n\t pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,\n\t\t\t\t rows > 1,\n\t\t\t\t form->type == FORM_INPUT_PASSWORD);\n\t if (pos != epos) {\n\t\tshiftAnchorPosition(buf->href, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->name, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->img, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->formitem, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t }\n\t}\n\tbreak;\n }\n copyBuffer(buf, &save);\n arrangeLine(buf);\n}", "project": "w3m", "hash": 45577909683508718942973794972642241617, "size": 98, "commit_id": "e2c7ecec6f9b730ad3c9bf8c8df9212970f183d7", "message": "Prevent dereference near-null pointer in formUpdateBuffer\n\nBug-Debian: https://github.com/tats/w3m/issues/35", "target": 0, "dataset": "other", "idx": 463013}
  959. {"func": "void sev_vm_destroy(struct kvm *kvm)\n{\n\tstruct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;\n\tstruct list_head *head = &sev->regions_list;\n\tstruct list_head *pos, *q;\n\n\tif (!sev_guest(kvm))\n\t\treturn;\n\n\tmutex_lock(&kvm->lock);\n\n\t/*\n\t * Ensure that all guest tagged cache entries are flushed before\n\t * releasing the pages back to the system for use. CLFLUSH will\n\t * not do this, so issue a WBINVD.\n\t */\n\twbinvd_on_all_cpus();\n\n\t/*\n\t * if userspace was terminated before unregistering the memory regions\n\t * then lets unpin all the registered memory.\n\t */\n\tif (!list_empty(head)) {\n\t\tlist_for_each_safe(pos, q, head) {\n\t\t\t__unregister_enc_region_locked(kvm,\n\t\t\t\tlist_entry(pos, struct enc_region, list));\n\t\t}\n\t}\n\n\tmutex_unlock(&kvm->lock);\n\n\tsev_unbind_asid(kvm, sev->handle);\n\tsev_asid_free(sev->asid);\n}", "project": "linux", "hash": 59854663405289045336965850461540245489, "size": 34, "commit_id": "7be74942f184fdfba34ddd19a0d995deb34d4a03", "message": "KVM: SVM: Periodically schedule when unregistering regions on destroy\n\nThere may be many encrypted regions that need to be unregistered when a\nSEV VM is destroyed. This can lead to soft lockups. For example, on a\nhost running 4.15:\n\nwatchdog: BUG: soft lockup - CPU#206 stuck for 11s! [t_virtual_machi:194348]\nCPU: 206 PID: 194348 Comm: t_virtual_machi\nRIP: 0010:free_unref_page_list+0x105/0x170\n...\nCall Trace:\n [<0>] release_pages+0x159/0x3d0\n [<0>] sev_unpin_memory+0x2c/0x50 [kvm_amd]\n [<0>] __unregister_enc_region_locked+0x2f/0x70 [kvm_amd]\n [<0>] svm_vm_destroy+0xa9/0x200 [kvm_amd]\n [<0>] kvm_arch_destroy_vm+0x47/0x200\n [<0>] kvm_put_kvm+0x1a8/0x2f0\n [<0>] kvm_vm_release+0x25/0x30\n [<0>] do_exit+0x335/0xc10\n [<0>] do_group_exit+0x3f/0xa0\n [<0>] get_signal+0x1bc/0x670\n [<0>] do_signal+0x31/0x130\n\nAlthough the CLFLUSH is no longer issued on every encrypted region to be\nunregistered, there are no other changes that can prevent soft lockups for\nvery large SEV VMs in the latest kernel.\n\nPeriodically schedule if necessary. This still holds kvm->lock across the\nresched, but since this only happens when the VM is destroyed this is\nassumed to be acceptable.\n\nSigned-off-by: David Rientjes <rientjes@google.com>\nMessage-Id: <alpine.DEB.2.23.453.2008251255240.2987727@chino.kir.corp.google.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 1, "dataset": "other", "idx": 212916}
  960. {"func": "void sev_vm_destroy(struct kvm *kvm)\n{\n\tstruct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;\n\tstruct list_head *head = &sev->regions_list;\n\tstruct list_head *pos, *q;\n\n\tif (!sev_guest(kvm))\n\t\treturn;\n\n\tmutex_lock(&kvm->lock);\n\n\t/*\n\t * Ensure that all guest tagged cache entries are flushed before\n\t * releasing the pages back to the system for use. CLFLUSH will\n\t * not do this, so issue a WBINVD.\n\t */\n\twbinvd_on_all_cpus();\n\n\t/*\n\t * if userspace was terminated before unregistering the memory regions\n\t * then lets unpin all the registered memory.\n\t */\n\tif (!list_empty(head)) {\n\t\tlist_for_each_safe(pos, q, head) {\n\t\t\t__unregister_enc_region_locked(kvm,\n\t\t\t\tlist_entry(pos, struct enc_region, list));\n\t\t\tcond_resched();\n\t\t}\n\t}\n\n\tmutex_unlock(&kvm->lock);\n\n\tsev_unbind_asid(kvm, sev->handle);\n\tsev_asid_free(sev->asid);\n}", "project": "linux", "hash": 32944969904859958026118495600871042845, "size": 35, "commit_id": "7be74942f184fdfba34ddd19a0d995deb34d4a03", "message": "KVM: SVM: Periodically schedule when unregistering regions on destroy\n\nThere may be many encrypted regions that need to be unregistered when a\nSEV VM is destroyed. This can lead to soft lockups. For example, on a\nhost running 4.15:\n\nwatchdog: BUG: soft lockup - CPU#206 stuck for 11s! [t_virtual_machi:194348]\nCPU: 206 PID: 194348 Comm: t_virtual_machi\nRIP: 0010:free_unref_page_list+0x105/0x170\n...\nCall Trace:\n [<0>] release_pages+0x159/0x3d0\n [<0>] sev_unpin_memory+0x2c/0x50 [kvm_amd]\n [<0>] __unregister_enc_region_locked+0x2f/0x70 [kvm_amd]\n [<0>] svm_vm_destroy+0xa9/0x200 [kvm_amd]\n [<0>] kvm_arch_destroy_vm+0x47/0x200\n [<0>] kvm_put_kvm+0x1a8/0x2f0\n [<0>] kvm_vm_release+0x25/0x30\n [<0>] do_exit+0x335/0xc10\n [<0>] do_group_exit+0x3f/0xa0\n [<0>] get_signal+0x1bc/0x670\n [<0>] do_signal+0x31/0x130\n\nAlthough the CLFLUSH is no longer issued on every encrypted region to be\nunregistered, there are no other changes that can prevent soft lockups for\nvery large SEV VMs in the latest kernel.\n\nPeriodically schedule if necessary. This still holds kvm->lock across the\nresched, but since this only happens when the VM is destroyed this is\nassumed to be acceptable.\n\nSigned-off-by: David Rientjes <rientjes@google.com>\nMessage-Id: <alpine.DEB.2.23.453.2008251255240.2987727@chino.kir.corp.google.com>\nSigned-off-by: Paolo Bonzini <pbonzini@redhat.com>", "target": 0, "dataset": "other", "idx": 463016}
  961. {"func": "static void ttm_put_pages(struct page **pages, unsigned npages, int flags,\n\t\t\t enum ttm_caching_state cstate)\n{\n\tstruct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\tstruct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);\n#endif\n\tunsigned long irq_flags;\n\tunsigned i;\n\n\tif (pool == NULL) {\n\t\t/* No pool for this memory type so free the pages */\n\t\ti = 0;\n\t\twhile (i < npages) {\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\t\t\tstruct page *p = pages[i];\n#endif\n\t\t\tunsigned order = 0, j;\n\n\t\t\tif (!pages[i]) {\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\t\t\tif (!(flags & TTM_PAGE_FLAG_DMA32) &&\n\t\t\t (npages - i) >= HPAGE_PMD_NR) {\n\t\t\t\tfor (j = 1; j < HPAGE_PMD_NR; ++j)\n\t\t\t\t\tif (p++ != pages[i + j])\n\t\t\t\t\t break;\n\n\t\t\t\tif (j == HPAGE_PMD_NR)\n\t\t\t\t\torder = HPAGE_PMD_ORDER;\n\t\t\t}\n#endif\n\n\t\t\tif (page_count(pages[i]) != 1)\n\t\t\t\tpr_err(\"Erroneous page count. Leaking pages.\\n\");\n\t\t\t__free_pages(pages[i], order);\n\n\t\t\tj = 1 << order;\n\t\t\twhile (j) {\n\t\t\t\tpages[i++] = NULL;\n\t\t\t\t--j;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\n\ti = 0;\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\tif (huge) {\n\t\tunsigned max_size, n2free;\n\n\t\tspin_lock_irqsave(&huge->lock, irq_flags);\n\t\twhile ((npages - i) >= HPAGE_PMD_NR) {\n\t\t\tstruct page *p = pages[i];\n\t\t\tunsigned j;\n\n\t\t\tif (!p)\n\t\t\t\tbreak;\n\n\t\t\tfor (j = 1; j < HPAGE_PMD_NR; ++j)\n\t\t\t\tif (p++ != pages[i + j])\n\t\t\t\t break;\n\n\t\t\tif (j != HPAGE_PMD_NR)\n\t\t\t\tbreak;\n\n\t\t\tlist_add_tail(&pages[i]->lru, &huge->list);\n\n\t\t\tfor (j = 0; j < HPAGE_PMD_NR; ++j)\n\t\t\t\tpages[i++] = NULL;\n\t\t\thuge->npages++;\n\t\t}\n\n\t\t/* Check that we don't go over the pool limit */\n\t\tmax_size = _manager->options.max_size;\n\t\tmax_size /= HPAGE_PMD_NR;\n\t\tif (huge->npages > max_size)\n\t\t\tn2free = huge->npages - max_size;\n\t\telse\n\t\t\tn2free = 0;\n\t\tspin_unlock_irqrestore(&huge->lock, irq_flags);\n\t\tif (n2free)\n\t\t\tttm_page_pool_free(huge, n2free, false);\n\t}\n#endif\n\n\tspin_lock_irqsave(&pool->lock, irq_flags);\n\twhile (i < npages) {\n\t\tif (pages[i]) {\n\t\t\tif (page_count(pages[i]) != 1)\n\t\t\t\tpr_err(\"Erroneous page count. Leaking pages.\\n\");\n\t\t\tlist_add_tail(&pages[i]->lru, &pool->list);\n\t\t\tpages[i] = NULL;\n\t\t\tpool->npages++;\n\t\t}\n\t\t++i;\n\t}\n\t/* Check that we don't go over the pool limit */\n\tnpages = 0;\n\tif (pool->npages > _manager->options.max_size) {\n\t\tnpages = pool->npages - _manager->options.max_size;\n\t\t/* free at least NUM_PAGES_TO_ALLOC number of pages\n\t\t * to reduce calls to set_memory_wb */\n\t\tif (npages < NUM_PAGES_TO_ALLOC)\n\t\t\tnpages = NUM_PAGES_TO_ALLOC;\n\t}\n\tspin_unlock_irqrestore(&pool->lock, irq_flags);\n\tif (npages)\n\t\tttm_page_pool_free(pool, npages, false);\n}", "project": "linux", "hash": 193657400577846816147392268052783548278, "size": 113, "commit_id": "453393369dc9806d2455151e329c599684762428", "message": "drm/ttm: fix incrementing the page pointer for huge pages\n\nWhen we increment the counter we need to increment the pointer as well.\n\nSigned-off-by: Christian K\u00f6nig <christian.koenig@amd.com>\nFixes: e16858a7e6e7 drm/ttm: fix start page for huge page check in ttm_put_pages()\nReviewed-by: Michel D\u00e4nzer <michel.daenzer@amd.com>\nAcked-by: Huang Rui <ray.huang@amd.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 1, "dataset": "other", "idx": 212944}
  962. {"func": "static void ttm_put_pages(struct page **pages, unsigned npages, int flags,\n\t\t\t enum ttm_caching_state cstate)\n{\n\tstruct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\tstruct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);\n#endif\n\tunsigned long irq_flags;\n\tunsigned i;\n\n\tif (pool == NULL) {\n\t\t/* No pool for this memory type so free the pages */\n\t\ti = 0;\n\t\twhile (i < npages) {\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\t\t\tstruct page *p = pages[i];\n#endif\n\t\t\tunsigned order = 0, j;\n\n\t\t\tif (!pages[i]) {\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\t\t\tif (!(flags & TTM_PAGE_FLAG_DMA32) &&\n\t\t\t (npages - i) >= HPAGE_PMD_NR) {\n\t\t\t\tfor (j = 1; j < HPAGE_PMD_NR; ++j)\n\t\t\t\t\tif (++p != pages[i + j])\n\t\t\t\t\t break;\n\n\t\t\t\tif (j == HPAGE_PMD_NR)\n\t\t\t\t\torder = HPAGE_PMD_ORDER;\n\t\t\t}\n#endif\n\n\t\t\tif (page_count(pages[i]) != 1)\n\t\t\t\tpr_err(\"Erroneous page count. Leaking pages.\\n\");\n\t\t\t__free_pages(pages[i], order);\n\n\t\t\tj = 1 << order;\n\t\t\twhile (j) {\n\t\t\t\tpages[i++] = NULL;\n\t\t\t\t--j;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\n\ti = 0;\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\tif (huge) {\n\t\tunsigned max_size, n2free;\n\n\t\tspin_lock_irqsave(&huge->lock, irq_flags);\n\t\twhile ((npages - i) >= HPAGE_PMD_NR) {\n\t\t\tstruct page *p = pages[i];\n\t\t\tunsigned j;\n\n\t\t\tif (!p)\n\t\t\t\tbreak;\n\n\t\t\tfor (j = 1; j < HPAGE_PMD_NR; ++j)\n\t\t\t\tif (++p != pages[i + j])\n\t\t\t\t break;\n\n\t\t\tif (j != HPAGE_PMD_NR)\n\t\t\t\tbreak;\n\n\t\t\tlist_add_tail(&pages[i]->lru, &huge->list);\n\n\t\t\tfor (j = 0; j < HPAGE_PMD_NR; ++j)\n\t\t\t\tpages[i++] = NULL;\n\t\t\thuge->npages++;\n\t\t}\n\n\t\t/* Check that we don't go over the pool limit */\n\t\tmax_size = _manager->options.max_size;\n\t\tmax_size /= HPAGE_PMD_NR;\n\t\tif (huge->npages > max_size)\n\t\t\tn2free = huge->npages - max_size;\n\t\telse\n\t\t\tn2free = 0;\n\t\tspin_unlock_irqrestore(&huge->lock, irq_flags);\n\t\tif (n2free)\n\t\t\tttm_page_pool_free(huge, n2free, false);\n\t}\n#endif\n\n\tspin_lock_irqsave(&pool->lock, irq_flags);\n\twhile (i < npages) {\n\t\tif (pages[i]) {\n\t\t\tif (page_count(pages[i]) != 1)\n\t\t\t\tpr_err(\"Erroneous page count. Leaking pages.\\n\");\n\t\t\tlist_add_tail(&pages[i]->lru, &pool->list);\n\t\t\tpages[i] = NULL;\n\t\t\tpool->npages++;\n\t\t}\n\t\t++i;\n\t}\n\t/* Check that we don't go over the pool limit */\n\tnpages = 0;\n\tif (pool->npages > _manager->options.max_size) {\n\t\tnpages = pool->npages - _manager->options.max_size;\n\t\t/* free at least NUM_PAGES_TO_ALLOC number of pages\n\t\t * to reduce calls to set_memory_wb */\n\t\tif (npages < NUM_PAGES_TO_ALLOC)\n\t\t\tnpages = NUM_PAGES_TO_ALLOC;\n\t}\n\tspin_unlock_irqrestore(&pool->lock, irq_flags);\n\tif (npages)\n\t\tttm_page_pool_free(pool, npages, false);\n}", "project": "linux", "hash": 326634532465872425758167027077494247468, "size": 113, "commit_id": "453393369dc9806d2455151e329c599684762428", "message": "drm/ttm: fix incrementing the page pointer for huge pages\n\nWhen we increment the counter we need to increment the pointer as well.\n\nSigned-off-by: Christian K\u00f6nig <christian.koenig@amd.com>\nFixes: e16858a7e6e7 drm/ttm: fix start page for huge page check in ttm_put_pages()\nReviewed-by: Michel D\u00e4nzer <michel.daenzer@amd.com>\nAcked-by: Huang Rui <ray.huang@amd.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 0, "dataset": "other", "idx": 463460}
  963. {"func": "ciphertext_to_compressed (gnutls_session_t session,\n gnutls_datum_t *ciphertext, \n uint8_t * compress_data,\n int compress_size,\n uint8_t type, record_parameters_st * params, \n uint64* sequence)\n{\n uint8_t tag[MAX_HASH_SIZE];\n uint8_t pad;\n int length, length_to_decrypt;\n uint16_t blocksize;\n int ret, i, pad_failed = 0;\n uint8_t preamble[MAX_PREAMBLE_SIZE];\n unsigned int preamble_size;\n unsigned int ver = gnutls_protocol_get_version (session);\n unsigned int tag_size = _gnutls_auth_cipher_tag_len (&params->read.cipher_state);\n unsigned int explicit_iv = _gnutls_version_has_explicit_iv (session->security_parameters.version);\n\n blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);\n\n /* actual decryption (inplace)\n */\n switch (_gnutls_cipher_is_block (params->cipher_algorithm))\n {\n case CIPHER_STREAM:\n /* The way AEAD ciphers are defined in RFC5246, it allows\n * only stream ciphers.\n */\n if (explicit_iv && _gnutls_auth_cipher_is_aead(&params->read.cipher_state))\n {\n uint8_t nonce[blocksize];\n /* Values in AEAD are pretty fixed in TLS 1.2 for 128-bit block\n */\n if (params->read.IV.data == NULL || params->read.IV.size != 4)\n return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);\n \n if (ciphertext->size < tag_size+AEAD_EXPLICIT_DATA_SIZE)\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n\n memcpy(nonce, params->read.IV.data, AEAD_IMPLICIT_DATA_SIZE);\n memcpy(&nonce[AEAD_IMPLICIT_DATA_SIZE], ciphertext->data, AEAD_EXPLICIT_DATA_SIZE);\n \n _gnutls_auth_cipher_setiv(&params->read.cipher_state, nonce, AEAD_EXPLICIT_DATA_SIZE+AEAD_IMPLICIT_DATA_SIZE);\n\n ciphertext->data += AEAD_EXPLICIT_DATA_SIZE;\n ciphertext->size -= AEAD_EXPLICIT_DATA_SIZE;\n \n length_to_decrypt = ciphertext->size - tag_size;\n }\n else\n {\n if (ciphertext->size < tag_size)\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n \n length_to_decrypt = ciphertext->size;\n }\n\n length = ciphertext->size - tag_size;\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n preamble_size =\n make_preamble (UINT64DATA(*sequence), type,\n length, ver, preamble);\n\n ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, preamble, preamble_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n if ((ret =\n _gnutls_auth_cipher_decrypt2 (&params->read.cipher_state,\n ciphertext->data, length_to_decrypt,\n ciphertext->data, ciphertext->size)) < 0)\n return gnutls_assert_val(ret);\n\n break;\n case CIPHER_BLOCK:\n if (ciphertext->size < MAX(blocksize, tag_size) || (ciphertext->size % blocksize != 0))\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n\n /* ignore the IV in TLS 1.1+\n */\n if (explicit_iv)\n {\n _gnutls_auth_cipher_setiv(&params->read.cipher_state,\n ciphertext->data, blocksize);\n\n ciphertext->size -= blocksize;\n ciphertext->data += blocksize;\n\n if (ciphertext->size == 0)\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n }\n\n /* we don't use the auth_cipher interface here, since\n * TLS with block ciphers is impossible to be used under such\n * an API. (the length of plaintext is required to calculate\n * auth_data, but it is not available before decryption).\n */\n if ((ret =\n _gnutls_cipher_decrypt (&params->read.cipher_state.cipher,\n ciphertext->data, ciphertext->size)) < 0)\n return gnutls_assert_val(ret);\n\n pad = ciphertext->data[ciphertext->size - 1] + 1; /* pad */\n\n if ((int) pad > (int) ciphertext->size - tag_size)\n {\n gnutls_assert ();\n _gnutls_record_log\n (\"REC[%p]: Short record length %d > %d - %d (under attack?)\\n\",\n session, pad, ciphertext->size, tag_size);\n /* We do not fail here. We check below for the\n * the pad_failed. If zero means success.\n */\n pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n pad %= blocksize;\n }\n\n length = ciphertext->size - tag_size - pad;\n\n /* Check the pading bytes (TLS 1.x)\n */\n if (ver != GNUTLS_SSL3)\n for (i = 2; i < pad; i++)\n {\n if (ciphertext->data[ciphertext->size - i] !=\n ciphertext->data[ciphertext->size - 1])\n pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n }\n\n if (length < 0)\n {\n /* Setting a proper length to prevent timing differences in\n * processing of records with invalid encryption.\n */\n length = ciphertext->size - tag_size;\n }\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n preamble_size =\n make_preamble (UINT64DATA(*sequence), type,\n length, ver, preamble);\n ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, preamble, preamble_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, ciphertext->data, length);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n break;\n default:\n return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);\n }\n\n ret = _gnutls_auth_cipher_tag(&params->read.cipher_state, tag, tag_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n /* This one was introduced to avoid a timing attack against the TLS\n * 1.0 protocol.\n */\n /* HMAC was not the same. \n */\n if (memcmp (tag, &ciphertext->data[length], tag_size) != 0 || pad_failed != 0)\n return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED);\n\n /* copy the decrypted stuff to compress_data.\n */\n if (compress_size < length)\n return gnutls_assert_val(GNUTLS_E_DECOMPRESSION_FAILED);\n\n if (compress_data != ciphertext->data)\n memcpy (compress_data, ciphertext->data, length);\n\n return length;\n}", "project": "gnutls", "hash": 259478820528968398998523761592348550013, "size": 184, "commit_id": "b495740f2ff66550ca9395b3fda3ea32c3acb185", "message": "changes in packet parsing.", "target": 1, "dataset": "other", "idx": 213025}
  964. {"func": "ciphertext_to_compressed (gnutls_session_t session,\n gnutls_datum_t *ciphertext, \n uint8_t * compress_data,\n int compress_size,\n uint8_t type, record_parameters_st * params, \n uint64* sequence)\n{\n uint8_t tag[MAX_HASH_SIZE];\n uint8_t pad;\n int length, length_to_decrypt;\n uint16_t blocksize;\n int ret, i, pad_failed = 0;\n uint8_t preamble[MAX_PREAMBLE_SIZE];\n unsigned int preamble_size;\n unsigned int ver = gnutls_protocol_get_version (session);\n unsigned int tag_size = _gnutls_auth_cipher_tag_len (&params->read.cipher_state);\n unsigned int explicit_iv = _gnutls_version_has_explicit_iv (session->security_parameters.version);\n\n blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);\n\n /* actual decryption (inplace)\n */\n switch (_gnutls_cipher_is_block (params->cipher_algorithm))\n {\n case CIPHER_STREAM:\n /* The way AEAD ciphers are defined in RFC5246, it allows\n * only stream ciphers.\n */\n if (explicit_iv && _gnutls_auth_cipher_is_aead(&params->read.cipher_state))\n {\n uint8_t nonce[blocksize];\n /* Values in AEAD are pretty fixed in TLS 1.2 for 128-bit block\n */\n if (params->read.IV.data == NULL || params->read.IV.size != 4)\n return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);\n \n if (ciphertext->size < tag_size+AEAD_EXPLICIT_DATA_SIZE)\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n\n memcpy(nonce, params->read.IV.data, AEAD_IMPLICIT_DATA_SIZE);\n memcpy(&nonce[AEAD_IMPLICIT_DATA_SIZE], ciphertext->data, AEAD_EXPLICIT_DATA_SIZE);\n \n _gnutls_auth_cipher_setiv(&params->read.cipher_state, nonce, AEAD_EXPLICIT_DATA_SIZE+AEAD_IMPLICIT_DATA_SIZE);\n\n ciphertext->data += AEAD_EXPLICIT_DATA_SIZE;\n ciphertext->size -= AEAD_EXPLICIT_DATA_SIZE;\n \n length_to_decrypt = ciphertext->size - tag_size;\n }\n else\n {\n if (ciphertext->size < tag_size)\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n \n length_to_decrypt = ciphertext->size;\n }\n\n length = ciphertext->size - tag_size;\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n preamble_size =\n make_preamble (UINT64DATA(*sequence), type,\n length, ver, preamble);\n\n ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, preamble, preamble_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n if ((ret =\n _gnutls_auth_cipher_decrypt2 (&params->read.cipher_state,\n ciphertext->data, length_to_decrypt,\n ciphertext->data, ciphertext->size)) < 0)\n return gnutls_assert_val(ret);\n\n break;\n case CIPHER_BLOCK:\n if (ciphertext->size < blocksize || (ciphertext->size % blocksize != 0))\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n\n /* ignore the IV in TLS 1.1+\n */\n if (explicit_iv)\n {\n _gnutls_auth_cipher_setiv(&params->read.cipher_state,\n ciphertext->data, blocksize);\n\n ciphertext->size -= blocksize;\n ciphertext->data += blocksize;\n }\n\n if (ciphertext->size < tag_size)\n return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED);\n\n /* we don't use the auth_cipher interface here, since\n * TLS with block ciphers is impossible to be used under such\n * an API. (the length of plaintext is required to calculate\n * auth_data, but it is not available before decryption).\n */\n if ((ret =\n _gnutls_cipher_decrypt (&params->read.cipher_state.cipher,\n ciphertext->data, ciphertext->size)) < 0)\n return gnutls_assert_val(ret);\n\n pad = ciphertext->data[ciphertext->size - 1] + 1; /* pad */\n\n\n if ((int) pad > (int) ciphertext->size - tag_size)\n {\n gnutls_assert ();\n _gnutls_record_log\n (\"REC[%p]: Short record length %d > %d - %d (under attack?)\\n\",\n session, pad, ciphertext->size, tag_size);\n /* We do not fail here. We check below for the\n * the pad_failed. If zero means success.\n */\n pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n pad %= blocksize;\n }\n\n length = ciphertext->size - tag_size - pad;\n\n /* Check the pading bytes (TLS 1.x)\n */\n if (ver != GNUTLS_SSL3)\n for (i = 2; i < pad; i++)\n {\n if (ciphertext->data[ciphertext->size - i] !=\n ciphertext->data[ciphertext->size - 1])\n pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n }\n\n if (length < 0)\n {\n /* Setting a proper length to prevent timing differences in\n * processing of records with invalid encryption.\n */\n length = ciphertext->size - tag_size;\n }\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n preamble_size =\n make_preamble (UINT64DATA(*sequence), type,\n length, ver, preamble);\n ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, preamble, preamble_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, ciphertext->data, length);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n break;\n default:\n return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);\n }\n\n ret = _gnutls_auth_cipher_tag(&params->read.cipher_state, tag, tag_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n /* This one was introduced to avoid a timing attack against the TLS\n * 1.0 protocol.\n */\n /* HMAC was not the same. \n */\n if (memcmp (tag, &ciphertext->data[length], tag_size) != 0 || pad_failed != 0)\n return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED);\n\n /* copy the decrypted stuff to compress_data.\n */\n if (compress_size < length)\n return gnutls_assert_val(GNUTLS_E_DECOMPRESSION_FAILED);\n\n if (compress_data != ciphertext->data)\n memcpy (compress_data, ciphertext->data, length);\n\n return length;\n}", "project": "gnutls", "hash": 154589990996518600118997836491749802345, "size": 182, "commit_id": "b495740f2ff66550ca9395b3fda3ea32c3acb185", "message": "changes in packet parsing.", "target": 0, "dataset": "other", "idx": 464938}
  965. {"func": "table_regex_match(const char *string, const char *pattern)\n{\n\tregex_t preg;\n\tint\tcflags = REG_EXTENDED|REG_NOSUB;\n\n\tif (strncmp(pattern, \"(?i)\", 4) == 0) {\n\t\tcflags |= REG_ICASE;\n\t\tpattern += 4;\n\t}\n\n\tif (regcomp(&preg, pattern, cflags) != 0)\n\t\treturn (0);\n\n\tif (regexec(&preg, string, 0, NULL, 0) != 0)\n\t\treturn (0);\n\n\treturn (1);\n}", "project": "src", "hash": 134955981984600634024647053081479880826, "size": 18, "commit_id": "79a034b4aed29e965f45a13409268290c9910043", "message": "Use regfree after we're done with preg.\n\nFrom gilles@", "target": 1, "dataset": "other", "idx": 213469}
  966. {"func": "table_regex_match(const char *string, const char *pattern)\n{\n\tregex_t preg;\n\tint\tcflags = REG_EXTENDED|REG_NOSUB;\n\tint ret;\n\n\tif (strncmp(pattern, \"(?i)\", 4) == 0) {\n\t\tcflags |= REG_ICASE;\n\t\tpattern += 4;\n\t}\n\n\tif (regcomp(&preg, pattern, cflags) != 0)\n\t\treturn (0);\n\n\tret = regexec(&preg, string, 0, NULL, 0);\n\n\tregfree(&preg);\n\n\tif (ret != 0)\n\t\treturn (0);\n\n\treturn (1);\n}", "project": "src", "hash": 27915400491158450836907057889102967473, "size": 23, "commit_id": "79a034b4aed29e965f45a13409268290c9910043", "message": "Use regfree after we're done with preg.\n\nFrom gilles@", "target": 0, "dataset": "other", "idx": 468895}
  967. {"func": "static int __ip_append_data(struct sock *sk,\n\t\t\t struct flowi4 *fl4,\n\t\t\t struct sk_buff_head *queue,\n\t\t\t struct inet_cork *cork,\n\t\t\t struct page_frag *pfrag,\n\t\t\t int getfrag(void *from, char *to, int offset,\n\t\t\t\t\tint len, int odd, struct sk_buff *skb),\n\t\t\t void *from, int length, int transhdrlen,\n\t\t\t unsigned int flags)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct sk_buff *skb;\n\n\tstruct ip_options *opt = cork->opt;\n\tint hh_len;\n\tint exthdrlen;\n\tint mtu;\n\tint copy;\n\tint err;\n\tint offset = 0;\n\tunsigned int maxfraglen, fragheaderlen, maxnonfragsize;\n\tint csummode = CHECKSUM_NONE;\n\tstruct rtable *rt = (struct rtable *)cork->dst;\n\tu32 tskey = 0;\n\n\tskb = skb_peek_tail(queue);\n\n\texthdrlen = !skb ? rt->dst.header_len : 0;\n\tmtu = cork->fragsize;\n\tif (cork->tx_flags & SKBTX_ANY_SW_TSTAMP &&\n\t sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)\n\t\ttskey = sk->sk_tskey++;\n\n\thh_len = LL_RESERVED_SPACE(rt->dst.dev);\n\n\tfragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0);\n\tmaxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen;\n\tmaxnonfragsize = ip_sk_ignore_df(sk) ? 0xFFFF : mtu;\n\n\tif (cork->length + length > maxnonfragsize - fragheaderlen) {\n\t\tip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,\n\t\t\t mtu - (opt ? opt->optlen : 0));\n\t\treturn -EMSGSIZE;\n\t}\n\n\t/*\n\t * transhdrlen > 0 means that this is the first fragment and we wish\n\t * it won't be fragmented in the future.\n\t */\n\tif (transhdrlen &&\n\t length + fragheaderlen <= mtu &&\n\t rt->dst.dev->features & (NETIF_F_HW_CSUM | NETIF_F_IP_CSUM) &&\n\t !(flags & MSG_MORE) &&\n\t !exthdrlen)\n\t\tcsummode = CHECKSUM_PARTIAL;\n\n\tcork->length += length;\n\tif ((((length + (skb ? skb->len : fragheaderlen)) > mtu) ||\n\t (skb && skb_is_gso(skb))) &&\n\t (sk->sk_protocol == IPPROTO_UDP) &&\n\t (rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) &&\n\t (sk->sk_type == SOCK_DGRAM) && !sk->sk_no_check_tx) {\n\t\terr = ip_ufo_append_data(sk, queue, getfrag, from, length,\n\t\t\t\t\t hh_len, fragheaderlen, transhdrlen,\n\t\t\t\t\t maxfraglen, flags);\n\t\tif (err)\n\t\t\tgoto error;\n\t\treturn 0;\n\t}\n\n\t/* So, what's going on in the loop below?\n\t *\n\t * We use calculated fragment length to generate chained skb,\n\t * each of segments is IP fragment ready for sending to network after\n\t * adding appropriate IP header.\n\t */\n\n\tif (!skb)\n\t\tgoto alloc_new_skb;\n\n\twhile (length > 0) {\n\t\t/* Check if the remaining data fits into current packet. */\n\t\tcopy = mtu - skb->len;\n\t\tif (copy < length)\n\t\t\tcopy = maxfraglen - skb->len;\n\t\tif (copy <= 0) {\n\t\t\tchar *data;\n\t\t\tunsigned int datalen;\n\t\t\tunsigned int fraglen;\n\t\t\tunsigned int fraggap;\n\t\t\tunsigned int alloclen;\n\t\t\tstruct sk_buff *skb_prev;\nalloc_new_skb:\n\t\t\tskb_prev = skb;\n\t\t\tif (skb_prev)\n\t\t\t\tfraggap = skb_prev->len - maxfraglen;\n\t\t\telse\n\t\t\t\tfraggap = 0;\n\n\t\t\t/*\n\t\t\t * If remaining data exceeds the mtu,\n\t\t\t * we know we need more fragment(s).\n\t\t\t */\n\t\t\tdatalen = length + fraggap;\n\t\t\tif (datalen > mtu - fragheaderlen)\n\t\t\t\tdatalen = maxfraglen - fragheaderlen;\n\t\t\tfraglen = datalen + fragheaderlen;\n\n\t\t\tif ((flags & MSG_MORE) &&\n\t\t\t !(rt->dst.dev->features&NETIF_F_SG))\n\t\t\t\talloclen = mtu;\n\t\t\telse\n\t\t\t\talloclen = fraglen;\n\n\t\t\talloclen += exthdrlen;\n\n\t\t\t/* The last fragment gets additional space at tail.\n\t\t\t * Note, with MSG_MORE we overallocate on fragments,\n\t\t\t * because we have no idea what fragment will be\n\t\t\t * the last.\n\t\t\t */\n\t\t\tif (datalen == length + fraggap)\n\t\t\t\talloclen += rt->dst.trailer_len;\n\n\t\t\tif (transhdrlen) {\n\t\t\t\tskb = sock_alloc_send_skb(sk,\n\t\t\t\t\t\talloclen + hh_len + 15,\n\t\t\t\t\t\t(flags & MSG_DONTWAIT), &err);\n\t\t\t} else {\n\t\t\t\tskb = NULL;\n\t\t\t\tif (refcount_read(&sk->sk_wmem_alloc) <=\n\t\t\t\t 2 * sk->sk_sndbuf)\n\t\t\t\t\tskb = sock_wmalloc(sk,\n\t\t\t\t\t\t\t alloclen + hh_len + 15, 1,\n\t\t\t\t\t\t\t sk->sk_allocation);\n\t\t\t\tif (unlikely(!skb))\n\t\t\t\t\terr = -ENOBUFS;\n\t\t\t}\n\t\t\tif (!skb)\n\t\t\t\tgoto error;\n\n\t\t\t/*\n\t\t\t *\tFill in the control structures\n\t\t\t */\n\t\t\tskb->ip_summed = csummode;\n\t\t\tskb->csum = 0;\n\t\t\tskb_reserve(skb, hh_len);\n\n\t\t\t/* only the initial fragment is time stamped */\n\t\t\tskb_shinfo(skb)->tx_flags = cork->tx_flags;\n\t\t\tcork->tx_flags = 0;\n\t\t\tskb_shinfo(skb)->tskey = tskey;\n\t\t\ttskey = 0;\n\n\t\t\t/*\n\t\t\t *\tFind where to start putting bytes.\n\t\t\t */\n\t\t\tdata = skb_put(skb, fraglen + exthdrlen);\n\t\t\tskb_set_network_header(skb, exthdrlen);\n\t\t\tskb->transport_header = (skb->network_header +\n\t\t\t\t\t\t fragheaderlen);\n\t\t\tdata += fragheaderlen + exthdrlen;\n\n\t\t\tif (fraggap) {\n\t\t\t\tskb->csum = skb_copy_and_csum_bits(\n\t\t\t\t\tskb_prev, maxfraglen,\n\t\t\t\t\tdata + transhdrlen, fraggap, 0);\n\t\t\t\tskb_prev->csum = csum_sub(skb_prev->csum,\n\t\t\t\t\t\t\t skb->csum);\n\t\t\t\tdata += fraggap;\n\t\t\t\tpskb_trim_unique(skb_prev, maxfraglen);\n\t\t\t}\n\n\t\t\tcopy = datalen - transhdrlen - fraggap;\n\t\t\tif (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {\n\t\t\t\terr = -EFAULT;\n\t\t\t\tkfree_skb(skb);\n\t\t\t\tgoto error;\n\t\t\t}\n\n\t\t\toffset += copy;\n\t\t\tlength -= datalen - fraggap;\n\t\t\ttranshdrlen = 0;\n\t\t\texthdrlen = 0;\n\t\t\tcsummode = CHECKSUM_NONE;\n\n\t\t\tif ((flags & MSG_CONFIRM) && !skb_prev)\n\t\t\t\tskb_set_dst_pending_confirm(skb, 1);\n\n\t\t\t/*\n\t\t\t * Put the packet on the pending queue.\n\t\t\t */\n\t\t\t__skb_queue_tail(queue, skb);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (copy > length)\n\t\t\tcopy = length;\n\n\t\tif (!(rt->dst.dev->features&NETIF_F_SG)) {\n\t\t\tunsigned int off;\n\n\t\t\toff = skb->len;\n\t\t\tif (getfrag(from, skb_put(skb, copy),\n\t\t\t\t\toffset, copy, off, skb) < 0) {\n\t\t\t\t__skb_trim(skb, off);\n\t\t\t\terr = -EFAULT;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t} else {\n\t\t\tint i = skb_shinfo(skb)->nr_frags;\n\n\t\t\terr = -ENOMEM;\n\t\t\tif (!sk_page_frag_refill(sk, pfrag))\n\t\t\t\tgoto error;\n\n\t\t\tif (!skb_can_coalesce(skb, i, pfrag->page,\n\t\t\t\t\t pfrag->offset)) {\n\t\t\t\terr = -EMSGSIZE;\n\t\t\t\tif (i == MAX_SKB_FRAGS)\n\t\t\t\t\tgoto error;\n\n\t\t\t\t__skb_fill_page_desc(skb, i, pfrag->page,\n\t\t\t\t\t\t pfrag->offset, 0);\n\t\t\t\tskb_shinfo(skb)->nr_frags = ++i;\n\t\t\t\tget_page(pfrag->page);\n\t\t\t}\n\t\t\tcopy = min_t(int, copy, pfrag->size - pfrag->offset);\n\t\t\tif (getfrag(from,\n\t\t\t\t page_address(pfrag->page) + pfrag->offset,\n\t\t\t\t offset, copy, skb->len, skb) < 0)\n\t\t\t\tgoto error_efault;\n\n\t\t\tpfrag->offset += copy;\n\t\t\tskb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);\n\t\t\tskb->len += copy;\n\t\t\tskb->data_len += copy;\n\t\t\tskb->truesize += copy;\n\t\t\trefcount_add(copy, &sk->sk_wmem_alloc);\n\t\t}\n\t\toffset += copy;\n\t\tlength -= copy;\n\t}\n\n\treturn 0;\n\nerror_efault:\n\terr = -EFAULT;\nerror:\n\tcork->length -= length;\n\tIP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS);\n\treturn err;\n}", "project": "net", "hash": 322529707948405632291501247024639555798, "size": 253, "commit_id": "85f1bd9a7b5a79d5baa8bf44af19658f7bf77bfa", "message": "udp: consistently apply ufo or fragmentation\n\nWhen iteratively building a UDP datagram with MSG_MORE and that\ndatagram exceeds MTU, consistently choose UFO or fragmentation.\n\nOnce skb_is_gso, always apply ufo. Conversely, once a datagram is\nsplit across multiple skbs, do not consider ufo.\n\nSendpage already maintains the first invariant, only add the second.\nIPv6 does not have a sendpage implementation to modify.\n\nA gso skb must have a partial checksum, do not follow sk_no_check_tx\nin udp_send_skb.\n\nFound by syzkaller.\n\nFixes: e89e9cf539a2 (\"[IPv4/IPv6]: UFO Scatter-gather approach\")\nReported-by: Andrey Konovalov <andreyknvl@google.com>\nSigned-off-by: Willem de Bruijn <willemb@google.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 1, "dataset": "other", "idx": 213470}
  968. {"func": "static int __ip_append_data(struct sock *sk,\n\t\t\t struct flowi4 *fl4,\n\t\t\t struct sk_buff_head *queue,\n\t\t\t struct inet_cork *cork,\n\t\t\t struct page_frag *pfrag,\n\t\t\t int getfrag(void *from, char *to, int offset,\n\t\t\t\t\tint len, int odd, struct sk_buff *skb),\n\t\t\t void *from, int length, int transhdrlen,\n\t\t\t unsigned int flags)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct sk_buff *skb;\n\n\tstruct ip_options *opt = cork->opt;\n\tint hh_len;\n\tint exthdrlen;\n\tint mtu;\n\tint copy;\n\tint err;\n\tint offset = 0;\n\tunsigned int maxfraglen, fragheaderlen, maxnonfragsize;\n\tint csummode = CHECKSUM_NONE;\n\tstruct rtable *rt = (struct rtable *)cork->dst;\n\tu32 tskey = 0;\n\n\tskb = skb_peek_tail(queue);\n\n\texthdrlen = !skb ? rt->dst.header_len : 0;\n\tmtu = cork->fragsize;\n\tif (cork->tx_flags & SKBTX_ANY_SW_TSTAMP &&\n\t sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)\n\t\ttskey = sk->sk_tskey++;\n\n\thh_len = LL_RESERVED_SPACE(rt->dst.dev);\n\n\tfragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0);\n\tmaxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen;\n\tmaxnonfragsize = ip_sk_ignore_df(sk) ? 0xFFFF : mtu;\n\n\tif (cork->length + length > maxnonfragsize - fragheaderlen) {\n\t\tip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,\n\t\t\t mtu - (opt ? opt->optlen : 0));\n\t\treturn -EMSGSIZE;\n\t}\n\n\t/*\n\t * transhdrlen > 0 means that this is the first fragment and we wish\n\t * it won't be fragmented in the future.\n\t */\n\tif (transhdrlen &&\n\t length + fragheaderlen <= mtu &&\n\t rt->dst.dev->features & (NETIF_F_HW_CSUM | NETIF_F_IP_CSUM) &&\n\t !(flags & MSG_MORE) &&\n\t !exthdrlen)\n\t\tcsummode = CHECKSUM_PARTIAL;\n\n\tcork->length += length;\n\tif ((skb && skb_is_gso(skb)) ||\n\t (((length + (skb ? skb->len : fragheaderlen)) > mtu) &&\n\t (skb_queue_len(queue) <= 1) &&\n\t (sk->sk_protocol == IPPROTO_UDP) &&\n\t (rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) &&\n\t (sk->sk_type == SOCK_DGRAM) && !sk->sk_no_check_tx)) {\n\t\terr = ip_ufo_append_data(sk, queue, getfrag, from, length,\n\t\t\t\t\t hh_len, fragheaderlen, transhdrlen,\n\t\t\t\t\t maxfraglen, flags);\n\t\tif (err)\n\t\t\tgoto error;\n\t\treturn 0;\n\t}\n\n\t/* So, what's going on in the loop below?\n\t *\n\t * We use calculated fragment length to generate chained skb,\n\t * each of segments is IP fragment ready for sending to network after\n\t * adding appropriate IP header.\n\t */\n\n\tif (!skb)\n\t\tgoto alloc_new_skb;\n\n\twhile (length > 0) {\n\t\t/* Check if the remaining data fits into current packet. */\n\t\tcopy = mtu - skb->len;\n\t\tif (copy < length)\n\t\t\tcopy = maxfraglen - skb->len;\n\t\tif (copy <= 0) {\n\t\t\tchar *data;\n\t\t\tunsigned int datalen;\n\t\t\tunsigned int fraglen;\n\t\t\tunsigned int fraggap;\n\t\t\tunsigned int alloclen;\n\t\t\tstruct sk_buff *skb_prev;\nalloc_new_skb:\n\t\t\tskb_prev = skb;\n\t\t\tif (skb_prev)\n\t\t\t\tfraggap = skb_prev->len - maxfraglen;\n\t\t\telse\n\t\t\t\tfraggap = 0;\n\n\t\t\t/*\n\t\t\t * If remaining data exceeds the mtu,\n\t\t\t * we know we need more fragment(s).\n\t\t\t */\n\t\t\tdatalen = length + fraggap;\n\t\t\tif (datalen > mtu - fragheaderlen)\n\t\t\t\tdatalen = maxfraglen - fragheaderlen;\n\t\t\tfraglen = datalen + fragheaderlen;\n\n\t\t\tif ((flags & MSG_MORE) &&\n\t\t\t !(rt->dst.dev->features&NETIF_F_SG))\n\t\t\t\talloclen = mtu;\n\t\t\telse\n\t\t\t\talloclen = fraglen;\n\n\t\t\talloclen += exthdrlen;\n\n\t\t\t/* The last fragment gets additional space at tail.\n\t\t\t * Note, with MSG_MORE we overallocate on fragments,\n\t\t\t * because we have no idea what fragment will be\n\t\t\t * the last.\n\t\t\t */\n\t\t\tif (datalen == length + fraggap)\n\t\t\t\talloclen += rt->dst.trailer_len;\n\n\t\t\tif (transhdrlen) {\n\t\t\t\tskb = sock_alloc_send_skb(sk,\n\t\t\t\t\t\talloclen + hh_len + 15,\n\t\t\t\t\t\t(flags & MSG_DONTWAIT), &err);\n\t\t\t} else {\n\t\t\t\tskb = NULL;\n\t\t\t\tif (refcount_read(&sk->sk_wmem_alloc) <=\n\t\t\t\t 2 * sk->sk_sndbuf)\n\t\t\t\t\tskb = sock_wmalloc(sk,\n\t\t\t\t\t\t\t alloclen + hh_len + 15, 1,\n\t\t\t\t\t\t\t sk->sk_allocation);\n\t\t\t\tif (unlikely(!skb))\n\t\t\t\t\terr = -ENOBUFS;\n\t\t\t}\n\t\t\tif (!skb)\n\t\t\t\tgoto error;\n\n\t\t\t/*\n\t\t\t *\tFill in the control structures\n\t\t\t */\n\t\t\tskb->ip_summed = csummode;\n\t\t\tskb->csum = 0;\n\t\t\tskb_reserve(skb, hh_len);\n\n\t\t\t/* only the initial fragment is time stamped */\n\t\t\tskb_shinfo(skb)->tx_flags = cork->tx_flags;\n\t\t\tcork->tx_flags = 0;\n\t\t\tskb_shinfo(skb)->tskey = tskey;\n\t\t\ttskey = 0;\n\n\t\t\t/*\n\t\t\t *\tFind where to start putting bytes.\n\t\t\t */\n\t\t\tdata = skb_put(skb, fraglen + exthdrlen);\n\t\t\tskb_set_network_header(skb, exthdrlen);\n\t\t\tskb->transport_header = (skb->network_header +\n\t\t\t\t\t\t fragheaderlen);\n\t\t\tdata += fragheaderlen + exthdrlen;\n\n\t\t\tif (fraggap) {\n\t\t\t\tskb->csum = skb_copy_and_csum_bits(\n\t\t\t\t\tskb_prev, maxfraglen,\n\t\t\t\t\tdata + transhdrlen, fraggap, 0);\n\t\t\t\tskb_prev->csum = csum_sub(skb_prev->csum,\n\t\t\t\t\t\t\t skb->csum);\n\t\t\t\tdata += fraggap;\n\t\t\t\tpskb_trim_unique(skb_prev, maxfraglen);\n\t\t\t}\n\n\t\t\tcopy = datalen - transhdrlen - fraggap;\n\t\t\tif (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {\n\t\t\t\terr = -EFAULT;\n\t\t\t\tkfree_skb(skb);\n\t\t\t\tgoto error;\n\t\t\t}\n\n\t\t\toffset += copy;\n\t\t\tlength -= datalen - fraggap;\n\t\t\ttranshdrlen = 0;\n\t\t\texthdrlen = 0;\n\t\t\tcsummode = CHECKSUM_NONE;\n\n\t\t\tif ((flags & MSG_CONFIRM) && !skb_prev)\n\t\t\t\tskb_set_dst_pending_confirm(skb, 1);\n\n\t\t\t/*\n\t\t\t * Put the packet on the pending queue.\n\t\t\t */\n\t\t\t__skb_queue_tail(queue, skb);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (copy > length)\n\t\t\tcopy = length;\n\n\t\tif (!(rt->dst.dev->features&NETIF_F_SG)) {\n\t\t\tunsigned int off;\n\n\t\t\toff = skb->len;\n\t\t\tif (getfrag(from, skb_put(skb, copy),\n\t\t\t\t\toffset, copy, off, skb) < 0) {\n\t\t\t\t__skb_trim(skb, off);\n\t\t\t\terr = -EFAULT;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t} else {\n\t\t\tint i = skb_shinfo(skb)->nr_frags;\n\n\t\t\terr = -ENOMEM;\n\t\t\tif (!sk_page_frag_refill(sk, pfrag))\n\t\t\t\tgoto error;\n\n\t\t\tif (!skb_can_coalesce(skb, i, pfrag->page,\n\t\t\t\t\t pfrag->offset)) {\n\t\t\t\terr = -EMSGSIZE;\n\t\t\t\tif (i == MAX_SKB_FRAGS)\n\t\t\t\t\tgoto error;\n\n\t\t\t\t__skb_fill_page_desc(skb, i, pfrag->page,\n\t\t\t\t\t\t pfrag->offset, 0);\n\t\t\t\tskb_shinfo(skb)->nr_frags = ++i;\n\t\t\t\tget_page(pfrag->page);\n\t\t\t}\n\t\t\tcopy = min_t(int, copy, pfrag->size - pfrag->offset);\n\t\t\tif (getfrag(from,\n\t\t\t\t page_address(pfrag->page) + pfrag->offset,\n\t\t\t\t offset, copy, skb->len, skb) < 0)\n\t\t\t\tgoto error_efault;\n\n\t\t\tpfrag->offset += copy;\n\t\t\tskb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);\n\t\t\tskb->len += copy;\n\t\t\tskb->data_len += copy;\n\t\t\tskb->truesize += copy;\n\t\t\trefcount_add(copy, &sk->sk_wmem_alloc);\n\t\t}\n\t\toffset += copy;\n\t\tlength -= copy;\n\t}\n\n\treturn 0;\n\nerror_efault:\n\terr = -EFAULT;\nerror:\n\tcork->length -= length;\n\tIP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS);\n\treturn err;\n}", "project": "net", "hash": 333052664581020657981105773969472049388, "size": 254, "commit_id": "85f1bd9a7b5a79d5baa8bf44af19658f7bf77bfa", "message": "udp: consistently apply ufo or fragmentation\n\nWhen iteratively building a UDP datagram with MSG_MORE and that\ndatagram exceeds MTU, consistently choose UFO or fragmentation.\n\nOnce skb_is_gso, always apply ufo. Conversely, once a datagram is\nsplit across multiple skbs, do not consider ufo.\n\nSendpage already maintains the first invariant, only add the second.\nIPv6 does not have a sendpage implementation to modify.\n\nA gso skb must have a partial checksum, do not follow sk_no_check_tx\nin udp_send_skb.\n\nFound by syzkaller.\n\nFixes: e89e9cf539a2 (\"[IPv4/IPv6]: UFO Scatter-gather approach\")\nReported-by: Andrey Konovalov <andreyknvl@google.com>\nSigned-off-by: Willem de Bruijn <willemb@google.com>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 0, "dataset": "other", "idx": 468988}
  969. {"func": "static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,\n const BYTE* exponent, int exponent_size, BYTE* output)\n{\n\tBN_CTX* ctx;\n\tint output_length = -1;\n\tBYTE* input_reverse;\n\tBYTE* modulus_reverse;\n\tBYTE* exponent_reverse;\n\tBIGNUM *mod, *exp, *x, *y;\n\tinput_reverse = (BYTE*)malloc(2 * key_length + exponent_size);\n\n\tif (!input_reverse)\n\t\treturn -1;\n\n\tmodulus_reverse = input_reverse + key_length;\n\texponent_reverse = modulus_reverse + key_length;\n\tmemcpy(modulus_reverse, modulus, key_length);\n\tcrypto_reverse(modulus_reverse, key_length);\n\tmemcpy(exponent_reverse, exponent, exponent_size);\n\tcrypto_reverse(exponent_reverse, exponent_size);\n\tmemcpy(input_reverse, input, length);\n\tcrypto_reverse(input_reverse, length);\n\n\tif (!(ctx = BN_CTX_new()))\n\t\tgoto fail_bn_ctx;\n\n\tif (!(mod = BN_new()))\n\t\tgoto fail_bn_mod;\n\n\tif (!(exp = BN_new()))\n\t\tgoto fail_bn_exp;\n\n\tif (!(x = BN_new()))\n\t\tgoto fail_bn_x;\n\n\tif (!(y = BN_new()))\n\t\tgoto fail_bn_y;\n\n\tBN_bin2bn(modulus_reverse, key_length, mod);\n\tBN_bin2bn(exponent_reverse, exponent_size, exp);\n\tBN_bin2bn(input_reverse, length, x);\n\tBN_mod_exp(y, x, exp, mod, ctx);\n\toutput_length = BN_bn2bin(y, output);\n\tcrypto_reverse(output, output_length);\n\n\tif (output_length < (int)key_length)\n\t\tmemset(output + output_length, 0, key_length - output_length);\n\n\tBN_free(y);\nfail_bn_y:\n\tBN_clear_free(x);\nfail_bn_x:\n\tBN_free(exp);\nfail_bn_exp:\n\tBN_free(mod);\nfail_bn_mod:\n\tBN_CTX_free(ctx);\nfail_bn_ctx:\n\tfree(input_reverse);\n\treturn output_length;\n}", "project": "FreeRDP", "hash": 248112898649019039113029495278291277796, "size": 61, "commit_id": "8305349a943c68b1bc8c158f431dc607655aadea", "message": "Fixed GHSL-2020-102 heap overflow\n\n(cherry picked from commit 197b16cc15a12813c2e4fa2d6ae9cd9c4a57e581)", "target": 1, "dataset": "other", "idx": 213662}
  970. {"func": "static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,\n const BYTE* exponent, int exponent_size, BYTE* output)\n{\n\tBN_CTX* ctx = NULL;\n\tint output_length = -1;\n\tBYTE* input_reverse = NULL;\n\tBYTE* modulus_reverse = NULL;\n\tBYTE* exponent_reverse = NULL;\n\tBIGNUM* mod = NULL;\n\tBIGNUM* exp = NULL;\n\tBIGNUM* x = NULL;\n\tBIGNUM* y = NULL;\n\tsize_t bufferSize = 2 * key_length + exponent_size;\n\n\tif (!input || (length < 0) || (exponent_size < 0) || !modulus || !exponent || !output)\n\t\treturn -1;\n\n\tif (length > bufferSize)\n\t\tbufferSize = length;\n\n\tinput_reverse = (BYTE*)calloc(bufferSize, 1);\n\n\tif (!input_reverse)\n\t\treturn -1;\n\n\tmodulus_reverse = input_reverse + key_length;\n\texponent_reverse = modulus_reverse + key_length;\n\tmemcpy(modulus_reverse, modulus, key_length);\n\tcrypto_reverse(modulus_reverse, key_length);\n\tmemcpy(exponent_reverse, exponent, exponent_size);\n\tcrypto_reverse(exponent_reverse, exponent_size);\n\tmemcpy(input_reverse, input, length);\n\tcrypto_reverse(input_reverse, length);\n\n\tif (!(ctx = BN_CTX_new()))\n\t\tgoto fail_bn_ctx;\n\n\tif (!(mod = BN_new()))\n\t\tgoto fail_bn_mod;\n\n\tif (!(exp = BN_new()))\n\t\tgoto fail_bn_exp;\n\n\tif (!(x = BN_new()))\n\t\tgoto fail_bn_x;\n\n\tif (!(y = BN_new()))\n\t\tgoto fail_bn_y;\n\n\tif (!BN_bin2bn(modulus_reverse, key_length, mod))\n\t\tgoto fail;\n\n\tif (!BN_bin2bn(exponent_reverse, exponent_size, exp))\n\t\tgoto fail;\n\tif (!BN_bin2bn(input_reverse, length, x))\n\t\tgoto fail;\n\tif (BN_mod_exp(y, x, exp, mod, ctx) != 1)\n\t\tgoto fail;\n\toutput_length = BN_bn2bin(y, output);\n\tif (output_length < 0)\n\t\tgoto fail;\n\tcrypto_reverse(output, output_length);\n\n\tif (output_length < key_length)\n\t\tmemset(output + output_length, 0, key_length - output_length);\n\nfail:\n\tBN_free(y);\nfail_bn_y:\n\tBN_clear_free(x);\nfail_bn_x:\n\tBN_free(exp);\nfail_bn_exp:\n\tBN_free(mod);\nfail_bn_mod:\n\tBN_CTX_free(ctx);\nfail_bn_ctx:\n\tfree(input_reverse);\n\treturn output_length;\n}", "project": "FreeRDP", "hash": 241821229484338014163593582174308767879, "size": 80, "commit_id": "8305349a943c68b1bc8c158f431dc607655aadea", "message": "Fixed GHSL-2020-102 heap overflow\n\n(cherry picked from commit 197b16cc15a12813c2e4fa2d6ae9cd9c4a57e581)", "target": 0, "dataset": "other", "idx": 473441}
  971. {"func": "open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred)\n{\n SSL_CTX *ssl_ctx = NULL;\n SSL *ssl = NULL;\n int n, finished = 0;\n X509_VERIFY_PARAM *param;\n uint8_t verify_crls = cred->x509Credential.x509CrlVerifyMode;\n\n if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method())))\n {\n rfbClientLog(\"Could not create new SSL context.\\n\");\n return NULL;\n }\n\n param = X509_VERIFY_PARAM_new();\n\n /* Setup verification if not anonymous */\n if (!anonTLS)\n {\n if (cred->x509Credential.x509CACertFile)\n {\n if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL))\n {\n rfbClientLog(\"Failed to load CA certificate from %s.\\n\",\n cred->x509Credential.x509CACertFile);\n goto error_free_ctx;\n }\n } else {\n rfbClientLog(\"Using default paths for certificate verification.\\n\");\n SSL_CTX_set_default_verify_paths (ssl_ctx);\n }\n\n if (cred->x509Credential.x509CACrlFile)\n {\n if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx))\n {\n rfbClientLog(\"CRLs could not be loaded.\\n\");\n goto error_free_ctx;\n }\n if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll;\n }\n\n if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile)\n {\n if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1)\n {\n rfbClientLog(\"Client certificate could not be loaded.\\n\");\n goto error_free_ctx;\n }\n\n if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile,\n SSL_FILETYPE_PEM) != 1)\n {\n rfbClientLog(\"Client private key could not be loaded.\\n\");\n goto error_free_ctx;\n }\n\n if (SSL_CTX_check_private_key(ssl_ctx) == 0) {\n rfbClientLog(\"Client certificate and private key do not match.\\n\");\n goto error_free_ctx;\n }\n }\n\n SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);\n\n if (verify_crls == rfbX509CrlVerifyClient) \n X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);\n else if (verify_crls == rfbX509CrlVerifyAll)\n X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);\n\n if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost)))\n {\n rfbClientLog(\"Could not set server name for verification.\\n\");\n goto error_free_ctx;\n }\n SSL_CTX_set1_param(ssl_ctx, param);\n }\n\n if (!(ssl = SSL_new (ssl_ctx)))\n {\n rfbClientLog(\"Could not create a new SSL session.\\n\");\n goto error_free_ctx;\n }\n\n /* TODO: finetune this list, take into account anonTLS bool */\n SSL_set_cipher_list(ssl, \"ALL\");\n\n SSL_set_fd (ssl, sockfd);\n SSL_CTX_set_app_data (ssl_ctx, client);\n\n do\n {\n n = SSL_connect(ssl);\n\t\t\n if (n != 1) \n {\n if (wait_for_data(ssl, n, 1) != 1) \n {\n finished = 1;\n SSL_shutdown(ssl);\n\n goto error_free_ssl;\n }\n }\n } while( n != 1 && finished != 1 );\n\n X509_VERIFY_PARAM_free(param);\n return ssl;\n\nerror_free_ssl:\n SSL_free(ssl);\n\nerror_free_ctx:\n X509_VERIFY_PARAM_free(param);\n SSL_CTX_free(ssl_ctx);\n\n return NULL;\n}", "project": "libvncserver", "hash": 117013703740746928818923290774033041402, "size": 118, "commit_id": "33441d90a506d5f3ae9388f2752901227e430553", "message": "libvncclient/tls_openssl: do not deref a NULL pointer\n\nHappens in anonTLS mode where cred is NULL.\n\nre #347", "target": 1, "dataset": "other", "idx": 214025}
  972. {"func": "open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred)\n{\n SSL_CTX *ssl_ctx = NULL;\n SSL *ssl = NULL;\n int n, finished = 0;\n X509_VERIFY_PARAM *param;\n uint8_t verify_crls;\n\n if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method())))\n {\n rfbClientLog(\"Could not create new SSL context.\\n\");\n return NULL;\n }\n\n param = X509_VERIFY_PARAM_new();\n\n /* Setup verification if not anonymous */\n if (!anonTLS)\n {\n verify_crls = cred->x509Credential.x509CrlVerifyMode;\n if (cred->x509Credential.x509CACertFile)\n {\n if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL))\n {\n rfbClientLog(\"Failed to load CA certificate from %s.\\n\",\n cred->x509Credential.x509CACertFile);\n goto error_free_ctx;\n }\n } else {\n rfbClientLog(\"Using default paths for certificate verification.\\n\");\n SSL_CTX_set_default_verify_paths (ssl_ctx);\n }\n\n if (cred->x509Credential.x509CACrlFile)\n {\n if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx))\n {\n rfbClientLog(\"CRLs could not be loaded.\\n\");\n goto error_free_ctx;\n }\n if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll;\n }\n\n if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile)\n {\n if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1)\n {\n rfbClientLog(\"Client certificate could not be loaded.\\n\");\n goto error_free_ctx;\n }\n\n if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile,\n SSL_FILETYPE_PEM) != 1)\n {\n rfbClientLog(\"Client private key could not be loaded.\\n\");\n goto error_free_ctx;\n }\n\n if (SSL_CTX_check_private_key(ssl_ctx) == 0) {\n rfbClientLog(\"Client certificate and private key do not match.\\n\");\n goto error_free_ctx;\n }\n }\n\n SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);\n\n if (verify_crls == rfbX509CrlVerifyClient) \n X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);\n else if (verify_crls == rfbX509CrlVerifyAll)\n X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);\n\n if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost)))\n {\n rfbClientLog(\"Could not set server name for verification.\\n\");\n goto error_free_ctx;\n }\n SSL_CTX_set1_param(ssl_ctx, param);\n }\n\n if (!(ssl = SSL_new (ssl_ctx)))\n {\n rfbClientLog(\"Could not create a new SSL session.\\n\");\n goto error_free_ctx;\n }\n\n /* TODO: finetune this list, take into account anonTLS bool */\n SSL_set_cipher_list(ssl, \"ALL\");\n\n SSL_set_fd (ssl, sockfd);\n SSL_CTX_set_app_data (ssl_ctx, client);\n\n do\n {\n n = SSL_connect(ssl);\n\t\t\n if (n != 1) \n {\n if (wait_for_data(ssl, n, 1) != 1) \n {\n finished = 1;\n SSL_shutdown(ssl);\n\n goto error_free_ssl;\n }\n }\n } while( n != 1 && finished != 1 );\n\n X509_VERIFY_PARAM_free(param);\n return ssl;\n\nerror_free_ssl:\n SSL_free(ssl);\n\nerror_free_ctx:\n X509_VERIFY_PARAM_free(param);\n SSL_CTX_free(ssl_ctx);\n\n return NULL;\n}", "project": "libvncserver", "hash": 65290517691015150407412891236689283742, "size": 119, "commit_id": "33441d90a506d5f3ae9388f2752901227e430553", "message": "libvncclient/tls_openssl: do not deref a NULL pointer\n\nHappens in anonTLS mode where cred is NULL.\n\nre #347", "target": 0, "dataset": "other", "idx": 474542}
  973. {"func": "static int dissect_dvb_s2_bb(tvbuff_t *tvb, int cur_off, proto_tree *tree, packet_info *pinfo)\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, cur_off, 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, cur_off + 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, cur_off + 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, cur_off + 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 cur_off + 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 cur_off + DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n }\n\n input8 = tvb_get_guint8(tvb, cur_off + 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 cur_off + 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 cur_off + DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"reserved\");\n }\n\n user_packet_length = input16 = tvb_get_ntohs(tvb, cur_off + 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 cur_off + 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, cur_off + 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 cur_off + 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, cur_off + DVB_S2_BB_OFFS_SYNC);\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, cur_off + 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, cur_off + DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN);\n\n new_off += 1;\n proto_tree_add_checksum(dvb_s2_bb_tree, tvb, cur_off + 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, cur_off), 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, cur_off + 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, cur_off + new_off, tree, pinfo, bb_data_len);\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, cur_off + 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, cur_off + 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, cur_off + 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, cur_off + 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": 308318766763033510949212779797367389554, "size": 147, "commit_id": "0d8be1fb797b3d65f1c2c204da76af8e8de6d3cc", "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.\n\n\n(cherry picked from commit 0137c24d60934f131b25506a88c9464e4dc827de)", "target": 1, "dataset": "other", "idx": 214056}
  974. {"func": "static int dissect_dvb_s2_bb(tvbuff_t *tvb, int cur_off, proto_tree *tree, packet_info *pinfo)\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, cur_off, 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, cur_off + 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, cur_off + 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, cur_off + 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 cur_off + 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 cur_off + DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n }\n\n input8 = tvb_get_guint8(tvb, cur_off + 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 cur_off + 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 cur_off + DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"reserved\");\n }\n\n user_packet_length = input16 = tvb_get_ntohs(tvb, cur_off + 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 cur_off + 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, cur_off + 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 cur_off + 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, cur_off + DVB_S2_BB_OFFS_SYNC);\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, cur_off + 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, cur_off + DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN);\n\n new_off += 1;\n proto_tree_add_checksum(dvb_s2_bb_tree, tvb, cur_off + 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, cur_off), 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, cur_off + 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, cur_off + new_off, tree, pinfo, bb_data_len);\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, cur_off + 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, cur_off + 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, cur_off + 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, cur_off + 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": 292878332668751229125261027041642584721, "size": 149, "commit_id": "0d8be1fb797b3d65f1c2c204da76af8e8de6d3cc", "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.\n\n\n(cherry picked from commit 0137c24d60934f131b25506a88c9464e4dc827de)", "target": 0, "dataset": "other", "idx": 475261}
  975. {"func": "static void inline ConvertXYZToJzazbz(const double X,const double Y,\n const double Z,const double white_luminance,double *Jz,double *az,double *bz)\n{\n#define Jzazbz_b 1.15 /* https://observablehq.com/@jrus/jzazbz */\n#define Jzazbz_g 0.66\n#define Jzazbz_c1 (3424.0/4096.0)\n#define Jzazbz_c2 (2413.0/128.0)\n#define Jzazbz_c3 (2392.0/128.0)\n#define Jzazbz_n (2610.0/16384.0)\n#define Jzazbz_p (1.7*2523.0/32.0)\n#define Jzazbz_d (-0.56)\n#define Jzazbz_d0 (1.6295499532821566e-11)\n\n double\n gamma,\n Iz,\n L,\n Lp,\n M,\n Mp,\n S,\n Sp,\n Xp,\n Yp,\n Zp;\n\n Xp=(Jzazbz_b*X-Z*(Jzazbz_b-1));\n Yp=(Jzazbz_g*Y-X*(Jzazbz_g-1));\n Zp=Z;\n L=0.41478972*Xp+0.579999*Yp+0.0146480*Zp;\n M=(-0.2015100)*Xp+1.120649*Yp+0.0531008*Zp;\n S=(-0.0166008)*Xp+0.264800*Yp+0.6684799*Zp;\n gamma=pow(L/white_luminance,Jzazbz_n);\n Lp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n gamma=pow(M/white_luminance,Jzazbz_n);\n Mp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n gamma=pow(S/white_luminance,Jzazbz_n);\n Sp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n Iz=0.5*Lp+0.5*Mp;\n *az=3.52400*Lp-4.066708*Mp+0.542708*Sp+0.5;\n *bz=0.199076*Lp+1.096799*Mp-1.295875*Sp+0.5;\n *Jz=((Jzazbz_d+1.0)*Iz)/(Jzazbz_d*Iz+1.0)-Jzazbz_d0;\n}", "project": "ImageMagick", "hash": 238788498874258350151289869670329565824, "size": 43, "commit_id": "75f6f5032690077cae3eaeda3c0165cc765eaeb5", "message": "https://github.com/ImageMagick/ImageMagick/issues/3295", "target": 1, "dataset": "other", "idx": 214120}
  976. {"func": "static void inline ConvertXYZToJzazbz(const double X,const double Y,\n const double Z,const double white_luminance,double *Jz,double *az,double *bz)\n{\n#define Jzazbz_b 1.15 /* https://observablehq.com/@jrus/jzazbz */\n#define Jzazbz_g 0.66\n#define Jzazbz_c1 (3424.0/4096.0)\n#define Jzazbz_c2 (2413.0/128.0)\n#define Jzazbz_c3 (2392.0/128.0)\n#define Jzazbz_n (2610.0/16384.0)\n#define Jzazbz_p (1.7*2523.0/32.0)\n#define Jzazbz_d (-0.56)\n#define Jzazbz_d0 (1.6295499532821566e-11)\n\n double\n gamma,\n Iz,\n L,\n Lp,\n M,\n Mp,\n S,\n Sp,\n Xp,\n Yp,\n Zp;\n\n Xp=(Jzazbz_b*X-Z*(Jzazbz_b-1));\n Yp=(Jzazbz_g*Y-X*(Jzazbz_g-1));\n Zp=Z;\n L=0.41478972*Xp+0.579999*Yp+0.0146480*Zp;\n M=(-0.2015100)*Xp+1.120649*Yp+0.0531008*Zp;\n S=(-0.0166008)*Xp+0.264800*Yp+0.6684799*Zp;\n gamma=pow(L*PerceptibleReciprocal(white_luminance),Jzazbz_n);\n Lp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n gamma=pow(M*PerceptibleReciprocal(white_luminance),Jzazbz_n);\n Mp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n gamma=pow(S*PerceptibleReciprocal(white_luminance),Jzazbz_n);\n Sp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n Iz=0.5*Lp+0.5*Mp;\n *az=3.52400*Lp-4.066708*Mp+0.542708*Sp+0.5;\n *bz=0.199076*Lp+1.096799*Mp-1.295875*Sp+0.5;\n *Jz=((Jzazbz_d+1.0)*Iz)/(Jzazbz_d*Iz+1.0)-Jzazbz_d0;\n}", "project": "ImageMagick", "hash": 198227054044668048777169440025596538351, "size": 43, "commit_id": "75f6f5032690077cae3eaeda3c0165cc765eaeb5", "message": "https://github.com/ImageMagick/ImageMagick/issues/3295", "target": 0, "dataset": "other", "idx": 475970}
  977. {"func": "static void dp8393x_do_transmit_packets(dp8393xState *s)\n{\n NetClientState *nc = qemu_get_queue(s->nic);\n int width, size;\n int tx_len, len;\n uint16_t i;\n\n width = (s->regs[SONIC_DCR] & SONIC_DCR_DW) ? 2 : 1;\n\n while (1) {\n /* Read memory */\n size = sizeof(uint16_t) * 6 * width;\n s->regs[SONIC_TTDA] = s->regs[SONIC_CTDA];\n DPRINTF(\"Transmit packet at %08x\\n\", dp8393x_ttda(s));\n address_space_read(&s->as, dp8393x_ttda(s) + sizeof(uint16_t) * width,\n MEMTXATTRS_UNSPECIFIED, s->data, size);\n tx_len = 0;\n\n /* Update registers */\n s->regs[SONIC_TCR] = dp8393x_get(s, width, 0) & 0xf000;\n s->regs[SONIC_TPS] = dp8393x_get(s, width, 1);\n s->regs[SONIC_TFC] = dp8393x_get(s, width, 2);\n s->regs[SONIC_TSA0] = dp8393x_get(s, width, 3);\n s->regs[SONIC_TSA1] = dp8393x_get(s, width, 4);\n s->regs[SONIC_TFS] = dp8393x_get(s, width, 5);\n\n /* Handle programmable interrupt */\n if (s->regs[SONIC_TCR] & SONIC_TCR_PINT) {\n s->regs[SONIC_ISR] |= SONIC_ISR_PINT;\n } else {\n s->regs[SONIC_ISR] &= ~SONIC_ISR_PINT;\n }\n\n for (i = 0; i < s->regs[SONIC_TFC]; ) {\n /* Append fragment */\n len = s->regs[SONIC_TFS];\n if (tx_len + len > sizeof(s->tx_buffer)) {\n len = sizeof(s->tx_buffer) - tx_len;\n }\n address_space_read(&s->as, dp8393x_tsa(s), MEMTXATTRS_UNSPECIFIED,\n &s->tx_buffer[tx_len], len);\n tx_len += len;\n\n i++;\n if (i != s->regs[SONIC_TFC]) {\n /* Read next fragment details */\n size = sizeof(uint16_t) * 3 * width;\n address_space_read(&s->as,\n dp8393x_ttda(s)\n + sizeof(uint16_t) * width * (4 + 3 * i),\n MEMTXATTRS_UNSPECIFIED, s->data,\n size);\n s->regs[SONIC_TSA0] = dp8393x_get(s, width, 0);\n s->regs[SONIC_TSA1] = dp8393x_get(s, width, 1);\n s->regs[SONIC_TFS] = dp8393x_get(s, width, 2);\n }\n }\n\n /* Handle Ethernet checksum */\n if (!(s->regs[SONIC_TCR] & SONIC_TCR_CRCI)) {\n /* Don't append FCS there, to look like slirp packets\n * which don't have one */\n } else {\n /* Remove existing FCS */\n tx_len -= 4;\n if (tx_len < 0) {\n SONIC_ERROR(\"tx_len is %d\\n\", tx_len);\n break;\n }\n }\n\n if (s->regs[SONIC_RCR] & (SONIC_RCR_LB1 | SONIC_RCR_LB0)) {\n /* Loopback */\n s->regs[SONIC_TCR] |= SONIC_TCR_CRSL;\n if (nc->info->can_receive(nc)) {\n s->loopback_packet = 1;\n nc->info->receive(nc, s->tx_buffer, tx_len);\n }\n } else {\n /* Transmit packet */\n qemu_send_packet(nc, s->tx_buffer, tx_len);\n }\n s->regs[SONIC_TCR] |= SONIC_TCR_PTX;\n\n /* Write status */\n dp8393x_put(s, width, 0,\n s->regs[SONIC_TCR] & 0x0fff); /* status */\n size = sizeof(uint16_t) * width;\n address_space_write(&s->as, dp8393x_ttda(s),\n MEMTXATTRS_UNSPECIFIED, s->data, size);\n\n if (!(s->regs[SONIC_CR] & SONIC_CR_HTX)) {\n /* Read footer of packet */\n size = sizeof(uint16_t) * width;\n address_space_read(&s->as,\n dp8393x_ttda(s)\n + sizeof(uint16_t) * width\n * (4 + 3 * s->regs[SONIC_TFC]),\n MEMTXATTRS_UNSPECIFIED, s->data,\n size);\n s->regs[SONIC_CTDA] = dp8393x_get(s, width, 0);\n if (s->regs[SONIC_CTDA] & SONIC_DESC_EOL) {\n /* EOL detected */\n break;\n }\n }\n }\n\n /* Done */\n s->regs[SONIC_CR] &= ~SONIC_CR_TXP;\n s->regs[SONIC_ISR] |= SONIC_ISR_TXDN;\n dp8393x_update_irq(s);\n}", "project": "qemu", "hash": 316061785017432960037477437719244038033, "size": 113, "commit_id": "331d2ac9ea307c990dc86e6493e8f0c48d14bb33", "message": "dp8393x: switch to use qemu_receive_packet() for loopback packet\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 <ppandit@redhat.com>\nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 <philmd@redhat.com\nSigned-off-by: Jason Wang <jasowang@redhat.com>", "target": 1, "dataset": "other", "idx": 214193}
  978. {"func": "static void dp8393x_do_transmit_packets(dp8393xState *s)\n{\n NetClientState *nc = qemu_get_queue(s->nic);\n int width, size;\n int tx_len, len;\n uint16_t i;\n\n width = (s->regs[SONIC_DCR] & SONIC_DCR_DW) ? 2 : 1;\n\n while (1) {\n /* Read memory */\n size = sizeof(uint16_t) * 6 * width;\n s->regs[SONIC_TTDA] = s->regs[SONIC_CTDA];\n DPRINTF(\"Transmit packet at %08x\\n\", dp8393x_ttda(s));\n address_space_read(&s->as, dp8393x_ttda(s) + sizeof(uint16_t) * width,\n MEMTXATTRS_UNSPECIFIED, s->data, size);\n tx_len = 0;\n\n /* Update registers */\n s->regs[SONIC_TCR] = dp8393x_get(s, width, 0) & 0xf000;\n s->regs[SONIC_TPS] = dp8393x_get(s, width, 1);\n s->regs[SONIC_TFC] = dp8393x_get(s, width, 2);\n s->regs[SONIC_TSA0] = dp8393x_get(s, width, 3);\n s->regs[SONIC_TSA1] = dp8393x_get(s, width, 4);\n s->regs[SONIC_TFS] = dp8393x_get(s, width, 5);\n\n /* Handle programmable interrupt */\n if (s->regs[SONIC_TCR] & SONIC_TCR_PINT) {\n s->regs[SONIC_ISR] |= SONIC_ISR_PINT;\n } else {\n s->regs[SONIC_ISR] &= ~SONIC_ISR_PINT;\n }\n\n for (i = 0; i < s->regs[SONIC_TFC]; ) {\n /* Append fragment */\n len = s->regs[SONIC_TFS];\n if (tx_len + len > sizeof(s->tx_buffer)) {\n len = sizeof(s->tx_buffer) - tx_len;\n }\n address_space_read(&s->as, dp8393x_tsa(s), MEMTXATTRS_UNSPECIFIED,\n &s->tx_buffer[tx_len], len);\n tx_len += len;\n\n i++;\n if (i != s->regs[SONIC_TFC]) {\n /* Read next fragment details */\n size = sizeof(uint16_t) * 3 * width;\n address_space_read(&s->as,\n dp8393x_ttda(s)\n + sizeof(uint16_t) * width * (4 + 3 * i),\n MEMTXATTRS_UNSPECIFIED, s->data,\n size);\n s->regs[SONIC_TSA0] = dp8393x_get(s, width, 0);\n s->regs[SONIC_TSA1] = dp8393x_get(s, width, 1);\n s->regs[SONIC_TFS] = dp8393x_get(s, width, 2);\n }\n }\n\n /* Handle Ethernet checksum */\n if (!(s->regs[SONIC_TCR] & SONIC_TCR_CRCI)) {\n /* Don't append FCS there, to look like slirp packets\n * which don't have one */\n } else {\n /* Remove existing FCS */\n tx_len -= 4;\n if (tx_len < 0) {\n SONIC_ERROR(\"tx_len is %d\\n\", tx_len);\n break;\n }\n }\n\n if (s->regs[SONIC_RCR] & (SONIC_RCR_LB1 | SONIC_RCR_LB0)) {\n /* Loopback */\n s->regs[SONIC_TCR] |= SONIC_TCR_CRSL;\n if (nc->info->can_receive(nc)) {\n s->loopback_packet = 1;\n qemu_receive_packet(nc, s->tx_buffer, tx_len);\n }\n } else {\n /* Transmit packet */\n qemu_send_packet(nc, s->tx_buffer, tx_len);\n }\n s->regs[SONIC_TCR] |= SONIC_TCR_PTX;\n\n /* Write status */\n dp8393x_put(s, width, 0,\n s->regs[SONIC_TCR] & 0x0fff); /* status */\n size = sizeof(uint16_t) * width;\n address_space_write(&s->as, dp8393x_ttda(s),\n MEMTXATTRS_UNSPECIFIED, s->data, size);\n\n if (!(s->regs[SONIC_CR] & SONIC_CR_HTX)) {\n /* Read footer of packet */\n size = sizeof(uint16_t) * width;\n address_space_read(&s->as,\n dp8393x_ttda(s)\n + sizeof(uint16_t) * width\n * (4 + 3 * s->regs[SONIC_TFC]),\n MEMTXATTRS_UNSPECIFIED, s->data,\n size);\n s->regs[SONIC_CTDA] = dp8393x_get(s, width, 0);\n if (s->regs[SONIC_CTDA] & SONIC_DESC_EOL) {\n /* EOL detected */\n break;\n }\n }\n }\n\n /* Done */\n s->regs[SONIC_CR] &= ~SONIC_CR_TXP;\n s->regs[SONIC_ISR] |= SONIC_ISR_TXDN;\n dp8393x_update_irq(s);\n}", "project": "qemu", "hash": 258794860106692447895072609340176223318, "size": 113, "commit_id": "331d2ac9ea307c990dc86e6493e8f0c48d14bb33", "message": "dp8393x: switch to use qemu_receive_packet() for loopback packet\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 <ppandit@redhat.com>\nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 <philmd@redhat.com\nSigned-off-by: Jason Wang <jasowang@redhat.com>", "target": 0, "dataset": "other", "idx": 476446}
  979. {"func": "int main(int argc, char **argv, char **envp)\n{\n // dynamically load shared library\n#ifdef DYNLOAD\n if (!uc_dyn_load(NULL, 0)) {\n printf(\"Error dynamically loading shared library.\\n\");\n printf(\"Please check that unicorn.dll/unicorn.so is available as well as\\n\");\n printf(\"any other dependent dll/so files.\\n\");\n printf(\"The easiest way is to place them in the same directory as this app.\\n\");\n return 1;\n }\n#endif\n \n test_arm();\n printf(\"==========================\\n\");\n test_thumb();\n\n // dynamically free shared library\n#ifdef DYNLOAD\n uc_dyn_free();\n#endif\n \n return 0;\n}", "project": "unicorn", "hash": 185725400238744388569454420547208561164, "size": 24, "commit_id": "bf1713d9e011b55ca1f502a6779fc4722b4bb077", "message": "Add arm ite blocks samples from #853 (#1381)", "target": 1, "dataset": "other", "idx": 214241}
  980. {"func": "int main(int argc, char **argv, char **envp)\n{\n // dynamically load shared library\n#ifdef DYNLOAD\n if (!uc_dyn_load(NULL, 0)) {\n printf(\"Error dynamically loading shared library.\\n\");\n printf(\"Please check that unicorn.dll/unicorn.so is available as well as\\n\");\n printf(\"any other dependent dll/so files.\\n\");\n printf(\"The easiest way is to place them in the same directory as this app.\\n\");\n return 1;\n }\n#endif\n \n test_arm();\n printf(\"==========================\\n\");\n test_thumb();\n printf(\"==========================\\n\");\n test_thumb_ite();\n // dynamically free shared library\n#ifdef DYNLOAD\n uc_dyn_free();\n#endif\n \n return 0;\n}", "project": "unicorn", "hash": 168497872221435357783029447196663285853, "size": 25, "commit_id": "bf1713d9e011b55ca1f502a6779fc4722b4bb077", "message": "Add arm ite blocks samples from #853 (#1381)", "target": 0, "dataset": "other", "idx": 476899}
  981. {"func": "xsltAddKey(xsltStylesheetPtr style, const xmlChar *name,\n\t const xmlChar *nameURI, const xmlChar *match,\n\t const xmlChar *use, xmlNodePtr inst) {\n xsltKeyDefPtr key;\n xmlChar *pattern = NULL;\n int current, end, start, i = 0;\n\n if ((style == NULL) || (name == NULL) || (match == NULL) || (use == NULL))\n\treturn(-1);\n\n#ifdef WITH_XSLT_DEBUG_KEYS\n xsltGenericDebug(xsltGenericDebugContext,\n\t\"Add key %s, match %s, use %s\\n\", name, match, use);\n#endif\n\n key = xsltNewKeyDef(name, nameURI);\n key->match = xmlStrdup(match);\n key->use = xmlStrdup(use);\n key->inst = inst;\n key->nsList = xmlGetNsList(inst->doc, inst);\n if (key->nsList != NULL) {\n while (key->nsList[i] != NULL)\n\t i++;\n }\n key->nsNr = i;\n\n /*\n * Split the | and register it as as many keys\n */\n current = end = 0;\n while (match[current] != 0) {\n\tstart = current;\n\twhile (IS_BLANK_CH(match[current]))\n\t current++;\n\tend = current;\n\twhile ((match[end] != 0) && (match[end] != '|')) {\n\t if (match[end] == '[') {\n\t end = skipPredicate(match, end);\n\t\tif (end <= 0) {\n\t\t xsltTransformError(NULL, style, inst,\n\t\t \"key pattern is malformed: %s\",\n\t\t\t\t key->match);\n\t\t if (style != NULL) style->errors++;\n\t\t goto error;\n\t\t}\n\t } else\n\t\tend++;\n\t}\n\tif (current == end) {\n\t xsltTransformError(NULL, style, inst,\n\t\t\t \"key pattern is empty\\n\");\n\t if (style != NULL) style->errors++;\n\t goto error;\n\t}\n\tif (match[start] != '/') {\n\t pattern = xmlStrcat(pattern, (xmlChar *)\"//\");\n\t if (pattern == NULL) {\n\t\tif (style != NULL) style->errors++;\n\t\tgoto error;\n\t }\n\t}\n\tpattern = xmlStrncat(pattern, &match[start], end - start);\n\tif (pattern == NULL) {\n\t if (style != NULL) style->errors++;\n\t goto error;\n\t}\n\n\tif (match[end] == '|') {\n\t pattern = xmlStrcat(pattern, (xmlChar *)\"|\");\n\t end++;\n\t}\n\tcurrent = end;\n }\n#ifdef WITH_XSLT_DEBUG_KEYS\n xsltGenericDebug(xsltGenericDebugContext,\n\t\" resulting pattern %s\\n\", pattern);\n#endif\n /*\n * XSLT-1: \"It is an error for the value of either the use\n * attribute or the match attribute to contain a\n * VariableReference.\"\n * TODO: We should report a variable-reference at compile-time.\n * Maybe a search for \"$\", if it occurs outside of quotation\n * marks, could be sufficient.\n */\n#ifdef XML_XPATH_NOVAR\n key->comp = xsltXPathCompileFlags(style, pattern, XML_XPATH_NOVAR);\n#else\n key->comp = xsltXPathCompile(style, pattern);\n#endif\n if (key->comp == NULL) {\n\txsltTransformError(NULL, style, inst,\n\t\t\"xsl:key : XPath pattern compilation failed '%s'\\n\",\n\t\t pattern);\n\tif (style != NULL) style->errors++;\n }\n#ifdef XML_XPATH_NOVAR\n key->usecomp = xsltXPathCompileFlags(style, use, XML_XPATH_NOVAR);\n#else\n key->usecomp = xsltXPathCompile(style, use);\n#endif\n if (key->usecomp == NULL) {\n\txsltTransformError(NULL, style, inst,\n\t\t\"xsl:key : XPath pattern compilation failed '%s'\\n\",\n\t\t use);\n\tif (style != NULL) style->errors++;\n }\n\n /*\n * Sometimes the stylesheet writer use the order to ease the\n * resolution of keys when they are dependant, keep the provided\n * order so add the new one at the end.\n */\n if (style->keys == NULL) {\n\tstyle->keys = key;\n } else {\n xsltKeyDefPtr prev = style->keys;\n\n\twhile (prev->next != NULL)\n\t prev = prev->next;\n\n\tprev->next = key;\n }\n key->next = NULL;\n\nerror:\n if (pattern != NULL)\n\txmlFree(pattern);\n return(0);\n}", "project": "libxslt", "hash": 70118853582158048870420962848114929649, "size": 130, "commit_id": "dc11b6b379a882418093ecc8adf11f6166682e8d", "message": "Fix crash with empty xsl:key/@match attribute\n\nSee https://bugzilla.gnome.org/show_bug.cgi?id=685328\n\nAlso improve some xsl:key error messages.", "target": 1, "dataset": "other", "idx": 214313}
  982. {"func": "xsltAddKey(xsltStylesheetPtr style, const xmlChar *name,\n\t const xmlChar *nameURI, const xmlChar *match,\n\t const xmlChar *use, xmlNodePtr inst) {\n xsltKeyDefPtr key;\n xmlChar *pattern = NULL;\n int current, end, start, i = 0;\n\n if ((style == NULL) || (name == NULL) || (match == NULL) || (use == NULL))\n\treturn(-1);\n\n#ifdef WITH_XSLT_DEBUG_KEYS\n xsltGenericDebug(xsltGenericDebugContext,\n\t\"Add key %s, match %s, use %s\\n\", name, match, use);\n#endif\n\n key = xsltNewKeyDef(name, nameURI);\n key->match = xmlStrdup(match);\n key->use = xmlStrdup(use);\n key->inst = inst;\n key->nsList = xmlGetNsList(inst->doc, inst);\n if (key->nsList != NULL) {\n while (key->nsList[i] != NULL)\n\t i++;\n }\n key->nsNr = i;\n\n /*\n * Split the | and register it as as many keys\n */\n current = end = 0;\n while (match[current] != 0) {\n\tstart = current;\n\twhile (IS_BLANK_CH(match[current]))\n\t current++;\n\tend = current;\n\twhile ((match[end] != 0) && (match[end] != '|')) {\n\t if (match[end] == '[') {\n\t end = skipPredicate(match, end);\n\t\tif (end <= 0) {\n\t\t xsltTransformError(NULL, style, inst,\n\t\t \"xsl:key : 'match' pattern is malformed: %s\",\n\t\t key->match);\n\t\t if (style != NULL) style->errors++;\n\t\t goto error;\n\t\t}\n\t } else\n\t\tend++;\n\t}\n\tif (current == end) {\n\t xsltTransformError(NULL, style, inst,\n\t\t\t \"xsl:key : 'match' pattern is empty\\n\");\n\t if (style != NULL) style->errors++;\n\t goto error;\n\t}\n\tif (match[start] != '/') {\n\t pattern = xmlStrcat(pattern, (xmlChar *)\"//\");\n\t if (pattern == NULL) {\n\t\tif (style != NULL) style->errors++;\n\t\tgoto error;\n\t }\n\t}\n\tpattern = xmlStrncat(pattern, &match[start], end - start);\n\tif (pattern == NULL) {\n\t if (style != NULL) style->errors++;\n\t goto error;\n\t}\n\n\tif (match[end] == '|') {\n\t pattern = xmlStrcat(pattern, (xmlChar *)\"|\");\n\t end++;\n\t}\n\tcurrent = end;\n }\n if (pattern == NULL) {\n xsltTransformError(NULL, style, inst,\n \"xsl:key : 'match' pattern is empty\\n\");\n if (style != NULL) style->errors++;\n goto error;\n }\n#ifdef WITH_XSLT_DEBUG_KEYS\n xsltGenericDebug(xsltGenericDebugContext,\n\t\" resulting pattern %s\\n\", pattern);\n#endif\n /*\n * XSLT-1: \"It is an error for the value of either the use\n * attribute or the match attribute to contain a\n * VariableReference.\"\n * TODO: We should report a variable-reference at compile-time.\n * Maybe a search for \"$\", if it occurs outside of quotation\n * marks, could be sufficient.\n */\n#ifdef XML_XPATH_NOVAR\n key->comp = xsltXPathCompileFlags(style, pattern, XML_XPATH_NOVAR);\n#else\n key->comp = xsltXPathCompile(style, pattern);\n#endif\n if (key->comp == NULL) {\n\txsltTransformError(NULL, style, inst,\n\t\t\"xsl:key : 'match' pattern compilation failed '%s'\\n\",\n\t\t pattern);\n\tif (style != NULL) style->errors++;\n }\n#ifdef XML_XPATH_NOVAR\n key->usecomp = xsltXPathCompileFlags(style, use, XML_XPATH_NOVAR);\n#else\n key->usecomp = xsltXPathCompile(style, use);\n#endif\n if (key->usecomp == NULL) {\n\txsltTransformError(NULL, style, inst,\n\t\t\"xsl:key : 'use' expression compilation failed '%s'\\n\",\n\t\t use);\n\tif (style != NULL) style->errors++;\n }\n\n /*\n * Sometimes the stylesheet writer use the order to ease the\n * resolution of keys when they are dependant, keep the provided\n * order so add the new one at the end.\n */\n if (style->keys == NULL) {\n\tstyle->keys = key;\n } else {\n xsltKeyDefPtr prev = style->keys;\n\n\twhile (prev->next != NULL)\n\t prev = prev->next;\n\n\tprev->next = key;\n }\n key->next = NULL;\n\nerror:\n if (pattern != NULL)\n\txmlFree(pattern);\n return(0);\n}", "project": "libxslt", "hash": 54032911179374397987084442578242302169, "size": 136, "commit_id": "dc11b6b379a882418093ecc8adf11f6166682e8d", "message": "Fix crash with empty xsl:key/@match attribute\n\nSee https://bugzilla.gnome.org/show_bug.cgi?id=685328\n\nAlso improve some xsl:key error messages.", "target": 0, "dataset": "other", "idx": 477535}
  983. {"func": "static bool l2cap_check_enc_key_size(struct hci_conn *hcon)\n{\n\t/* The minimum encryption key size needs to be enforced by the\n\t * host stack before establishing any L2CAP connections. The\n\t * specification in theory allows a minimum of 1, but to align\n\t * BR/EDR and LE transports, a minimum of 7 is chosen.\n\t *\n\t * This check might also be called for unencrypted connections\n\t * that have no key size requirements. Ensure that the link is\n\t * actually encrypted before enforcing a key size.\n\t */\n\treturn (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags) ||\n\t\thcon->enc_key_size > HCI_MIN_ENC_KEY_SIZE);\n}", "project": "linux", "hash": 212269271340075918698506153323878239453, "size": 14, "commit_id": "eca94432934fe5f141d084f2e36ee2c0e614cc04", "message": "Bluetooth: Fix faulty expression for minimum encryption key size check\n\nFix minimum encryption key size check so that HCI_MIN_ENC_KEY_SIZE is\nalso allowed as stated in the comment.\n\nThis bug caused connection problems with devices having maximum\nencryption key size of 7 octets (56-bit).\n\nFixes: 693cd8ce3f88 (\"Bluetooth: Fix regression with minimum encryption key size alignment\")\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203997\nSigned-off-by: Matias Karhumaa <matias.karhumaa@gmail.com>\nCc: stable@vger.kernel.org\nSigned-off-by: Marcel Holtmann <marcel@holtmann.org>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 1, "dataset": "other", "idx": 214365}
  984. {"func": "static bool l2cap_check_enc_key_size(struct hci_conn *hcon)\n{\n\t/* The minimum encryption key size needs to be enforced by the\n\t * host stack before establishing any L2CAP connections. The\n\t * specification in theory allows a minimum of 1, but to align\n\t * BR/EDR and LE transports, a minimum of 7 is chosen.\n\t *\n\t * This check might also be called for unencrypted connections\n\t * that have no key size requirements. Ensure that the link is\n\t * actually encrypted before enforcing a key size.\n\t */\n\treturn (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags) ||\n\t\thcon->enc_key_size >= HCI_MIN_ENC_KEY_SIZE);\n}", "project": "linux", "hash": 319380273204740789729762662276611703691, "size": 14, "commit_id": "eca94432934fe5f141d084f2e36ee2c0e614cc04", "message": "Bluetooth: Fix faulty expression for minimum encryption key size check\n\nFix minimum encryption key size check so that HCI_MIN_ENC_KEY_SIZE is\nalso allowed as stated in the comment.\n\nThis bug caused connection problems with devices having maximum\nencryption key size of 7 octets (56-bit).\n\nFixes: 693cd8ce3f88 (\"Bluetooth: Fix regression with minimum encryption key size alignment\")\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203997\nSigned-off-by: Matias Karhumaa <matias.karhumaa@gmail.com>\nCc: stable@vger.kernel.org\nSigned-off-by: Marcel Holtmann <marcel@holtmann.org>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "target": 0, "dataset": "other", "idx": 477978}
  985. {"func": "spell_read_tree(\n FILE\t*fd,\n char_u\t**bytsp,\n idx_T\t**idxsp,\n int\t\tprefixtree,\t/* TRUE for the prefix tree */\n int\t\tprefixcnt)\t/* when \"prefixtree\" is TRUE: prefix count */\n{\n int\t\tlen;\n int\t\tidx;\n char_u\t*bp;\n idx_T\t*ip;\n\n /* The tree size was computed when writing the file, so that we can\n * allocate it as one long block. <nodecount> */\n len = get4c(fd);\n if (len < 0)\n\treturn SP_TRUNCERROR;\n if (len > 0)\n {\n\t/* Allocate the byte array. */\n\tbp = lalloc((long_u)len, TRUE);\n\tif (bp == NULL)\n\t return SP_OTHERERROR;\n\t*bytsp = bp;\n\n\t/* Allocate the index array. */\n\tip = (idx_T *)lalloc_clear((long_u)(len * sizeof(int)), TRUE);\n\tif (ip == NULL)\n\t return SP_OTHERERROR;\n\t*idxsp = ip;\n\n\t/* Recursively read the tree and store it in the array. */\n\tidx = read_tree_node(fd, bp, ip, len, 0, prefixtree, prefixcnt);\n\tif (idx < 0)\n\t return idx;\n }\n return 0;\n}", "project": "vim", "hash": 299704516071114356319960105952359505097, "size": 38, "commit_id": "399c297aa93afe2c0a39e2a1b3f972aebba44c9d", "message": "patch 8.0.0322: possible overflow with corrupted spell file\n\nProblem: Possible overflow with spell file where the tree length is\n corrupted.\nSolution: Check for an invalid length (suggested by shqking)", "target": 1, "dataset": "other", "idx": 214366}
  986. {"func": "spell_read_tree(\n FILE\t*fd,\n char_u\t**bytsp,\n idx_T\t**idxsp,\n int\t\tprefixtree,\t/* TRUE for the prefix tree */\n int\t\tprefixcnt)\t/* when \"prefixtree\" is TRUE: prefix count */\n{\n int\t\tlen;\n int\t\tidx;\n char_u\t*bp;\n idx_T\t*ip;\n\n /* The tree size was computed when writing the file, so that we can\n * allocate it as one long block. <nodecount> */\n len = get4c(fd);\n if (len < 0)\n\treturn SP_TRUNCERROR;\n if (len >= 0x3ffffff)\n\t/* Invalid length, multiply with sizeof(int) would overflow. */\n\treturn SP_FORMERROR;\n if (len > 0)\n {\n\t/* Allocate the byte array. */\n\tbp = lalloc((long_u)len, TRUE);\n\tif (bp == NULL)\n\t return SP_OTHERERROR;\n\t*bytsp = bp;\n\n\t/* Allocate the index array. */\n\tip = (idx_T *)lalloc_clear((long_u)(len * sizeof(int)), TRUE);\n\tif (ip == NULL)\n\t return SP_OTHERERROR;\n\t*idxsp = ip;\n\n\t/* Recursively read the tree and store it in the array. */\n\tidx = read_tree_node(fd, bp, ip, len, 0, prefixtree, prefixcnt);\n\tif (idx < 0)\n\t return idx;\n }\n return 0;\n}", "project": "vim", "hash": 297151306078472778214889535736355052234, "size": 41, "commit_id": "399c297aa93afe2c0a39e2a1b3f972aebba44c9d", "message": "patch 8.0.0322: possible overflow with corrupted spell file\n\nProblem: Possible overflow with spell file where the tree length is\n corrupted.\nSolution: Check for an invalid length (suggested by shqking)", "target": 0, "dataset": "other", "idx": 478041}
  987. {"func": "static void host_callback(void *arg, int status, int timeouts,\n unsigned char *abuf, int alen)\n{\n struct host_query *hquery = (struct host_query*)arg;\n int addinfostatus = ARES_SUCCESS;\n hquery->timeouts += timeouts;\n hquery->remaining--;\n\n if (status == ARES_SUCCESS)\n {\n addinfostatus = ares__parse_into_addrinfo(abuf, alen, hquery->ai);\n }\n else if (status == ARES_EDESTRUCTION)\n {\n end_hquery(hquery, status);\n }\n\n if (!hquery->remaining)\n {\n if (addinfostatus != ARES_SUCCESS)\n {\n /* error in parsing result e.g. no memory */\n end_hquery(hquery, addinfostatus);\n }\n else if (hquery->ai->nodes)\n {\n /* at least one query ended with ARES_SUCCESS */\n end_hquery(hquery, ARES_SUCCESS);\n }\n else if (status == ARES_ENOTFOUND)\n {\n next_lookup(hquery, status);\n }\n else\n {\n end_hquery(hquery, status);\n }\n }\n\n /* at this point we keep on waiting for the next query to finish */\n}", "project": "c-ares", "hash": 338428520293637615587127648198461687166, "size": 41, "commit_id": "1cc7e83c3bdfaafbc5919c95025592d8de3a170e", "message": "Prevent possible double-free in ares_getaddrinfo() if ares_destroy() is called\n\nIn the event that ares_destroy() is called prior to ares_getaddrinfo() completing,\nit would result in an invalid read and double-free due to calling end_hquery() twice.\n\nReported By: Jann Horn @ Google Project Zero", "target": 1, "dataset": "other", "idx": 214405}
  988. {"func": "static void host_callback(void *arg, int status, int timeouts,\n unsigned char *abuf, int alen)\n{\n struct host_query *hquery = (struct host_query*)arg;\n int addinfostatus = ARES_SUCCESS;\n hquery->timeouts += timeouts;\n hquery->remaining--;\n\n if (status == ARES_SUCCESS)\n {\n addinfostatus = ares__parse_into_addrinfo(abuf, alen, hquery->ai);\n }\n else if (status == ARES_EDESTRUCTION)\n {\n end_hquery(hquery, status);\n return;\n }\n\n if (!hquery->remaining)\n {\n if (addinfostatus != ARES_SUCCESS)\n {\n /* error in parsing result e.g. no memory */\n end_hquery(hquery, addinfostatus);\n }\n else if (hquery->ai->nodes)\n {\n /* at least one query ended with ARES_SUCCESS */\n end_hquery(hquery, ARES_SUCCESS);\n }\n else if (status == ARES_ENOTFOUND)\n {\n next_lookup(hquery, status);\n }\n else\n {\n end_hquery(hquery, status);\n }\n }\n\n /* at this point we keep on waiting for the next query to finish */\n}", "project": "c-ares", "hash": 65112642692504141750909294658666282062, "size": 42, "commit_id": "1cc7e83c3bdfaafbc5919c95025592d8de3a170e", "message": "Prevent possible double-free in ares_getaddrinfo() if ares_destroy() is called\n\nIn the event that ares_destroy() is called prior to ares_getaddrinfo() completing,\nit would result in an invalid read and double-free due to calling end_hquery() twice.\n\nReported By: Jann Horn @ Google Project Zero", "target": 0, "dataset": "other", "idx": 478396}
  989. {"func": "opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)\n{\n png_structp png = NULL;\n png_infop info = NULL;\n double gamma;\n int bit_depth, interlace_type, compression_type, filter_type;\n OPJ_UINT32 i;\n png_uint_32 width, height = 0U;\n int color_type;\n FILE *reader = NULL;\n OPJ_BYTE** rows = NULL;\n OPJ_INT32* row32s = NULL;\n /* j2k: */\n opj_image_t *image = NULL;\n opj_image_cmptparm_t cmptparm[4];\n OPJ_UINT32 nr_comp;\n OPJ_BYTE sigbuf[8];\n convert_XXx32s_C1R cvtXXTo32s = NULL;\n convert_32s_CXPX cvtCxToPx = NULL;\n OPJ_INT32* planes[4];\n\n if ((reader = fopen(read_idf, \"rb\")) == NULL) {\n fprintf(stderr, \"pngtoimage: can not open %s\\n\", read_idf);\n return NULL;\n }\n\n if (fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE\n || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0) {\n fprintf(stderr, \"pngtoimage: %s is no valid PNG file\\n\", read_idf);\n goto fin;\n }\n\n if ((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,\n NULL, NULL, NULL)) == NULL) {\n goto fin;\n }\n if ((info = png_create_info_struct(png)) == NULL) {\n goto fin;\n }\n\n if (setjmp(png_jmpbuf(png))) {\n goto fin;\n }\n\n png_init_io(png, reader);\n png_set_sig_bytes(png, MAGIC_SIZE);\n\n png_read_info(png, info);\n\n if (png_get_IHDR(png, info, &width, &height,\n &bit_depth, &color_type, &interlace_type,\n &compression_type, &filter_type) == 0) {\n goto fin;\n }\n\n /* png_set_expand():\n * expand paletted images to RGB, expand grayscale images of\n * less than 8-bit depth to 8-bit depth, and expand tRNS chunks\n * to alpha channels.\n */\n if (color_type == PNG_COLOR_TYPE_PALETTE) {\n png_set_expand(png);\n }\n\n if (png_get_valid(png, info, PNG_INFO_tRNS)) {\n png_set_expand(png);\n }\n /* We might wan't to expand background */\n /*\n if(png_get_valid(png, info, PNG_INFO_bKGD)) {\n png_color_16p bgnd;\n png_get_bKGD(png, info, &bgnd);\n png_set_background(png, bgnd, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);\n }\n */\n\n if (!png_get_gAMA(png, info, &gamma)) {\n gamma = 1.0;\n }\n\n /* we're not displaying but converting, screen gamma == 1.0 */\n png_set_gamma(png, 1.0, gamma);\n\n png_read_update_info(png, info);\n\n color_type = png_get_color_type(png, info);\n\n switch (color_type) {\n case PNG_COLOR_TYPE_GRAY:\n nr_comp = 1;\n break;\n case PNG_COLOR_TYPE_GRAY_ALPHA:\n nr_comp = 2;\n break;\n case PNG_COLOR_TYPE_RGB:\n nr_comp = 3;\n break;\n case PNG_COLOR_TYPE_RGB_ALPHA:\n nr_comp = 4;\n break;\n default:\n fprintf(stderr, \"pngtoimage: colortype %d is not supported\\n\", color_type);\n goto fin;\n }\n cvtCxToPx = convert_32s_CXPX_LUT[nr_comp];\n bit_depth = png_get_bit_depth(png, info);\n\n switch (bit_depth) {\n case 1:\n case 2:\n case 4:\n case 8:\n cvtXXTo32s = convert_XXu32s_C1R_LUT[bit_depth];\n break;\n case 16: /* 16 bpp is specific to PNG */\n cvtXXTo32s = convert_16u32s_C1R;\n break;\n default:\n fprintf(stderr, \"pngtoimage: bit depth %d is not supported\\n\", bit_depth);\n goto fin;\n }\n\n\n rows = (OPJ_BYTE**)calloc(height + 1, sizeof(OPJ_BYTE*));\n if (rows == NULL) {\n fprintf(stderr, \"pngtoimage: memory out\\n\");\n goto fin;\n }\n for (i = 0; i < height; ++i) {\n rows[i] = (OPJ_BYTE*)malloc(png_get_rowbytes(png, info));\n if (rows[i] == NULL) {\n fprintf(stderr, \"pngtoimage: memory out\\n\");\n goto fin;\n }\n }\n png_read_image(png, rows);\n\n /* Create image */\n memset(cmptparm, 0, sizeof(cmptparm));\n for (i = 0; i < nr_comp; ++i) {\n cmptparm[i].prec = (OPJ_UINT32)bit_depth;\n /* bits_per_pixel: 8 or 16 */\n cmptparm[i].bpp = (OPJ_UINT32)bit_depth;\n cmptparm[i].sgnd = 0;\n cmptparm[i].dx = (OPJ_UINT32)params->subsampling_dx;\n cmptparm[i].dy = (OPJ_UINT32)params->subsampling_dy;\n cmptparm[i].w = (OPJ_UINT32)width;\n cmptparm[i].h = (OPJ_UINT32)height;\n }\n\n image = opj_image_create(nr_comp, &cmptparm[0],\n (nr_comp > 2U) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY);\n if (image == NULL) {\n goto fin;\n }\n image->x0 = (OPJ_UINT32)params->image_offset_x0;\n image->y0 = (OPJ_UINT32)params->image_offset_y0;\n image->x1 = (OPJ_UINT32)(image->x0 + (width - 1) * (OPJ_UINT32)\n params->subsampling_dx + 1 + image->x0);\n image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)\n params->subsampling_dy + 1 + image->y0);\n\n row32s = (OPJ_INT32 *)malloc((size_t)width * nr_comp * sizeof(OPJ_INT32));\n if (row32s == NULL) {\n goto fin;\n }\n\n /* Set alpha channel */\n image->comps[nr_comp - 1U].alpha = 1U - (nr_comp & 1U);\n\n for (i = 0; i < nr_comp; i++) {\n planes[i] = image->comps[i].data;\n }\n\n for (i = 0; i < height; ++i) {\n cvtXXTo32s(rows[i], row32s, (OPJ_SIZE_T)width * nr_comp);\n cvtCxToPx(row32s, planes, width);\n planes[0] += width;\n planes[1] += width;\n planes[2] += width;\n planes[3] += width;\n }\nfin:\n if (rows) {\n for (i = 0; i < height; ++i)\n if (rows[i]) {\n free(rows[i]);\n }\n free(rows);\n }\n if (row32s) {\n free(row32s);\n }\n if (png) {\n png_destroy_read_struct(&png, &info, NULL);\n }\n\n fclose(reader);\n\n return image;\n\n}/* pngtoimage() */", "project": "openjpeg", "hash": 316530901664567822353293166039183109395, "size": 202, "commit_id": "b2072402b7e14d22bba6fb8cde2a1e9996e9a919", "message": "pngtoimage(): fix wrong computation of x1,y1 if -d option is used, that would result in a heap buffer overflow (fixes #1284)", "target": 1, "dataset": "other", "idx": 214409}
  990. {"func": "opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)\n{\n png_structp png = NULL;\n png_infop info = NULL;\n double gamma;\n int bit_depth, interlace_type, compression_type, filter_type;\n OPJ_UINT32 i;\n png_uint_32 width, height = 0U;\n int color_type;\n FILE *reader = NULL;\n OPJ_BYTE** rows = NULL;\n OPJ_INT32* row32s = NULL;\n /* j2k: */\n opj_image_t *image = NULL;\n opj_image_cmptparm_t cmptparm[4];\n OPJ_UINT32 nr_comp;\n OPJ_BYTE sigbuf[8];\n convert_XXx32s_C1R cvtXXTo32s = NULL;\n convert_32s_CXPX cvtCxToPx = NULL;\n OPJ_INT32* planes[4];\n\n if ((reader = fopen(read_idf, \"rb\")) == NULL) {\n fprintf(stderr, \"pngtoimage: can not open %s\\n\", read_idf);\n return NULL;\n }\n\n if (fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE\n || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0) {\n fprintf(stderr, \"pngtoimage: %s is no valid PNG file\\n\", read_idf);\n goto fin;\n }\n\n if ((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,\n NULL, NULL, NULL)) == NULL) {\n goto fin;\n }\n if ((info = png_create_info_struct(png)) == NULL) {\n goto fin;\n }\n\n if (setjmp(png_jmpbuf(png))) {\n goto fin;\n }\n\n png_init_io(png, reader);\n png_set_sig_bytes(png, MAGIC_SIZE);\n\n png_read_info(png, info);\n\n if (png_get_IHDR(png, info, &width, &height,\n &bit_depth, &color_type, &interlace_type,\n &compression_type, &filter_type) == 0) {\n goto fin;\n }\n\n /* png_set_expand():\n * expand paletted images to RGB, expand grayscale images of\n * less than 8-bit depth to 8-bit depth, and expand tRNS chunks\n * to alpha channels.\n */\n if (color_type == PNG_COLOR_TYPE_PALETTE) {\n png_set_expand(png);\n }\n\n if (png_get_valid(png, info, PNG_INFO_tRNS)) {\n png_set_expand(png);\n }\n /* We might wan't to expand background */\n /*\n if(png_get_valid(png, info, PNG_INFO_bKGD)) {\n png_color_16p bgnd;\n png_get_bKGD(png, info, &bgnd);\n png_set_background(png, bgnd, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);\n }\n */\n\n if (!png_get_gAMA(png, info, &gamma)) {\n gamma = 1.0;\n }\n\n /* we're not displaying but converting, screen gamma == 1.0 */\n png_set_gamma(png, 1.0, gamma);\n\n png_read_update_info(png, info);\n\n color_type = png_get_color_type(png, info);\n\n switch (color_type) {\n case PNG_COLOR_TYPE_GRAY:\n nr_comp = 1;\n break;\n case PNG_COLOR_TYPE_GRAY_ALPHA:\n nr_comp = 2;\n break;\n case PNG_COLOR_TYPE_RGB:\n nr_comp = 3;\n break;\n case PNG_COLOR_TYPE_RGB_ALPHA:\n nr_comp = 4;\n break;\n default:\n fprintf(stderr, \"pngtoimage: colortype %d is not supported\\n\", color_type);\n goto fin;\n }\n cvtCxToPx = convert_32s_CXPX_LUT[nr_comp];\n bit_depth = png_get_bit_depth(png, info);\n\n switch (bit_depth) {\n case 1:\n case 2:\n case 4:\n case 8:\n cvtXXTo32s = convert_XXu32s_C1R_LUT[bit_depth];\n break;\n case 16: /* 16 bpp is specific to PNG */\n cvtXXTo32s = convert_16u32s_C1R;\n break;\n default:\n fprintf(stderr, \"pngtoimage: bit depth %d is not supported\\n\", bit_depth);\n goto fin;\n }\n\n\n rows = (OPJ_BYTE**)calloc(height + 1, sizeof(OPJ_BYTE*));\n if (rows == NULL) {\n fprintf(stderr, \"pngtoimage: memory out\\n\");\n goto fin;\n }\n for (i = 0; i < height; ++i) {\n rows[i] = (OPJ_BYTE*)malloc(png_get_rowbytes(png, info));\n if (rows[i] == NULL) {\n fprintf(stderr, \"pngtoimage: memory out\\n\");\n goto fin;\n }\n }\n png_read_image(png, rows);\n\n /* Create image */\n memset(cmptparm, 0, sizeof(cmptparm));\n for (i = 0; i < nr_comp; ++i) {\n cmptparm[i].prec = (OPJ_UINT32)bit_depth;\n /* bits_per_pixel: 8 or 16 */\n cmptparm[i].bpp = (OPJ_UINT32)bit_depth;\n cmptparm[i].sgnd = 0;\n cmptparm[i].dx = (OPJ_UINT32)params->subsampling_dx;\n cmptparm[i].dy = (OPJ_UINT32)params->subsampling_dy;\n cmptparm[i].w = (OPJ_UINT32)width;\n cmptparm[i].h = (OPJ_UINT32)height;\n }\n\n image = opj_image_create(nr_comp, &cmptparm[0],\n (nr_comp > 2U) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY);\n if (image == NULL) {\n goto fin;\n }\n image->x0 = (OPJ_UINT32)params->image_offset_x0;\n image->y0 = (OPJ_UINT32)params->image_offset_y0;\n image->x1 = (OPJ_UINT32)(image->x0 + (width - 1) * (OPJ_UINT32)\n params->subsampling_dx + 1);\n image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)\n params->subsampling_dy + 1);\n\n row32s = (OPJ_INT32 *)malloc((size_t)width * nr_comp * sizeof(OPJ_INT32));\n if (row32s == NULL) {\n goto fin;\n }\n\n /* Set alpha channel */\n image->comps[nr_comp - 1U].alpha = 1U - (nr_comp & 1U);\n\n for (i = 0; i < nr_comp; i++) {\n planes[i] = image->comps[i].data;\n }\n\n for (i = 0; i < height; ++i) {\n cvtXXTo32s(rows[i], row32s, (OPJ_SIZE_T)width * nr_comp);\n cvtCxToPx(row32s, planes, width);\n planes[0] += width;\n planes[1] += width;\n planes[2] += width;\n planes[3] += width;\n }\nfin:\n if (rows) {\n for (i = 0; i < height; ++i)\n if (rows[i]) {\n free(rows[i]);\n }\n free(rows);\n }\n if (row32s) {\n free(row32s);\n }\n if (png) {\n png_destroy_read_struct(&png, &info, NULL);\n }\n\n fclose(reader);\n\n return image;\n\n}/* pngtoimage() */", "project": "openjpeg", "hash": 111527323522954682670053156159153319598, "size": 202, "commit_id": "b2072402b7e14d22bba6fb8cde2a1e9996e9a919", "message": "pngtoimage(): fix wrong computation of x1,y1 if -d option is used, that would result in a heap buffer overflow (fixes #1284)", "target": 0, "dataset": "other", "idx": 478420}
  991. {"func": "static void slc_bump(struct slcan *sl)\n{\n\tstruct sk_buff *skb;\n\tstruct can_frame cf;\n\tint i, tmp;\n\tu32 tmpid;\n\tchar *cmd = sl->rbuff;\n\n\tcf.can_id = 0;\n\n\tswitch (*cmd) {\n\tcase 'r':\n\t\tcf.can_id = CAN_RTR_FLAG;\n\t\t/* fallthrough */\n\tcase 't':\n\t\t/* store dlc ASCII value and terminate SFF CAN ID string */\n\t\tcf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN];\n\t\tsl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN] = 0;\n\t\t/* point to payload data behind the dlc */\n\t\tcmd += SLC_CMD_LEN + SLC_SFF_ID_LEN + 1;\n\t\tbreak;\n\tcase 'R':\n\t\tcf.can_id = CAN_RTR_FLAG;\n\t\t/* fallthrough */\n\tcase 'T':\n\t\tcf.can_id |= CAN_EFF_FLAG;\n\t\t/* store dlc ASCII value and terminate EFF CAN ID string */\n\t\tcf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN];\n\t\tsl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN] = 0;\n\t\t/* point to payload data behind the dlc */\n\t\tcmd += SLC_CMD_LEN + SLC_EFF_ID_LEN + 1;\n\t\tbreak;\n\tdefault:\n\t\treturn;\n\t}\n\n\tif (kstrtou32(sl->rbuff + SLC_CMD_LEN, 16, &tmpid))\n\t\treturn;\n\n\tcf.can_id |= tmpid;\n\n\t/* get can_dlc from sanitized ASCII value */\n\tif (cf.can_dlc >= '0' && cf.can_dlc < '9')\n\t\tcf.can_dlc -= '0';\n\telse\n\t\treturn;\n\n\t*(u64 *) (&cf.data) = 0; /* clear payload */\n\n\t/* RTR frames may have a dlc > 0 but they never have any data bytes */\n\tif (!(cf.can_id & CAN_RTR_FLAG)) {\n\t\tfor (i = 0; i < cf.can_dlc; i++) {\n\t\t\ttmp = hex_to_bin(*cmd++);\n\t\t\tif (tmp < 0)\n\t\t\t\treturn;\n\t\t\tcf.data[i] = (tmp << 4);\n\t\t\ttmp = hex_to_bin(*cmd++);\n\t\t\tif (tmp < 0)\n\t\t\t\treturn;\n\t\t\tcf.data[i] |= tmp;\n\t\t}\n\t}\n\n\tskb = dev_alloc_skb(sizeof(struct can_frame) +\n\t\t\t sizeof(struct can_skb_priv));\n\tif (!skb)\n\t\treturn;\n\n\tskb->dev = sl->dev;\n\tskb->protocol = htons(ETH_P_CAN);\n\tskb->pkt_type = PACKET_BROADCAST;\n\tskb->ip_summed = CHECKSUM_UNNECESSARY;\n\n\tcan_skb_reserve(skb);\n\tcan_skb_prv(skb)->ifindex = sl->dev->ifindex;\n\tcan_skb_prv(skb)->skbcnt = 0;\n\n\tskb_put_data(skb, &cf, sizeof(struct can_frame));\n\n\tsl->dev->stats.rx_packets++;\n\tsl->dev->stats.rx_bytes += cf.can_dlc;\n\tnetif_rx_ni(skb);\n}", "project": "linux", "hash": 21373888120245067949221535188537720172, "size": 83, "commit_id": "b9258a2cece4ec1f020715fe3554bc2e360f6264", "message": "slcan: Don't transmit uninitialized stack data in padding\n\nstruct can_frame contains some padding which is not explicitly zeroed in\nslc_bump. This uninitialized data will then be transmitted if the stack\ninitialization hardening feature is not enabled (CONFIG_INIT_STACK_ALL).\n\nThis commit just zeroes the whole struct including the padding.\n\nSigned-off-by: Richard Palethorpe <rpalethorpe@suse.com>\nFixes: a1044e36e457 (\"can: add slcan driver for serial/USB-serial CAN adapters\")\nReviewed-by: Kees Cook <keescook@chromium.org>\nCc: linux-can@vger.kernel.org\nCc: netdev@vger.kernel.org\nCc: security@kernel.org\nCc: wg@grandegger.com\nCc: mkl@pengutronix.de\nCc: davem@davemloft.net\nAcked-by: Marc Kleine-Budde <mkl@pengutronix.de>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 1, "dataset": "other", "idx": 214425}
  992. {"func": "static void slc_bump(struct slcan *sl)\n{\n\tstruct sk_buff *skb;\n\tstruct can_frame cf;\n\tint i, tmp;\n\tu32 tmpid;\n\tchar *cmd = sl->rbuff;\n\n\tmemset(&cf, 0, sizeof(cf));\n\n\tswitch (*cmd) {\n\tcase 'r':\n\t\tcf.can_id = CAN_RTR_FLAG;\n\t\t/* fallthrough */\n\tcase 't':\n\t\t/* store dlc ASCII value and terminate SFF CAN ID string */\n\t\tcf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN];\n\t\tsl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN] = 0;\n\t\t/* point to payload data behind the dlc */\n\t\tcmd += SLC_CMD_LEN + SLC_SFF_ID_LEN + 1;\n\t\tbreak;\n\tcase 'R':\n\t\tcf.can_id = CAN_RTR_FLAG;\n\t\t/* fallthrough */\n\tcase 'T':\n\t\tcf.can_id |= CAN_EFF_FLAG;\n\t\t/* store dlc ASCII value and terminate EFF CAN ID string */\n\t\tcf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN];\n\t\tsl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN] = 0;\n\t\t/* point to payload data behind the dlc */\n\t\tcmd += SLC_CMD_LEN + SLC_EFF_ID_LEN + 1;\n\t\tbreak;\n\tdefault:\n\t\treturn;\n\t}\n\n\tif (kstrtou32(sl->rbuff + SLC_CMD_LEN, 16, &tmpid))\n\t\treturn;\n\n\tcf.can_id |= tmpid;\n\n\t/* get can_dlc from sanitized ASCII value */\n\tif (cf.can_dlc >= '0' && cf.can_dlc < '9')\n\t\tcf.can_dlc -= '0';\n\telse\n\t\treturn;\n\n\t/* RTR frames may have a dlc > 0 but they never have any data bytes */\n\tif (!(cf.can_id & CAN_RTR_FLAG)) {\n\t\tfor (i = 0; i < cf.can_dlc; i++) {\n\t\t\ttmp = hex_to_bin(*cmd++);\n\t\t\tif (tmp < 0)\n\t\t\t\treturn;\n\t\t\tcf.data[i] = (tmp << 4);\n\t\t\ttmp = hex_to_bin(*cmd++);\n\t\t\tif (tmp < 0)\n\t\t\t\treturn;\n\t\t\tcf.data[i] |= tmp;\n\t\t}\n\t}\n\n\tskb = dev_alloc_skb(sizeof(struct can_frame) +\n\t\t\t sizeof(struct can_skb_priv));\n\tif (!skb)\n\t\treturn;\n\n\tskb->dev = sl->dev;\n\tskb->protocol = htons(ETH_P_CAN);\n\tskb->pkt_type = PACKET_BROADCAST;\n\tskb->ip_summed = CHECKSUM_UNNECESSARY;\n\n\tcan_skb_reserve(skb);\n\tcan_skb_prv(skb)->ifindex = sl->dev->ifindex;\n\tcan_skb_prv(skb)->skbcnt = 0;\n\n\tskb_put_data(skb, &cf, sizeof(struct can_frame));\n\n\tsl->dev->stats.rx_packets++;\n\tsl->dev->stats.rx_bytes += cf.can_dlc;\n\tnetif_rx_ni(skb);\n}", "project": "linux", "hash": 325057014109399130748004599861744385783, "size": 81, "commit_id": "b9258a2cece4ec1f020715fe3554bc2e360f6264", "message": "slcan: Don't transmit uninitialized stack data in padding\n\nstruct can_frame contains some padding which is not explicitly zeroed in\nslc_bump. This uninitialized data will then be transmitted if the stack\ninitialization hardening feature is not enabled (CONFIG_INIT_STACK_ALL).\n\nThis commit just zeroes the whole struct including the padding.\n\nSigned-off-by: Richard Palethorpe <rpalethorpe@suse.com>\nFixes: a1044e36e457 (\"can: add slcan driver for serial/USB-serial CAN adapters\")\nReviewed-by: Kees Cook <keescook@chromium.org>\nCc: linux-can@vger.kernel.org\nCc: netdev@vger.kernel.org\nCc: security@kernel.org\nCc: wg@grandegger.com\nCc: mkl@pengutronix.de\nCc: davem@davemloft.net\nAcked-by: Marc Kleine-Budde <mkl@pengutronix.de>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "target": 0, "dataset": "other", "idx": 478530}
  993. {"func": "static unsigned int xdr_set_page_base(struct xdr_stream *xdr,\n\t\t\t\t unsigned int base, unsigned int len)\n{\n\tunsigned int pgnr;\n\tunsigned int maxlen;\n\tunsigned int pgoff;\n\tunsigned int pgend;\n\tvoid *kaddr;\n\n\tmaxlen = xdr->buf->page_len;\n\tif (base >= maxlen) {\n\t\tbase = maxlen;\n\t\tmaxlen = 0;\n\t} else\n\t\tmaxlen -= base;\n\tif (len > maxlen)\n\t\tlen = maxlen;\n\n\txdr_stream_page_set_pos(xdr, base);\n\tbase += xdr->buf->page_base;\n\n\tpgnr = base >> PAGE_SHIFT;\n\txdr->page_ptr = &xdr->buf->pages[pgnr];\n\tkaddr = page_address(*xdr->page_ptr);\n\n\tpgoff = base & ~PAGE_MASK;\n\txdr->p = (__be32*)(kaddr + pgoff);\n\n\tpgend = pgoff + len;\n\tif (pgend > PAGE_SIZE)\n\t\tpgend = PAGE_SIZE;\n\txdr->end = (__be32*)(kaddr + pgend);\n\txdr->iov = NULL;\n\treturn len;\n}", "project": "linux", "hash": 274422321753562622361315728373118052641, "size": 35, "commit_id": "6d1c0f3d28f98ea2736128ed3e46821496dc3a8c", "message": "sunrpc: Avoid a KASAN slab-out-of-bounds bug in xdr_set_page_base()\n\nThis seems to happen fairly easily during READ_PLUS testing on NFS v4.2.\nI found that we could end up accessing xdr->buf->pages[pgnr] with a pgnr\ngreater than the number of pages in the array. So let's just return\nearly if we're setting base to a point at the end of the page data and\nlet xdr_set_tail_base() handle setting up the buffer pointers instead.\n\nSigned-off-by: Anna Schumaker <Anna.Schumaker@Netapp.com>\nFixes: 8d86e373b0ef (\"SUNRPC: Clean up helpers xdr_set_iov() and xdr_set_page_base()\")\nSigned-off-by: Trond Myklebust <trond.myklebust@hammerspace.com>", "target": 1, "dataset": "other", "idx": 214890}
  994. {"func": "static unsigned int xdr_set_page_base(struct xdr_stream *xdr,\n\t\t\t\t unsigned int base, unsigned int len)\n{\n\tunsigned int pgnr;\n\tunsigned int maxlen;\n\tunsigned int pgoff;\n\tunsigned int pgend;\n\tvoid *kaddr;\n\n\tmaxlen = xdr->buf->page_len;\n\tif (base >= maxlen)\n\t\treturn 0;\n\telse\n\t\tmaxlen -= base;\n\tif (len > maxlen)\n\t\tlen = maxlen;\n\n\txdr_stream_page_set_pos(xdr, base);\n\tbase += xdr->buf->page_base;\n\n\tpgnr = base >> PAGE_SHIFT;\n\txdr->page_ptr = &xdr->buf->pages[pgnr];\n\tkaddr = page_address(*xdr->page_ptr);\n\n\tpgoff = base & ~PAGE_MASK;\n\txdr->p = (__be32*)(kaddr + pgoff);\n\n\tpgend = pgoff + len;\n\tif (pgend > PAGE_SIZE)\n\t\tpgend = PAGE_SIZE;\n\txdr->end = (__be32*)(kaddr + pgend);\n\txdr->iov = NULL;\n\treturn len;\n}", "project": "linux", "hash": 272280587655938095471660267479071957383, "size": 34, "commit_id": "6d1c0f3d28f98ea2736128ed3e46821496dc3a8c", "message": "sunrpc: Avoid a KASAN slab-out-of-bounds bug in xdr_set_page_base()\n\nThis seems to happen fairly easily during READ_PLUS testing on NFS v4.2.\nI found that we could end up accessing xdr->buf->pages[pgnr] with a pgnr\ngreater than the number of pages in the array. So let's just return\nearly if we're setting base to a point at the end of the page data and\nlet xdr_set_tail_base() handle setting up the buffer pointers instead.\n\nSigned-off-by: Anna Schumaker <Anna.Schumaker@Netapp.com>\nFixes: 8d86e373b0ef (\"SUNRPC: Clean up helpers xdr_set_iov() and xdr_set_page_base()\")\nSigned-off-by: Trond Myklebust <trond.myklebust@hammerspace.com>", "target": 0, "dataset": "other", "idx": 481051}
  995. {"func": "static void suboption(struct Curl_easy *data)\n{\n struct curl_slist *v;\n unsigned char temp[2048];\n ssize_t bytes_written;\n size_t len;\n int err;\n char varname[128] = \"\";\n char varval[128] = \"\";\n struct TELNET *tn = data->req.p.telnet;\n struct connectdata *conn = data->conn;\n\n printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn) + 2);\n switch(CURL_SB_GET(tn)) {\n case CURL_TELOPT_TTYPE:\n len = strlen(tn->subopt_ttype) + 4 + 2;\n msnprintf((char *)temp, sizeof(temp),\n \"%c%c%c%c%s%c%c\", CURL_IAC, CURL_SB, CURL_TELOPT_TTYPE,\n CURL_TELQUAL_IS, tn->subopt_ttype, CURL_IAC, CURL_SE);\n bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);\n if(bytes_written < 0) {\n err = SOCKERRNO;\n failf(data,\"Sending data failed (%d)\",err);\n }\n printsub(data, '>', &temp[2], len-2);\n break;\n case CURL_TELOPT_XDISPLOC:\n len = strlen(tn->subopt_xdisploc) + 4 + 2;\n msnprintf((char *)temp, sizeof(temp),\n \"%c%c%c%c%s%c%c\", CURL_IAC, CURL_SB, CURL_TELOPT_XDISPLOC,\n CURL_TELQUAL_IS, tn->subopt_xdisploc, CURL_IAC, CURL_SE);\n bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);\n if(bytes_written < 0) {\n err = SOCKERRNO;\n failf(data,\"Sending data failed (%d)\",err);\n }\n printsub(data, '>', &temp[2], len-2);\n break;\n case CURL_TELOPT_NEW_ENVIRON:\n msnprintf((char *)temp, sizeof(temp),\n \"%c%c%c%c\", CURL_IAC, CURL_SB, CURL_TELOPT_NEW_ENVIRON,\n CURL_TELQUAL_IS);\n len = 4;\n\n for(v = tn->telnet_vars; v; v = v->next) {\n size_t tmplen = (strlen(v->data) + 1);\n /* Add the variable only if it fits */\n if(len + tmplen < (int)sizeof(temp)-6) {\n if(sscanf(v->data, \"%127[^,],%127s\", varname, varval)) {\n msnprintf((char *)&temp[len], sizeof(temp) - len,\n \"%c%s%c%s\", CURL_NEW_ENV_VAR, varname,\n CURL_NEW_ENV_VALUE, varval);\n len += tmplen;\n }\n }\n }\n msnprintf((char *)&temp[len], sizeof(temp) - len,\n \"%c%c\", CURL_IAC, CURL_SE);\n len += 2;\n bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);\n if(bytes_written < 0) {\n err = SOCKERRNO;\n failf(data,\"Sending data failed (%d)\",err);\n }\n printsub(data, '>', &temp[2], len-2);\n break;\n }\n return;\n}", "project": "curl", "hash": 294290589936532991240501967275180184556, "size": 69, "commit_id": "39ce47f219b09c380b81f89fe54ac586c8db6bde", "message": "telnet: check sscanf() for correct number of matches\n\nCVE-2021-22898\n\nBug: https://curl.se/docs/CVE-2021-22898.html", "target": 1, "dataset": "other", "idx": 214926}
  996. {"func": "static void suboption(struct Curl_easy *data)\n{\n struct curl_slist *v;\n unsigned char temp[2048];\n ssize_t bytes_written;\n size_t len;\n int err;\n char varname[128] = \"\";\n char varval[128] = \"\";\n struct TELNET *tn = data->req.p.telnet;\n struct connectdata *conn = data->conn;\n\n printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn) + 2);\n switch(CURL_SB_GET(tn)) {\n case CURL_TELOPT_TTYPE:\n len = strlen(tn->subopt_ttype) + 4 + 2;\n msnprintf((char *)temp, sizeof(temp),\n \"%c%c%c%c%s%c%c\", CURL_IAC, CURL_SB, CURL_TELOPT_TTYPE,\n CURL_TELQUAL_IS, tn->subopt_ttype, CURL_IAC, CURL_SE);\n bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);\n if(bytes_written < 0) {\n err = SOCKERRNO;\n failf(data,\"Sending data failed (%d)\",err);\n }\n printsub(data, '>', &temp[2], len-2);\n break;\n case CURL_TELOPT_XDISPLOC:\n len = strlen(tn->subopt_xdisploc) + 4 + 2;\n msnprintf((char *)temp, sizeof(temp),\n \"%c%c%c%c%s%c%c\", CURL_IAC, CURL_SB, CURL_TELOPT_XDISPLOC,\n CURL_TELQUAL_IS, tn->subopt_xdisploc, CURL_IAC, CURL_SE);\n bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);\n if(bytes_written < 0) {\n err = SOCKERRNO;\n failf(data,\"Sending data failed (%d)\",err);\n }\n printsub(data, '>', &temp[2], len-2);\n break;\n case CURL_TELOPT_NEW_ENVIRON:\n msnprintf((char *)temp, sizeof(temp),\n \"%c%c%c%c\", CURL_IAC, CURL_SB, CURL_TELOPT_NEW_ENVIRON,\n CURL_TELQUAL_IS);\n len = 4;\n\n for(v = tn->telnet_vars; v; v = v->next) {\n size_t tmplen = (strlen(v->data) + 1);\n /* Add the variable only if it fits */\n if(len + tmplen < (int)sizeof(temp)-6) {\n if(sscanf(v->data, \"%127[^,],%127s\", varname, varval) == 2) {\n msnprintf((char *)&temp[len], sizeof(temp) - len,\n \"%c%s%c%s\", CURL_NEW_ENV_VAR, varname,\n CURL_NEW_ENV_VALUE, varval);\n len += tmplen;\n }\n }\n }\n msnprintf((char *)&temp[len], sizeof(temp) - len,\n \"%c%c\", CURL_IAC, CURL_SE);\n len += 2;\n bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);\n if(bytes_written < 0) {\n err = SOCKERRNO;\n failf(data,\"Sending data failed (%d)\",err);\n }\n printsub(data, '>', &temp[2], len-2);\n break;\n }\n return;\n}", "project": "curl", "hash": 162263181786713465891376018168428301129, "size": 69, "commit_id": "39ce47f219b09c380b81f89fe54ac586c8db6bde", "message": "telnet: check sscanf() for correct number of matches\n\nCVE-2021-22898\n\nBug: https://curl.se/docs/CVE-2021-22898.html", "target": 0, "dataset": "other", "idx": 481492}
  997. {"func": "void LibRaw::identify_process_dng_fields()\n{\n\tif (!dng_version) return;\n\tint c;\n\t{\n\t\t/* copy DNG data from per-IFD field to color.dng */\n\t\tint iifd = find_ifd_by_offset(data_offset);\n\t\tint pifd = find_ifd_by_offset(thumb_offset);\n\n#define CFAROUND(value, filters) \\\n filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) \\\n : value\n\n#define IFDCOLORINDEX(ifd, subset, bit) \\\n (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) \\\n ? ifd \\\n : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1)\n\n#define IFDLEVELINDEX(ifd, bit) \\\n (tiff_ifd[ifd].dng_levels.parsedfields & bit) \\\n ? ifd \\\n : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1)\n\n#define COPYARR(to, from) memmove(&to, &from, sizeof(from))\n\n\t\tif (iifd < (int)tiff_nifds && iifd >= 0)\n\t\t{\n\t\t\tint sidx;\n\t\t\t// Per field, not per structure\n\t\t\tif (!(imgdata.params.raw_processing_options &\n\t\t\t\tLIBRAW_PROCESSING_DONT_CHECK_DNG_ILLUMINANT))\n\t\t\t{\n\t\t\t\tint illidx[2], cmidx[2], calidx[2], abidx;\n\t\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t\t{\n\t\t\t\t\tillidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_ILLUMINANT);\n\t\t\t\t\tcmidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_COLORMATRIX);\n\t\t\t\t\tcalidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_CALIBRATION);\n\t\t\t\t}\n\t\t\t\tabidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE);\n\t\t\t\t// Data found, all in same ifd, illuminants are inited\n\t\t\t\tif (illidx[0] >= 0 && illidx[0] < (int)tiff_nifds &&\n\t\t\t\t\tillidx[0] == illidx[1] && illidx[0] == cmidx[0] &&\n\t\t\t\t\tillidx[0] == cmidx[1] &&\n\t\t\t\t\ttiff_ifd[illidx[0]].dng_color[0].illuminant > 0 &&\n\t\t\t\t\ttiff_ifd[illidx[0]].dng_color[1].illuminant > 0)\n\t\t\t\t{\n\t\t\t\t\tsidx = illidx[0]; // => selected IFD\n\t\t\t\t\tdouble cc[4][4], cm[4][3], cam_xyz[4][3];\n\t\t\t\t\t// CM -> Color Matrix\n\t\t\t\t\t// CC -> Camera calibration\n\t\t\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\t\t\t\tfor (int i = 0; i < 4; i++)\n\t\t\t\t\t\t\tcc[j][i] = i == j;\n\t\t\t\t\tint colidx = -1;\n\n\t\t\t\t\t// IS D65 here?\n\t\t\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (tiff_ifd[sidx].dng_color[i].illuminant == LIBRAW_WBI_D65)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcolidx = i;\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\t// Other daylight-type ill\n\t\t\t\t\tif (colidx < 0)\n\t\t\t\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint ill = tiff_ifd[sidx].dng_color[i].illuminant;\n\t\t\t\t\t\t\tif (ill == LIBRAW_WBI_Daylight || ill == LIBRAW_WBI_D55 ||\n\t\t\t\t\t\t\t\till == LIBRAW_WBI_D75 || ill == LIBRAW_WBI_D50 ||\n\t\t\t\t\t\t\t\till == LIBRAW_WBI_Flash)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcolidx = i;\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\tif (colidx >= 0) // Selected\n\t\t\t\t\t{\n\t\t\t\t\t\t// Init camera matrix from DNG\n\t\t\t\t\t\tFORCC for (int j = 0; j < 3; j++) cm[c][j] =\n\t\t\t\t\t\t\ttiff_ifd[sidx].dng_color[colidx].colormatrix[c][j];\n\n\t\t\t\t\t\tif (calidx[colidx] == sidx)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (int i = 0; i < colors; i++)\n\t\t\t\t\t\t\t\tFORCC\n\t\t\t\t\t\t\t\tcc[i][c] = tiff_ifd[sidx].dng_color[colidx].calibration[i][c];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (abidx == sidx)\n\t\t\t\t\t\t\tfor (int i = 0; i < colors; i++)\n\t\t\t\t\t\t\t\tFORCC cc[i][c] *= tiff_ifd[sidx].dng_levels.analogbalance[i];\n\t\t\t\t\t\tint j;\n\t\t\t\t\t\tFORCC for (int i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0;\n\t\t\t\t\t\t\tj < colors; j++)\n\t\t\t\t\t\t\tcam_xyz[c][i] +=\n\t\t\t\t\t\t\tcc[c][j] * cm[j][i]; // add AsShotXY later * xyz[i];\n\t\t\t\t\t\tcam_xyz_coeff(cmatrix, cam_xyz);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool noFujiDNGCrop = makeIs(LIBRAW_CAMERAMAKER_Fujifilm)\n\t\t\t\t&& (!strcmp(normalized_model, \"S3Pro\")\n\t\t\t\t\t|| !strcmp(normalized_model, \"S5Pro\")\n\t\t\t\t\t|| !strcmp(normalized_model, \"S2Pro\"));\n\n\t\t\tif (!noFujiDNGCrop &&\n\t\t\t\t(imgdata.params.raw_processing_options &LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP))\n\t\t\t{\n\t\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN);\n\t\t\t\tint sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE);\n\t\t\t\tif (sidx >= 0 && sidx == sidx2 &&\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.default_crop[2] > 0 &&\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.default_crop[3] > 0)\n\t\t\t\t{\n\t\t\t\t\tint lm = tiff_ifd[sidx].dng_levels.default_crop[0];\n\t\t\t\t\tint lmm = CFAROUND(lm, filters);\n\t\t\t\t\tint tm = tiff_ifd[sidx].dng_levels.default_crop[1];\n\t\t\t\t\tint tmm = CFAROUND(tm, filters);\n\t\t\t\t\tint ww = tiff_ifd[sidx].dng_levels.default_crop[2];\n\t\t\t\t\tint hh = tiff_ifd[sidx].dng_levels.default_crop[3];\n\t\t\t\t\tif (lmm > lm)\n\t\t\t\t\t\tww -= (lmm - lm);\n\t\t\t\t\tif (tmm > tm)\n\t\t\t\t\t\thh -= (tmm - tm);\n\t\t\t\t\tif (left_margin + lm + ww <= raw_width &&\n\t\t\t\t\t\ttop_margin + tm + hh <= raw_height)\n\t\t\t\t\t{\n\t\t\t\t\t\tleft_margin += lmm;\n\t\t\t\t\t\ttop_margin += tmm;\n\t\t\t\t\t\twidth = ww;\n\t\t\t\t\t\theight = hh;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(imgdata.color.dng_color[0].parsedfields &\n\t\t\t\tLIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)\n\t\t\t{\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\tCOPYARR(imgdata.color.dng_color[0].forwardmatrix,\n\t\t\t\t\t\ttiff_ifd[sidx].dng_color[0].forwardmatrix);\n\t\t\t}\n\t\t\tif (!(imgdata.color.dng_color[1].parsedfields &\n\t\t\t\tLIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)\n\t\t\t{\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\tCOPYARR(imgdata.color.dng_color[1].forwardmatrix,\n\t\t\t\t\t\ttiff_ifd[sidx].dng_color[1].forwardmatrix);\n\t\t\t}\n\t\t\tfor (int ss = 0; ss < 2; ss++)\n\t\t\t{\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\tCOPYARR(imgdata.color.dng_color[ss].colormatrix,\n\t\t\t\t\t\ttiff_ifd[sidx].dng_color[ss].colormatrix);\n\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\tCOPYARR(imgdata.color.dng_color[ss].calibration,\n\t\t\t\t\t\ttiff_ifd[sidx].dng_color[ss].calibration);\n\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\timgdata.color.dng_color[ss].illuminant =\n\t\t\t\t\ttiff_ifd[sidx].dng_color[ss].illuminant;\n\t\t\t}\n\t\t\t// Levels\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE);\n\t\t\tif (sidx >= 0)\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.analogbalance,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.analogbalance);\n\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BASELINEEXPOSURE);\n\t\t\tif (sidx >= 0)\n\t\t\t\timgdata.color.dng_levels.baseline_exposure =\n\t\t\t\ttiff_ifd[sidx].dng_levels.baseline_exposure;\n\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE);\n\t\t\tif (sidx >= 0 && tiff_ifd[sidx].dng_levels.dng_whitelevel[0])\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.dng_whitelevel,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_whitelevel);\n\t\t\telse if (tiff_ifd[iifd].sample_format <= 2 && tiff_ifd[iifd].bps > 0 && tiff_ifd[iifd].bps < 32)\n\t\t\t\tFORC4\n\t\t\t\timgdata.color.dng_levels.dng_whitelevel[c] = (1 << tiff_ifd[iifd].bps) - 1;\n\n\n\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ASSHOTNEUTRAL);\n\t\t\tif (sidx >= 0)\n\t\t\t{\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.asshotneutral,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.asshotneutral);\n\t\t\t\tif (imgdata.color.dng_levels.asshotneutral[0])\n\t\t\t\t{\n\t\t\t\t\tcam_mul[3] = 0;\n\t\t\t\t\tFORCC\n\t\t\t\t\t\tif (fabs(imgdata.color.dng_levels.asshotneutral[c]) > 0.0001)\n\t\t\t\t\t\t\tcam_mul[c] = 1 / imgdata.color.dng_levels.asshotneutral[c];\n\t\t\t\t}\n\t\t\t}\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK);\n\t\t\tif (sidx >= 0)\n\t\t\t{\n\t\t\t\timgdata.color.dng_levels.dng_fblack =\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_fblack;\n\t\t\t\timgdata.color.dng_levels.dng_black =\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_black;\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.dng_cblack,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_cblack);\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.dng_fcblack,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_fcblack);\n\t\t\t}\n\n\n\t\t\tif (pifd >= 0)\n\t\t\t{\n\t\t\t\tsidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\timgdata.color.dng_levels.preview_colorspace =\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.preview_colorspace;\n\t\t\t}\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2);\n\t\t\tif (sidx >= 0)\n\t\t\t\tmeta_offset = tiff_ifd[sidx].opcode2_offset;\n\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE);\n\t\t\tINT64 linoff = -1;\n\t\t\tint linlen = 0;\n\t\t\tif (sidx >= 0)\n\t\t\t{\n\t\t\t\tlinoff = tiff_ifd[sidx].lineartable_offset;\n\t\t\t\tlinlen = tiff_ifd[sidx].lineartable_len;\n\t\t\t}\n\n\t\t\tif (linoff >= 0 && linlen > 0)\n\t\t\t{\n\t\t\t\tINT64 pos = ftell(ifp);\n\t\t\t\tfseek(ifp, linoff, SEEK_SET);\n\t\t\t\tlinear_table(linlen);\n\t\t\t\tfseek(ifp, pos, SEEK_SET);\n\t\t\t}\n\t\t\t// Need to add curve too\n\t\t}\n\t\t/* Copy DNG black level to LibRaw's */\n\t\tif (load_raw == &LibRaw::lossy_dng_load_raw)\n\t\t{\n\t\t\tmaximum = 0xffff;\n\t\t\tFORC4 imgdata.color.linear_max[c] = imgdata.color.dng_levels.dng_whitelevel[c] = 0xffff;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmaximum = imgdata.color.dng_levels.dng_whitelevel[0];\n\t\t}\n\t\tblack = imgdata.color.dng_levels.dng_black;\n\n\t\tif (tiff_samples == 2 && imgdata.color.dng_levels.dng_cblack[4] * imgdata.color.dng_levels.dng_cblack[5] * tiff_samples\n\t\t\t== imgdata.color.dng_levels.dng_cblack[LIBRAW_CBLACK_SIZE - 1])\n\t\t{\n\t\t\tunsigned ff = filters;\n\t\t\tif (filters > 999 && colors == 3)\n\t\t\t\tfilters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) &\n\t\t\t\tfilters << 1;\n\n\t\t\t/* Special case, Fuji SuperCCD dng */\n\t\t\tint csum[4] = { 0,0,0,0 }, ccount[4] = { 0,0,0,0 };\n\t\t\tint i = 6 + shot_select;\n\t\t\tfor (unsigned row = 0; row < imgdata.color.dng_levels.dng_cblack[4]; row++)\n\t\t\t\tfor (unsigned col = 0; col < imgdata.color.dng_levels.dng_cblack[5]; col++)\n\t\t\t\t{\n\t\t\t\t\tcsum[FC(row, col)] += imgdata.color.dng_levels.dng_cblack[i];\n\t\t\t\t\tccount[FC(row, col)]++;\n\t\t\t\t\ti += tiff_samples;\n\t\t\t\t}\n\t\t\tfor (int c = 0; c < 4; c++)\n\t\t\t\tif (ccount[c])\n\t\t\t\t\timgdata.color.dng_levels.dng_cblack[c] += csum[c] / ccount[c];\n\t\t\timgdata.color.dng_levels.dng_cblack[4] = imgdata.color.dng_levels.dng_cblack[5] = 0;\n\t\t\tfilters = ff;\n\t\t}\n\t\telse if (tiff_samples > 2 && tiff_samples <= 4 && imgdata.color.dng_levels.dng_cblack[4] * imgdata.color.dng_levels.dng_cblack[5] * tiff_samples\n\t\t\t== imgdata.color.dng_levels.dng_cblack[LIBRAW_CBLACK_SIZE - 1])\n\t\t{\n\t\t\t/* Special case, per_channel blacks in RepeatDim, average for per-channel */\n\t\t\tint csum[4] = { 0,0,0,0 }, ccount[4] = { 0,0,0,0 };\n\t\t\tint i = 6;\n\t\t\tfor (unsigned row = 0; row < imgdata.color.dng_levels.dng_cblack[4]; row++)\n\t\t\t\tfor (unsigned col = 0; col < imgdata.color.dng_levels.dng_cblack[5]; col++)\n\t\t\t\t\tfor (unsigned c = 0; c < tiff_samples; c++)\n\t\t\t\t\t{\n\t\t\t\t\t\tcsum[c] += imgdata.color.dng_levels.dng_cblack[i];\n\t\t\t\t\t\tccount[c]++;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\tfor (int c = 0; c < 4; c++)\n\t\t\t\tif (ccount[c])\n\t\t\t\t\timgdata.color.dng_levels.dng_cblack[c] += csum[c] / ccount[c];\n\t\t\timgdata.color.dng_levels.dng_cblack[4] = imgdata.color.dng_levels.dng_cblack[5] = 0;\n\t\t}\n\n\t\tmemmove(cblack, imgdata.color.dng_levels.dng_cblack, sizeof(cblack));\n\n\t\tif (iifd < (int)tiff_nifds && iifd >= 0)\n\t\t{\n\t\t\tint sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINEARRESPONSELIMIT);\n\t\t\tif (sidx >= 0)\n\t\t\t{\n\t\t\t\timgdata.color.dng_levels.LinearResponseLimit =\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.LinearResponseLimit;\n\t\t\t\tif (imgdata.color.dng_levels.LinearResponseLimit > 0.1 &&\n\t\t\t\t\timgdata.color.dng_levels.LinearResponseLimit <= 1.0)\n\t\t\t\t{\n\t\t\t\t\t// And approx promote it to linear_max:\n\t\t\t\t\tint bl4 = 0, bl64 = 0;\n\t\t\t\t\tfor (int chan = 0; chan < colors && chan < 4; chan++)\n\t\t\t\t\t\tbl4 += cblack[chan];\n\t\t\t\t\tbl4 /= LIM(colors, 1, 4);\n\n\t\t\t\t\tif (cblack[4] * cblack[5] > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned cnt = 0;\n\t\t\t\t\t\tfor (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbl64 += cblack[c + 6];\n\t\t\t\t\t\t\tcnt++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbl64 /= LIM(cnt, 1, 4096);\n\t\t\t\t\t}\n\t\t\t\t\tint rblack = black + bl4 + bl64;\n\t\t\t\t\tfor (int chan = 0; chan < colors && chan < 4; chan++)\n\t\t\t\t\t\timgdata.color.linear_max[chan] =\n\t\t\t\t\t\t(maximum - rblack) *\n\t\t\t\t\t\timgdata.color.dng_levels.LinearResponseLimit +\n\t\t\t\t\t\trblack;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "project": "LibRaw", "hash": 208600525321410359156531031353922710019, "size": 344, "commit_id": "4feaed4dea636cee4fee010f615881ccf76a096d", "message": "limit loops to MIN(colors,4) in dng fields parser", "target": 1, "dataset": "other", "idx": 214990}
  998. {"func": "void LibRaw::identify_process_dng_fields()\n{\n\tif (!dng_version) return;\n\tint c;\n\t{\n\t\t/* copy DNG data from per-IFD field to color.dng */\n\t\tint iifd = find_ifd_by_offset(data_offset);\n\t\tint pifd = find_ifd_by_offset(thumb_offset);\n\n#define CFAROUND(value, filters) \\\n filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) \\\n : value\n\n#define IFDCOLORINDEX(ifd, subset, bit) \\\n (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) \\\n ? ifd \\\n : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1)\n\n#define IFDLEVELINDEX(ifd, bit) \\\n (tiff_ifd[ifd].dng_levels.parsedfields & bit) \\\n ? ifd \\\n : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1)\n\n#define COPYARR(to, from) memmove(&to, &from, sizeof(from))\n\n\t\tif (iifd < (int)tiff_nifds && iifd >= 0)\n\t\t{\n\t\t\tint sidx;\n\t\t\t// Per field, not per structure\n\t\t\tif (!(imgdata.params.raw_processing_options &\n\t\t\t\tLIBRAW_PROCESSING_DONT_CHECK_DNG_ILLUMINANT))\n\t\t\t{\n\t\t\t\tint illidx[2], cmidx[2], calidx[2], abidx;\n\t\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t\t{\n\t\t\t\t\tillidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_ILLUMINANT);\n\t\t\t\t\tcmidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_COLORMATRIX);\n\t\t\t\t\tcalidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_CALIBRATION);\n\t\t\t\t}\n\t\t\t\tabidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE);\n\t\t\t\t// Data found, all in same ifd, illuminants are inited\n\t\t\t\tif (illidx[0] >= 0 && illidx[0] < (int)tiff_nifds &&\n\t\t\t\t\tillidx[0] == illidx[1] && illidx[0] == cmidx[0] &&\n\t\t\t\t\tillidx[0] == cmidx[1] &&\n\t\t\t\t\ttiff_ifd[illidx[0]].dng_color[0].illuminant > 0 &&\n\t\t\t\t\ttiff_ifd[illidx[0]].dng_color[1].illuminant > 0)\n\t\t\t\t{\n\t\t\t\t\tsidx = illidx[0]; // => selected IFD\n\t\t\t\t\tdouble cc[4][4], cm[4][3], cam_xyz[4][3];\n\t\t\t\t\t// CM -> Color Matrix\n\t\t\t\t\t// CC -> Camera calibration\n\t\t\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\t\t\t\tfor (int i = 0; i < 4; i++)\n\t\t\t\t\t\t\tcc[j][i] = i == j;\n\t\t\t\t\tint colidx = -1;\n\n\t\t\t\t\t// IS D65 here?\n\t\t\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (tiff_ifd[sidx].dng_color[i].illuminant == LIBRAW_WBI_D65)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcolidx = i;\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\t// Other daylight-type ill\n\t\t\t\t\tif (colidx < 0)\n\t\t\t\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint ill = tiff_ifd[sidx].dng_color[i].illuminant;\n\t\t\t\t\t\t\tif (ill == LIBRAW_WBI_Daylight || ill == LIBRAW_WBI_D55 ||\n\t\t\t\t\t\t\t\till == LIBRAW_WBI_D75 || ill == LIBRAW_WBI_D50 ||\n\t\t\t\t\t\t\t\till == LIBRAW_WBI_Flash)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcolidx = i;\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\tif (colidx >= 0) // Selected\n\t\t\t\t\t{\n\t\t\t\t\t\t// Init camera matrix from DNG\n\t\t\t\t\t\tFORCC for (int j = 0; j < 3; j++) cm[c][j] =\n\t\t\t\t\t\t\ttiff_ifd[sidx].dng_color[colidx].colormatrix[c][j];\n\n\t\t\t\t\t\tif (calidx[colidx] == sidx)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (int i = 0; i < colors && i < 4; i++)\n\t\t\t\t\t\t\t\tFORCC\n\t\t\t\t\t\t\t\tcc[i][c] = tiff_ifd[sidx].dng_color[colidx].calibration[i][c];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (abidx == sidx)\n\t\t\t\t\t\t\tfor (int i = 0; i < colors && i < 4; i++)\n\t\t\t\t\t\t\t\tFORCC cc[i][c] *= tiff_ifd[sidx].dng_levels.analogbalance[i];\n\t\t\t\t\t\tint j;\n\t\t\t\t\t\tFORCC for (int i = 0; i < 3; i++) \n for (cam_xyz[c][i] = j = 0; j < colors && j < 4; j++)\n\t\t\t\t\t\t\t cam_xyz[c][i] +=\n\t\t\t\t\t\t\t cc[c][j] * cm[j][i]; // add AsShotXY later * xyz[i];\n\t\t\t\t\t\tcam_xyz_coeff(cmatrix, cam_xyz);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool noFujiDNGCrop = makeIs(LIBRAW_CAMERAMAKER_Fujifilm)\n\t\t\t\t&& (!strcmp(normalized_model, \"S3Pro\")\n\t\t\t\t\t|| !strcmp(normalized_model, \"S5Pro\")\n\t\t\t\t\t|| !strcmp(normalized_model, \"S2Pro\"));\n\n\t\t\tif (!noFujiDNGCrop &&\n\t\t\t\t(imgdata.params.raw_processing_options &LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP))\n\t\t\t{\n\t\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN);\n\t\t\t\tint sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE);\n\t\t\t\tif (sidx >= 0 && sidx == sidx2 &&\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.default_crop[2] > 0 &&\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.default_crop[3] > 0)\n\t\t\t\t{\n\t\t\t\t\tint lm = tiff_ifd[sidx].dng_levels.default_crop[0];\n\t\t\t\t\tint lmm = CFAROUND(lm, filters);\n\t\t\t\t\tint tm = tiff_ifd[sidx].dng_levels.default_crop[1];\n\t\t\t\t\tint tmm = CFAROUND(tm, filters);\n\t\t\t\t\tint ww = tiff_ifd[sidx].dng_levels.default_crop[2];\n\t\t\t\t\tint hh = tiff_ifd[sidx].dng_levels.default_crop[3];\n\t\t\t\t\tif (lmm > lm)\n\t\t\t\t\t\tww -= (lmm - lm);\n\t\t\t\t\tif (tmm > tm)\n\t\t\t\t\t\thh -= (tmm - tm);\n\t\t\t\t\tif (left_margin + lm + ww <= raw_width &&\n\t\t\t\t\t\ttop_margin + tm + hh <= raw_height)\n\t\t\t\t\t{\n\t\t\t\t\t\tleft_margin += lmm;\n\t\t\t\t\t\ttop_margin += tmm;\n\t\t\t\t\t\twidth = ww;\n\t\t\t\t\t\theight = hh;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(imgdata.color.dng_color[0].parsedfields &\n\t\t\t\tLIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)\n\t\t\t{\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\tCOPYARR(imgdata.color.dng_color[0].forwardmatrix,\n\t\t\t\t\t\ttiff_ifd[sidx].dng_color[0].forwardmatrix);\n\t\t\t}\n\t\t\tif (!(imgdata.color.dng_color[1].parsedfields &\n\t\t\t\tLIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)\n\t\t\t{\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\tCOPYARR(imgdata.color.dng_color[1].forwardmatrix,\n\t\t\t\t\t\ttiff_ifd[sidx].dng_color[1].forwardmatrix);\n\t\t\t}\n\t\t\tfor (int ss = 0; ss < 2; ss++)\n\t\t\t{\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\tCOPYARR(imgdata.color.dng_color[ss].colormatrix,\n\t\t\t\t\t\ttiff_ifd[sidx].dng_color[ss].colormatrix);\n\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\tCOPYARR(imgdata.color.dng_color[ss].calibration,\n\t\t\t\t\t\ttiff_ifd[sidx].dng_color[ss].calibration);\n\n\t\t\t\tsidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\timgdata.color.dng_color[ss].illuminant =\n\t\t\t\t\ttiff_ifd[sidx].dng_color[ss].illuminant;\n\t\t\t}\n\t\t\t// Levels\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE);\n\t\t\tif (sidx >= 0)\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.analogbalance,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.analogbalance);\n\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BASELINEEXPOSURE);\n\t\t\tif (sidx >= 0)\n\t\t\t\timgdata.color.dng_levels.baseline_exposure =\n\t\t\t\ttiff_ifd[sidx].dng_levels.baseline_exposure;\n\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE);\n\t\t\tif (sidx >= 0 && tiff_ifd[sidx].dng_levels.dng_whitelevel[0])\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.dng_whitelevel,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_whitelevel);\n\t\t\telse if (tiff_ifd[iifd].sample_format <= 2 && tiff_ifd[iifd].bps > 0 && tiff_ifd[iifd].bps < 32)\n\t\t\t\tFORC4\n\t\t\t\timgdata.color.dng_levels.dng_whitelevel[c] = (1 << tiff_ifd[iifd].bps) - 1;\n\n\n\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ASSHOTNEUTRAL);\n\t\t\tif (sidx >= 0)\n\t\t\t{\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.asshotneutral,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.asshotneutral);\n\t\t\t\tif (imgdata.color.dng_levels.asshotneutral[0])\n\t\t\t\t{\n\t\t\t\t\tcam_mul[3] = 0;\n\t\t\t\t\tFORCC\n\t\t\t\t\t\tif (fabs(imgdata.color.dng_levels.asshotneutral[c]) > 0.0001)\n\t\t\t\t\t\t\tcam_mul[c] = 1 / imgdata.color.dng_levels.asshotneutral[c];\n\t\t\t\t}\n\t\t\t}\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK);\n\t\t\tif (sidx >= 0)\n\t\t\t{\n\t\t\t\timgdata.color.dng_levels.dng_fblack =\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_fblack;\n\t\t\t\timgdata.color.dng_levels.dng_black =\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_black;\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.dng_cblack,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_cblack);\n\t\t\t\tCOPYARR(imgdata.color.dng_levels.dng_fcblack,\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.dng_fcblack);\n\t\t\t}\n\n\n\t\t\tif (pifd >= 0)\n\t\t\t{\n\t\t\t\tsidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS);\n\t\t\t\tif (sidx >= 0)\n\t\t\t\t\timgdata.color.dng_levels.preview_colorspace =\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.preview_colorspace;\n\t\t\t}\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2);\n\t\t\tif (sidx >= 0)\n\t\t\t\tmeta_offset = tiff_ifd[sidx].opcode2_offset;\n\n\t\t\tsidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE);\n\t\t\tINT64 linoff = -1;\n\t\t\tint linlen = 0;\n\t\t\tif (sidx >= 0)\n\t\t\t{\n\t\t\t\tlinoff = tiff_ifd[sidx].lineartable_offset;\n\t\t\t\tlinlen = tiff_ifd[sidx].lineartable_len;\n\t\t\t}\n\n\t\t\tif (linoff >= 0 && linlen > 0)\n\t\t\t{\n\t\t\t\tINT64 pos = ftell(ifp);\n\t\t\t\tfseek(ifp, linoff, SEEK_SET);\n\t\t\t\tlinear_table(linlen);\n\t\t\t\tfseek(ifp, pos, SEEK_SET);\n\t\t\t}\n\t\t\t// Need to add curve too\n\t\t}\n\t\t/* Copy DNG black level to LibRaw's */\n\t\tif (load_raw == &LibRaw::lossy_dng_load_raw)\n\t\t{\n\t\t\tmaximum = 0xffff;\n\t\t\tFORC4 imgdata.color.linear_max[c] = imgdata.color.dng_levels.dng_whitelevel[c] = 0xffff;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmaximum = imgdata.color.dng_levels.dng_whitelevel[0];\n\t\t}\n\t\tblack = imgdata.color.dng_levels.dng_black;\n\n\t\tif (tiff_samples == 2 && imgdata.color.dng_levels.dng_cblack[4] * imgdata.color.dng_levels.dng_cblack[5] * tiff_samples\n\t\t\t== imgdata.color.dng_levels.dng_cblack[LIBRAW_CBLACK_SIZE - 1])\n\t\t{\n\t\t\tunsigned ff = filters;\n\t\t\tif (filters > 999 && colors == 3)\n\t\t\t\tfilters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) &\n\t\t\t\tfilters << 1;\n\n\t\t\t/* Special case, Fuji SuperCCD dng */\n\t\t\tint csum[4] = { 0,0,0,0 }, ccount[4] = { 0,0,0,0 };\n\t\t\tint i = 6 + shot_select;\n\t\t\tfor (unsigned row = 0; row < imgdata.color.dng_levels.dng_cblack[4]; row++)\n\t\t\t\tfor (unsigned col = 0; col < imgdata.color.dng_levels.dng_cblack[5]; col++)\n\t\t\t\t{\n\t\t\t\t\tcsum[FC(row, col)] += imgdata.color.dng_levels.dng_cblack[i];\n\t\t\t\t\tccount[FC(row, col)]++;\n\t\t\t\t\ti += tiff_samples;\n\t\t\t\t}\n\t\t\tfor (int c = 0; c < 4; c++)\n\t\t\t\tif (ccount[c])\n\t\t\t\t\timgdata.color.dng_levels.dng_cblack[c] += csum[c] / ccount[c];\n\t\t\timgdata.color.dng_levels.dng_cblack[4] = imgdata.color.dng_levels.dng_cblack[5] = 0;\n\t\t\tfilters = ff;\n\t\t}\n\t\telse if (tiff_samples > 2 && tiff_samples <= 4 && imgdata.color.dng_levels.dng_cblack[4] * imgdata.color.dng_levels.dng_cblack[5] * tiff_samples\n\t\t\t== imgdata.color.dng_levels.dng_cblack[LIBRAW_CBLACK_SIZE - 1])\n\t\t{\n\t\t\t/* Special case, per_channel blacks in RepeatDim, average for per-channel */\n\t\t\tint csum[4] = { 0,0,0,0 }, ccount[4] = { 0,0,0,0 };\n\t\t\tint i = 6;\n\t\t\tfor (unsigned row = 0; row < imgdata.color.dng_levels.dng_cblack[4]; row++)\n\t\t\t\tfor (unsigned col = 0; col < imgdata.color.dng_levels.dng_cblack[5]; col++)\n\t\t\t\t\tfor (unsigned c = 0; c < tiff_samples && c < 4; c++)\n\t\t\t\t\t{\n\t\t\t\t\t\tcsum[c] += imgdata.color.dng_levels.dng_cblack[i];\n\t\t\t\t\t\tccount[c]++;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\tfor (int c = 0; c < 4; c++)\n\t\t\t\tif (ccount[c])\n\t\t\t\t\timgdata.color.dng_levels.dng_cblack[c] += csum[c] / ccount[c];\n\t\t\timgdata.color.dng_levels.dng_cblack[4] = imgdata.color.dng_levels.dng_cblack[5] = 0;\n\t\t}\n\n\t\tmemmove(cblack, imgdata.color.dng_levels.dng_cblack, sizeof(cblack));\n\n\t\tif (iifd < (int)tiff_nifds && iifd >= 0)\n\t\t{\n\t\t\tint sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINEARRESPONSELIMIT);\n\t\t\tif (sidx >= 0)\n\t\t\t{\n\t\t\t\timgdata.color.dng_levels.LinearResponseLimit =\n\t\t\t\t\ttiff_ifd[sidx].dng_levels.LinearResponseLimit;\n\t\t\t\tif (imgdata.color.dng_levels.LinearResponseLimit > 0.1 &&\n\t\t\t\t\timgdata.color.dng_levels.LinearResponseLimit <= 1.0)\n\t\t\t\t{\n\t\t\t\t\t// And approx promote it to linear_max:\n\t\t\t\t\tint bl4 = 0, bl64 = 0;\n\t\t\t\t\tfor (int chan = 0; chan < colors && chan < 4; chan++)\n\t\t\t\t\t\tbl4 += cblack[chan];\n\t\t\t\t\tbl4 /= LIM(colors, 1, 4);\n\n\t\t\t\t\tif (cblack[4] * cblack[5] > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned cnt = 0;\n\t\t\t\t\t\tfor (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbl64 += cblack[c + 6];\n\t\t\t\t\t\t\tcnt++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbl64 /= LIM(cnt, 1, 4096);\n\t\t\t\t\t}\n\t\t\t\t\tint rblack = black + bl4 + bl64;\n\t\t\t\t\tfor (int chan = 0; chan < colors && chan < 4; chan++)\n\t\t\t\t\t\timgdata.color.linear_max[chan] =\n\t\t\t\t\t\t(maximum - rblack) *\n\t\t\t\t\t\timgdata.color.dng_levels.LinearResponseLimit +\n\t\t\t\t\t\trblack;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "project": "LibRaw", "hash": 37186369853422378844569840658555284518, "size": 344, "commit_id": "4feaed4dea636cee4fee010f615881ccf76a096d", "message": "limit loops to MIN(colors,4) in dng fields parser", "target": 0, "dataset": "other", "idx": 482359}
  999. {"func": "MagickExport void ConvertRGBToHSL(const Quantum red,const Quantum green,\n const Quantum blue,double *hue,double *saturation,double *lightness)\n{\n double\n c,\n max,\n min;\n\n /*\n Convert RGB to HSL colorspace.\n */\n assert(hue != (double *) NULL);\n assert(saturation != (double *) NULL);\n assert(lightness != (double *) NULL);\n max=MagickMax(QuantumScale*red,MagickMax(QuantumScale*green,\n QuantumScale*blue));\n min=MagickMin(QuantumScale*red,MagickMin(QuantumScale*green,\n QuantumScale*blue));\n c=max-min;\n *lightness=(max+min)/2.0;\n if (c <= 0.0)\n {\n *hue=0.0;\n *saturation=0.0;\n return;\n }\n if (fabs(max-QuantumScale*red) < MagickEpsilon)\n {\n *hue=(QuantumScale*green-QuantumScale*blue)/c;\n if ((QuantumScale*green) < (QuantumScale*blue))\n *hue+=6.0;\n }\n else\n if (fabs(max-QuantumScale*green) < MagickEpsilon)\n *hue=2.0+(QuantumScale*blue-QuantumScale*red)/c;\n else\n *hue=4.0+(QuantumScale*red-QuantumScale*green)/c;\n *hue*=60.0/360.0;\n if (*lightness <= 0.5)\n *saturation=c/(2.0*(*lightness));\n else\n *saturation=c/(2.0-2.0*(*lightness));\n}", "project": "ImageMagick6", "hash": 64316640286512378958089004373682516754, "size": 43, "commit_id": "64c0cc234280544dabacc2b28017521851deebde", "message": "https://github.com/ImageMagick/ImageMagick/issues/3321", "target": 1, "dataset": "other", "idx": 215048}
  1000. {"func": "MagickExport void ConvertRGBToHSL(const Quantum red,const Quantum green,\n const Quantum blue,double *hue,double *saturation,double *lightness)\n{\n double\n c,\n max,\n min;\n\n /*\n Convert RGB to HSL colorspace.\n */\n assert(hue != (double *) NULL);\n assert(saturation != (double *) NULL);\n assert(lightness != (double *) NULL);\n max=MagickMax(QuantumScale*red,MagickMax(QuantumScale*green,\n QuantumScale*blue));\n min=MagickMin(QuantumScale*red,MagickMin(QuantumScale*green,\n QuantumScale*blue));\n c=max-min;\n *lightness=(max+min)/2.0;\n if (c <= 0.0)\n {\n *hue=0.0;\n *saturation=0.0;\n return;\n }\n if (fabs(max-QuantumScale*red) < MagickEpsilon)\n {\n *hue=(QuantumScale*green-QuantumScale*blue)/c;\n if ((QuantumScale*green) < (QuantumScale*blue))\n *hue+=6.0;\n }\n else\n if (fabs(max-QuantumScale*green) < MagickEpsilon)\n *hue=2.0+(QuantumScale*blue-QuantumScale*red)/c;\n else\n *hue=4.0+(QuantumScale*red-QuantumScale*green)/c;\n *hue*=60.0/360.0;\n if (*lightness <= 0.5)\n *saturation=c*PerceptibleReciprocal(2.0*(*lightness));\n else\n *saturation=c*PerceptibleReciprocal(2.0-2.0*(*lightness));\n}", "project": "ImageMagick6", "hash": 224060726924583917833900427488966825442, "size": 43, "commit_id": "64c0cc234280544dabacc2b28017521851deebde", "message": "https://github.com/ImageMagick/ImageMagick/issues/3321", "target": 0, "dataset": "other", "idx": 482921}
  1001. {"func": "struct clock_source *dce100_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 162375462985061810672821165302100186277, "size": 22, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 1, "dataset": "other", "idx": 215059}
  1002. {"func": "struct clock_source *dce100_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 12504623577116996886674834703313256811, "size": 23, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 0, "dataset": "other", "idx": 482955}
  1003. {"func": "struct clock_source *dce80_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 47031023642369501827563085012832170420, "size": 22, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 1, "dataset": "other", "idx": 215060}
  1004. {"func": "struct clock_source *dce100_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 12504623577116996886674834703313256811, "size": 23, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 0, "dataset": "other", "idx": 482955}
  1005. {"func": "struct clock_source *dcn10_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce112_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 271763125377938091679854459980248910171, "size": 22, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 1, "dataset": "other", "idx": 215061}
  1006. {"func": "struct clock_source *dce100_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 12504623577116996886674834703313256811, "size": 23, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 0, "dataset": "other", "idx": 482955}
  1007. {"func": "struct clock_source *dce112_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce112_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 199589559251523108029584750650448513021, "size": 22, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 1, "dataset": "other", "idx": 215062}
  1008. {"func": "struct clock_source *dce100_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 12504623577116996886674834703313256811, "size": 23, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 0, "dataset": "other", "idx": 482955}
  1009. {"func": "struct clock_source *dce110_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 31654476780755587973778973098883413139, "size": 22, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 1, "dataset": "other", "idx": 215063}
  1010. {"func": "struct clock_source *dce100_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 12504623577116996886674834703313256811, "size": 23, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 0, "dataset": "other", "idx": 482955}
  1011. {"func": "struct clock_source *dcn20_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dcn20_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 177672847907118008764814032612740810929, "size": 22, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 1, "dataset": "other", "idx": 215064}
  1012. {"func": "struct clock_source *dcn10_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce112_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 139266790086854436831409090331754192145, "size": 23, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 0, "dataset": "other", "idx": 483006}
  1013. {"func": "static struct clock_source *dce120_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(*clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce112_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\t\t regs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 288594546535569243400673837265126927733, "size": 22, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 1, "dataset": "other", "idx": 215065}
  1014. {"func": "static struct clock_source *dce120_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(*clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce112_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\t\t regs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "project": "linux", "hash": 326037735483413902171736333958270598485, "size": 23, "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>\nSigned-off-by: Alex Deucher <alexander.deucher@amd.com>", "target": 0, "dataset": "other", "idx": 483005}
  1015. {"func": "static void get_over(struct SYMBOL *s)\n{\n\tstruct VOICE_S *p_voice, *p_voice2, *p_voice3;\n\tint range, voice, voice2, voice3;\nstatic char tx_wrong_dur[] = \"Wrong duration in voice overlay\";\nstatic char txt_no_note[] = \"No note in voice overlay\";\n\n\t/* treat the end of overlay */\n\tp_voice = curvoice;\n\tif (p_voice->ignore)\n\t\treturn;\n\tif (s->abc_type == ABC_T_BAR\n\t || s->u.v_over.type == V_OVER_E) {\n\t\tif (!p_voice->last_sym) {\n\t\t\terror(1, s, txt_no_note);\n\t\t\treturn;\n\t\t}\n\t\tp_voice->last_sym->sflags |= S_BEAM_END;\n\t\tover_bar = 0;\n\t\tif (over_time < 0) {\n\t\t\terror(1, s, \"Erroneous end of voice overlap\");\n\t\t\treturn;\n\t\t}\n\t\tif (p_voice->time != over_mxtime)\n\t\t\terror(1, s, tx_wrong_dur);\n\t\tcurvoice = &voice_tb[over_voice];\n\t\tover_mxtime = 0;\n\t\tover_voice = -1;\n\t\tover_time = -1;\n\t\treturn;\n\t}\n\n\t/* treat the full overlay start */\n\tif (s->u.v_over.type == V_OVER_S) {\n\t\tover_voice = p_voice - voice_tb;\n\t\tover_time = p_voice->time;\n\t\treturn;\n\t}\n\n\t/* (here is treated a new overlay - '&') */\n\t/* create the extra voice if not done yet */\n\tif (!p_voice->last_sym) {\n\t\terror(1, s, txt_no_note);\n\t\treturn;\n\t}\n\tp_voice->last_sym->sflags |= S_BEAM_END;\n\tvoice2 = s->u.v_over.voice;\n\tp_voice2 = &voice_tb[voice2];\n\tif (parsys->voice[voice2].range < 0) {\n\t\tint clone;\n\n\t\tif (cfmt.abc2pscompat) {\n\t\t\terror(1, s, \"Cannot have %%%%abc2pscompat\");\n\t\t\tcfmt.abc2pscompat = 0;\n\t\t}\n\t\tclone = p_voice->clone >= 0;\n\t\tp_voice2->id[0] = '&';\n\t\tp_voice2->id[1] = '\\0';\n\t\tp_voice2->second = 1;\n\t\tparsys->voice[voice2].second = 1;\n\t\tp_voice2->scale = p_voice->scale;\n\t\tp_voice2->octave = p_voice->octave;\n\t\tp_voice2->transpose = p_voice->transpose;\n\t\tmemcpy(&p_voice2->key, &p_voice->key,\n\t\t\t\t\tsizeof p_voice2->key);\n\t\tmemcpy(&p_voice2->ckey, &p_voice->ckey,\n\t\t\t\t\tsizeof p_voice2->ckey);\n\t\tmemcpy(&p_voice2->okey, &p_voice->okey,\n\t\t\t\t\tsizeof p_voice2->okey);\n\t\tp_voice2->posit = p_voice->posit;\n\t\tp_voice2->staff = p_voice->staff;\n\t\tp_voice2->cstaff = p_voice->cstaff;\n\t\tp_voice2->color = p_voice->color;\n\t\tp_voice2->map_name = p_voice->map_name;\n\t\trange = parsys->voice[p_voice - voice_tb].range;\n\t\tfor (voice = 0; voice < MAXVOICE; voice++) {\n\t\t\tif (parsys->voice[voice].range > range)\n\t\t\t\tparsys->voice[voice].range += clone + 1;\n\t\t}\n\t\tparsys->voice[voice2].range = range + 1;\n\t\tvoice_link(p_voice2);\n\t\tif (clone) {\n\t\t\tfor (voice3 = MAXVOICE; --voice3 >= 0; ) {\n\t\t\t\tif (parsys->voice[voice3].range < 0)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (voice3 > 0) {\n\t\t\t\tp_voice3 = &voice_tb[voice3];\n\t\t\t\tstrcpy(p_voice3->id, p_voice2->id);\n\t\t\t\tp_voice3->second = 1;\n\t\t\t\tparsys->voice[voice3].second = 1;\n\t\t\t\tp_voice3->scale = voice_tb[p_voice->clone].scale;\n\t\t\t\tparsys->voice[voice3].range = range + 2;\n\t\t\t\tvoice_link(p_voice3);\n\t\t\t\tp_voice2->clone = voice3;\n\t\t\t} else {\n\t\t\t\terror(1, s,\n\t\t\t\t \"Too many voices for overlay cloning\");\n\t\t\t}\n\t\t}\n\t}\n\tvoice = p_voice - voice_tb;\n//\tp_voice2->cstaff = p_voice2->staff = parsys->voice[voice2].staff\n//\t\t\t= parsys->voice[voice].staff;\n//\tif ((voice3 = p_voice2->clone) >= 0) {\n//\t\tp_voice3 = &voice_tb[voice3];\n//\t\tp_voice3->cstaff = p_voice3->staff\n//\t\t\t\t= parsys->voice[voice3].staff\n//\t\t\t\t= parsys->voice[p_voice->clone].staff;\n//\t}\n\n\tif (over_time < 0) {\t\t\t/* first '&' in a measure */\n\t\tint time;\n\n\t\tover_bar = 1;\n\t\tover_mxtime = p_voice->time;\n\t\tover_voice = voice;\n\t\ttime = p_voice2->time;\n\t\tfor (s = p_voice->last_sym; /*s*/; s = s->prev) {\n\t\t\tif (s->type == BAR\n\t\t\t || s->time <= time)\t/* (if start of tune) */\n\t\t\t\tbreak;\n\t\t}\n\t\tover_time = s->time;\n\t} else {\n\t\tif (over_mxtime == 0)\n\t\t\tover_mxtime = p_voice->time;\n\t\telse if (p_voice->time != over_mxtime)\n\t\t\terror(1, s, tx_wrong_dur);\n\t}\n\tp_voice2->time = over_time;\n\tcurvoice = p_voice2;\n}", "project": "abcm2ps", "hash": 89478143332361880739890507095670885956, "size": 133, "commit_id": "2f56e1179cab6affeb8afa9d6c324008fe40d8e3", "message": "fix: array overflow when wrong duration in voice overlay\n\nIssue #83,", "target": 1, "dataset": "other", "idx": 215165}
  1016. {"func": "static void get_over(struct SYMBOL *s)\n{\n\tstruct VOICE_S *p_voice, *p_voice2, *p_voice3;\n\tint range, voice, voice2, voice3;\nstatic char tx_wrong_dur[] = \"Wrong duration in voice overlay\";\nstatic char txt_no_note[] = \"No note in voice overlay\";\n\n\t/* treat the end of overlay */\n\tp_voice = curvoice;\n\tif (p_voice->ignore)\n\t\treturn;\n\tif (s->abc_type == ABC_T_BAR\n\t || s->u.v_over.type == V_OVER_E) {\n\t\tif (!p_voice->last_sym) {\n\t\t\terror(1, s, txt_no_note);\n\t\t\treturn;\n\t\t}\n\t\tp_voice->last_sym->sflags |= S_BEAM_END;\n\t\tover_bar = 0;\n\t\tif (over_time < 0) {\n\t\t\terror(1, s, \"Erroneous end of voice overlap\");\n\t\t\treturn;\n\t\t}\n\t\tcurvoice = &voice_tb[over_voice];\n\t\tif (p_voice->time != over_mxtime) {\n\t\t\terror(1, s, tx_wrong_dur);\n\t\t\tif (p_voice->time > over_mxtime)\n\t\t\t\tcurvoice->time = p_voice->time;\n\t\t\telse\n\t\t\t\tp_voice->time = curvoice->time;\n\t\t}\n\t\tover_mxtime = 0;\n\t\tover_voice = -1;\n\t\tover_time = -1;\n\t\treturn;\n\t}\n\n\t/* treat the full overlay start */\n\tif (s->u.v_over.type == V_OVER_S) {\n\t\tover_voice = p_voice - voice_tb;\n\t\tover_time = p_voice->time;\n\t\treturn;\n\t}\n\n\t/* (here is treated a new overlay - '&') */\n\t/* create the extra voice if not done yet */\n\tif (!p_voice->last_sym) {\n\t\terror(1, s, txt_no_note);\n\t\treturn;\n\t}\n\tp_voice->last_sym->sflags |= S_BEAM_END;\n\tvoice2 = s->u.v_over.voice;\n\tp_voice2 = &voice_tb[voice2];\n\tif (parsys->voice[voice2].range < 0) {\n\t\tint clone;\n\n\t\tif (cfmt.abc2pscompat) {\n\t\t\terror(1, s, \"Cannot have %%%%abc2pscompat\");\n\t\t\tcfmt.abc2pscompat = 0;\n\t\t}\n\t\tclone = p_voice->clone >= 0;\n\t\tp_voice2->id[0] = '&';\n\t\tp_voice2->id[1] = '\\0';\n\t\tp_voice2->second = 1;\n\t\tparsys->voice[voice2].second = 1;\n\t\tp_voice2->scale = p_voice->scale;\n\t\tp_voice2->octave = p_voice->octave;\n\t\tp_voice2->transpose = p_voice->transpose;\n\t\tmemcpy(&p_voice2->key, &p_voice->key,\n\t\t\t\t\tsizeof p_voice2->key);\n\t\tmemcpy(&p_voice2->ckey, &p_voice->ckey,\n\t\t\t\t\tsizeof p_voice2->ckey);\n\t\tmemcpy(&p_voice2->okey, &p_voice->okey,\n\t\t\t\t\tsizeof p_voice2->okey);\n\t\tp_voice2->posit = p_voice->posit;\n\t\tp_voice2->staff = p_voice->staff;\n\t\tp_voice2->cstaff = p_voice->cstaff;\n\t\tp_voice2->color = p_voice->color;\n\t\tp_voice2->map_name = p_voice->map_name;\n\t\trange = parsys->voice[p_voice - voice_tb].range;\n\t\tfor (voice = 0; voice < MAXVOICE; voice++) {\n\t\t\tif (parsys->voice[voice].range > range)\n\t\t\t\tparsys->voice[voice].range += clone + 1;\n\t\t}\n\t\tparsys->voice[voice2].range = range + 1;\n\t\tvoice_link(p_voice2);\n\t\tif (clone) {\n\t\t\tfor (voice3 = MAXVOICE; --voice3 >= 0; ) {\n\t\t\t\tif (parsys->voice[voice3].range < 0)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (voice3 > 0) {\n\t\t\t\tp_voice3 = &voice_tb[voice3];\n\t\t\t\tstrcpy(p_voice3->id, p_voice2->id);\n\t\t\t\tp_voice3->second = 1;\n\t\t\t\tparsys->voice[voice3].second = 1;\n\t\t\t\tp_voice3->scale = voice_tb[p_voice->clone].scale;\n\t\t\t\tparsys->voice[voice3].range = range + 2;\n\t\t\t\tvoice_link(p_voice3);\n\t\t\t\tp_voice2->clone = voice3;\n\t\t\t} else {\n\t\t\t\terror(1, s,\n\t\t\t\t \"Too many voices for overlay cloning\");\n\t\t\t}\n\t\t}\n\t}\n\tvoice = p_voice - voice_tb;\n//\tp_voice2->cstaff = p_voice2->staff = parsys->voice[voice2].staff\n//\t\t\t= parsys->voice[voice].staff;\n//\tif ((voice3 = p_voice2->clone) >= 0) {\n//\t\tp_voice3 = &voice_tb[voice3];\n//\t\tp_voice3->cstaff = p_voice3->staff\n//\t\t\t\t= parsys->voice[voice3].staff\n//\t\t\t\t= parsys->voice[p_voice->clone].staff;\n//\t}\n\n\tif (over_time < 0) {\t\t\t/* first '&' in a measure */\n\t\tint time;\n\n\t\tover_bar = 1;\n\t\tover_mxtime = p_voice->time;\n\t\tover_voice = voice;\n\t\ttime = p_voice2->time;\n\t\tfor (s = p_voice->last_sym; /*s*/; s = s->prev) {\n\t\t\tif (s->type == BAR\n\t\t\t || s->time <= time)\t/* (if start of tune) */\n\t\t\t\tbreak;\n\t\t}\n\t\tover_time = s->time;\n\t} else {\n\t\tif (over_mxtime == 0)\n\t\t\tover_mxtime = p_voice->time;\n\t\telse if (p_voice->time != over_mxtime)\n\t\t\terror(1, s, tx_wrong_dur);\n\t}\n\tp_voice2->time = over_time;\n\tcurvoice = p_voice2;\n}", "project": "abcm2ps", "hash": 106849796852152645656287252191337327464, "size": 138, "commit_id": "2f56e1179cab6affeb8afa9d6c324008fe40d8e3", "message": "fix: array overflow when wrong duration in voice overlay\n\nIssue #83,", "target": 0, "dataset": "other", "idx": 484351}
  1017. {"func": "static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement TSRMLS_DC)\n{\n\tint de, i=0, section_index = SECTION_MAKERNOTE;\n\tint NumDirEntries, old_motorola_intel, offset_diff;\n\tconst maker_note_type *maker_note;\n\tchar *dir_start;\n\n\tfor (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) {\n\t\tif (i==sizeof(maker_note_array)/sizeof(maker_note_type)) {\n#ifdef EXIF_DEBUG\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"No maker note data found. Detected maker: %s (length = %d)\", ImageInfo->make, strlen(ImageInfo->make));\n#endif\n\t\t\t/* unknown manufacturer, not an error, use it as a string */\n\t\t\treturn TRUE;\n\t\t}\n\n\t\tmaker_note = maker_note_array+i;\n\n\t\t/*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"check (%s,%s)\", maker_note->make?maker_note->make:\"\", maker_note->model?maker_note->model:\"\");*/\n\t\tif (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make)))\n\t\t\tcontinue;\n\t\tif (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model)))\n\t\t\tcontinue;\n\t\tif (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len))\n\t\t\tcontinue;\n\t\tbreak;\n\t}\n\n\tif (maker_note->offset >= value_len) {\n\t\t/* Do not go past the value end */\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data too short: 0x%04X offset 0x%04X\", value_len, maker_note->offset);\n\t\treturn FALSE;\n\t}\n\n\tdir_start = value_ptr + maker_note->offset;\n\n#ifdef EXIF_DEBUG\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Process %s @x%04X + 0x%04X=%d: %s\", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement));\n#endif\n\n\tImageInfo->sections_found |= FOUND_MAKERNOTE;\n\n\told_motorola_intel = ImageInfo->motorola_intel;\n\tswitch (maker_note->byte_order) {\n\t\tcase MN_ORDER_INTEL:\n\t\t\tImageInfo->motorola_intel = 0;\n\t\t\tbreak;\n\t\tcase MN_ORDER_MOTOROLA:\n\t\t\tImageInfo->motorola_intel = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\tcase MN_ORDER_NORMAL:\n\t\t\tbreak;\n\t}\n\n\tNumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);\n\n\tswitch (maker_note->offset_mode) {\n\t\tcase MN_OFFSET_MAKER:\n\t\t\toffset_base = value_ptr;\n\t\t\tbreak;\n\t\tcase MN_OFFSET_GUESS:\n\t\t\tif (maker_note->offset + 10 + 4 >= value_len) {\n\t\t\t\t/* Can not read dir_start+10 since it's beyond value end */\n\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data too short: 0x%04X\", value_len);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\toffset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel);\n#ifdef EXIF_DEBUG\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Using automatic offset correction: 0x%04X\", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff);\n#endif\n\t\t\tif (offset_diff < 0 || offset_diff >= value_len ) {\n\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data bad offset: 0x%04X length 0x%04X\", offset_diff, value_len);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\toffset_base = value_ptr + offset_diff;\n\t\t\tbreak;\n\t\tdefault:\n\t\tcase MN_OFFSET_NORMAL:\n\t\t\tbreak;\n\t}\n\n\tif ((2+NumDirEntries*12) > value_len) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X\", NumDirEntries, 2+NumDirEntries*12, value_len);\n\t\treturn FALSE;\n\t}\n\n\tfor (de=0;de<NumDirEntries;de++) {\n\t\tif (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de,\n\t\t\t\t\t\t\t\t offset_base, IFDlength, displacement, section_index, 0, maker_note->tag_table TSRMLS_CC)) {\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\tImageInfo->motorola_intel = old_motorola_intel;\n/*\tNextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/\n#ifdef EXIF_DEBUG\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Subsection %s done\", exif_get_sectionname(SECTION_MAKERNOTE));\n#endif\n\treturn TRUE;\n}", "project": "php-src", "hash": 22189568364832264784102840174267992879, "size": 100, "commit_id": "3462efa386f26d343062094514af604c29e3edce", "message": "Fix bug #76557: heap-buffer-overflow (READ of size 48) while reading exif data\n\nUse MAKERNOTE length as data size.", "target": 1, "dataset": "other", "idx": 215213}
  1018. {"func": "static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement TSRMLS_DC)\n{\n\tint de, i=0, section_index = SECTION_MAKERNOTE;\n\tint NumDirEntries, old_motorola_intel, offset_diff;\n\tconst maker_note_type *maker_note;\n\tchar *dir_start;\n\tint data_len;\n\n\tfor (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) {\n\t\tif (i==sizeof(maker_note_array)/sizeof(maker_note_type)) {\n#ifdef EXIF_DEBUG\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"No maker note data found. Detected maker: %s (length = %d)\", ImageInfo->make, strlen(ImageInfo->make));\n#endif\n\t\t\t/* unknown manufacturer, not an error, use it as a string */\n\t\t\treturn TRUE;\n\t\t}\n\n\t\tmaker_note = maker_note_array+i;\n\n\t\t/*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"check (%s,%s)\", maker_note->make?maker_note->make:\"\", maker_note->model?maker_note->model:\"\");*/\n\t\tif (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make)))\n\t\t\tcontinue;\n\t\tif (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model)))\n\t\t\tcontinue;\n\t\tif (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len))\n\t\t\tcontinue;\n\t\tbreak;\n\t}\n\n\tif (maker_note->offset >= value_len) {\n\t\t/* Do not go past the value end */\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data too short: 0x%04X offset 0x%04X\", value_len, maker_note->offset);\n\t\treturn FALSE;\n\t}\n\n\tdir_start = value_ptr + maker_note->offset;\n\n#ifdef EXIF_DEBUG\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Process %s @x%04X + 0x%04X=%d: %s\", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement));\n#endif\n\n\tImageInfo->sections_found |= FOUND_MAKERNOTE;\n\n\told_motorola_intel = ImageInfo->motorola_intel;\n\tswitch (maker_note->byte_order) {\n\t\tcase MN_ORDER_INTEL:\n\t\t\tImageInfo->motorola_intel = 0;\n\t\t\tbreak;\n\t\tcase MN_ORDER_MOTOROLA:\n\t\t\tImageInfo->motorola_intel = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\tcase MN_ORDER_NORMAL:\n\t\t\tbreak;\n\t}\n\n\tNumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);\n\n\tswitch (maker_note->offset_mode) {\n\t\tcase MN_OFFSET_MAKER:\n\t\t\toffset_base = value_ptr;\n\t\t\tdata_len = value_len;\n\t\t\tbreak;\n\t\tcase MN_OFFSET_GUESS:\n\t\t\tif (maker_note->offset + 10 + 4 >= value_len) {\n\t\t\t\t/* Can not read dir_start+10 since it's beyond value end */\n\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data too short: 0x%04X\", value_len);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\toffset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel);\n#ifdef EXIF_DEBUG\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Using automatic offset correction: 0x%04X\", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff);\n#endif\n\t\t\tif (offset_diff < 0 || offset_diff >= value_len ) {\n\t\t\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"IFD data bad offset: 0x%04X length 0x%04X\", offset_diff, value_len);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\toffset_base = value_ptr + offset_diff;\n\t\t\tdata_len = value_len - offset_diff;\n\t\t\tbreak;\n\t\tdefault:\n\t\tcase MN_OFFSET_NORMAL:\n\t\t\tbreak;\n\t}\n\n\tif ((2+NumDirEntries*12) > value_len) {\n\t\texif_error_docref(\"exif_read_data#error_ifd\" EXIFERR_CC, ImageInfo, E_WARNING, \"Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X\", NumDirEntries, 2+NumDirEntries*12, value_len);\n\t\treturn FALSE;\n\t}\n\n\tfor (de=0;de<NumDirEntries;de++) {\n\t\tif (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de,\n\t\t\t\t\t\t\t\t offset_base, data_len, displacement, section_index, 0, maker_note->tag_table TSRMLS_CC)) {\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\tImageInfo->motorola_intel = old_motorola_intel;\n/*\tNextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/\n#ifdef EXIF_DEBUG\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Subsection %s done\", exif_get_sectionname(SECTION_MAKERNOTE));\n#endif\n\treturn TRUE;\n}", "project": "php-src", "hash": 179703936053344348653074411508239418076, "size": 103, "commit_id": "3462efa386f26d343062094514af604c29e3edce", "message": "Fix bug #76557: heap-buffer-overflow (READ of size 48) while reading exif data\n\nUse MAKERNOTE length as data size.", "target": 0, "dataset": "other", "idx": 485283}
  1019. {"func": "gdImagePtr gdImageCrop(gdImagePtr src, const gdRectPtr crop)\n{\n\tgdImagePtr dst;\n\tint y;\n\n\t/* check size */\n\tif (crop->width<=0 || crop->height<=0) {\n\t\treturn NULL;\n\t}\n\n\t/* allocate the requested size (could be only partially filled) */\n\tif (src->trueColor) {\n\t\tdst = gdImageCreateTrueColor(crop->width, crop->height);\n\t\tgdImageSaveAlpha(dst, 1);\n\t} else {\n\t\tdst = gdImageCreate(crop->width, crop->height);\n\t\tgdImagePaletteCopy(dst, src);\n\t}\n\tif (dst == NULL) {\n\t\treturn NULL;\n\t}\n\tdst->transparent = src->transparent;\n\n\t/* check position in the src image */\n\tif (crop->x < 0 || crop->x>=src->sx || crop->y<0 || crop->y>=src->sy) {\n\t\treturn dst;\n\t}\n\n\t/* reduce size if needed */\n\tif ((src->sx - crop->width) < crop->x) {\n\t\tcrop->width = src->sx - crop->x;\n\t}\n\tif ((src->sy - crop->height) < crop->y) {\n\t\tcrop->height = src->sy - crop->y;\n\t}\n\n#if 0\nprintf(\"rect->x: %i\\nrect->y: %i\\nrect->width: %i\\nrect->height: %i\\n\", crop->x, crop->y, crop->width, crop->height);\n#endif\n\ty = crop->y;\n\tif (src->trueColor) {\n\t\tunsigned int dst_y = 0;\n\t\twhile (y < (crop->y + (crop->height - 1))) {\n\t\t\t/* TODO: replace 4 w/byte per channel||pitch once available */\n\t\t\tmemcpy(dst->tpixels[dst_y++], src->tpixels[y++] + crop->x, crop->width * 4);\n\t\t}\n\t} else {\n\t\tint x;\n\t\tfor (y = crop->y; y < (crop->y + (crop->height - 1)); y++) {\n\t\t\tfor (x = crop->x; x < (crop->x + (crop->width - 1)); x++) {\n\t\t\t\tdst->pixels[y - crop->y][x - crop->x] = src->pixels[y][x];\n\t\t\t}\n\t\t}\n\t}\n\treturn dst;\n}", "project": "php-src", "hash": 121046021861658525511228885017249088421, "size": 56, "commit_id": "af09d8b96a8aacdd7d738fec81b695c1c58368f7", "message": "Fixed Bug #66815 imagecrop(): insufficient fix for NULL defer CVE-2013-7327\n\nThis amends commit 8f4a537, which aimed to correct NULL dereference because of\nmissing check of gdImageCreateTrueColor() / gdImageCreate() return value. That\ncommit checks for negative crop rectangle width and height, but\ngdImageCreate*() can also return NULL when width * height overflows. Hence\nNULL deref is still possible, as gdImageSaveAlpha() and gdImagePaletteCopy()\nis called before dst == NULL check.\n\nThis moves NULL check to happen right after gdImageCreate*(). It also removes\nwidth and height check before gdImageCreate*(), as the same check is done by\nimage create functions (with an extra warning).\n\nFrom thoger redhat com", "target": 1, "dataset": "other", "idx": 215215}
  1020. {"func": "gdImagePtr gdImageCrop(gdImagePtr src, const gdRectPtr crop)\n{\n\tgdImagePtr dst;\n\tint y;\n\n\t/* allocate the requested size (could be only partially filled) */\n\tif (src->trueColor) {\n\t\tdst = gdImageCreateTrueColor(crop->width, crop->height);\n\t\tif (dst == NULL) {\n\t\t\treturn NULL;\n\t\t}\n\t\tgdImageSaveAlpha(dst, 1);\n\t} else {\n\t\tdst = gdImageCreate(crop->width, crop->height);\n\t\tif (dst == NULL) {\n\t\t\treturn NULL;\n\t\t}\n\t\tgdImagePaletteCopy(dst, src);\n\t}\n\tdst->transparent = src->transparent;\n\n\t/* check position in the src image */\n\tif (crop->x < 0 || crop->x>=src->sx || crop->y<0 || crop->y>=src->sy) {\n\t\treturn dst;\n\t}\n\n\t/* reduce size if needed */\n\tif ((src->sx - crop->width) < crop->x) {\n\t\tcrop->width = src->sx - crop->x;\n\t}\n\tif ((src->sy - crop->height) < crop->y) {\n\t\tcrop->height = src->sy - crop->y;\n\t}\n\n#if 0\nprintf(\"rect->x: %i\\nrect->y: %i\\nrect->width: %i\\nrect->height: %i\\n\", crop->x, crop->y, crop->width, crop->height);\n#endif\n\ty = crop->y;\n\tif (src->trueColor) {\n\t\tunsigned int dst_y = 0;\n\t\twhile (y < (crop->y + (crop->height - 1))) {\n\t\t\t/* TODO: replace 4 w/byte per channel||pitch once available */\n\t\t\tmemcpy(dst->tpixels[dst_y++], src->tpixels[y++] + crop->x, crop->width * 4);\n\t\t}\n\t} else {\n\t\tint x;\n\t\tfor (y = crop->y; y < (crop->y + (crop->height - 1)); y++) {\n\t\t\tfor (x = crop->x; x < (crop->x + (crop->width - 1)); x++) {\n\t\t\t\tdst->pixels[y - crop->y][x - crop->x] = src->pixels[y][x];\n\t\t\t}\n\t\t}\n\t}\n\treturn dst;\n}", "project": "php-src", "hash": 211902895967623924199736087663142577675, "size": 54, "commit_id": "af09d8b96a8aacdd7d738fec81b695c1c58368f7", "message": "Fixed Bug #66815 imagecrop(): insufficient fix for NULL defer CVE-2013-7327\n\nThis amends commit 8f4a537, which aimed to correct NULL dereference because of\nmissing check of gdImageCreateTrueColor() / gdImageCreate() return value. That\ncommit checks for negative crop rectangle width and height, but\ngdImageCreate*() can also return NULL when width * height overflows. Hence\nNULL deref is still possible, as gdImageSaveAlpha() and gdImagePaletteCopy()\nis called before dst == NULL check.\n\nThis moves NULL check to happen right after gdImageCreate*(). It also removes\nwidth and height check before gdImageCreate*(), as the same check is done by\nimage create functions (with an extra warning).\n\nFrom thoger redhat com", "target": 0, "dataset": "other", "idx": 485284}
  1021. {"func": "isdn_net_setcfg(isdn_net_ioctl_cfg * cfg)\n{\n\tisdn_net_dev *p = isdn_net_findif(cfg->name);\n\tulong features;\n\tint i;\n\tint drvidx;\n\tint chidx;\n\tchar drvid[25];\n\n\tif (p) {\n\t\tisdn_net_local *lp = p->local;\n\n\t\t/* See if any registered driver supports the features we want */\n\t\tfeatures = ((1 << cfg->l2_proto) << ISDN_FEATURE_L2_SHIFT) |\n\t\t\t((1 << cfg->l3_proto) << ISDN_FEATURE_L3_SHIFT);\n\t\tfor (i = 0; i < ISDN_MAX_DRIVERS; i++)\n\t\t\tif (dev->drv[i])\n\t\t\t\tif ((dev->drv[i]->interface->features & features) == features)\n\t\t\t\t\tbreak;\n\t\tif (i == ISDN_MAX_DRIVERS) {\n\t\t\tprintk(KERN_WARNING \"isdn_net: No driver with selected features\\n\");\n\t\t\treturn -ENODEV;\n\t\t}\n\t\tif (lp->p_encap != cfg->p_encap){\n#ifdef CONFIG_ISDN_X25\n\t\t\tstruct concap_proto * cprot = p -> cprot;\n#endif\n\t\t\tif (isdn_net_device_started(p)) {\n\t\t\t\tprintk(KERN_WARNING \"%s: cannot change encap when if is up\\n\",\n\t\t\t\t p->dev->name);\n\t\t\t\treturn -EBUSY;\n\t\t\t}\n#ifdef CONFIG_ISDN_X25\n\t\t\tif( cprot && cprot -> pops )\n\t\t\t\tcprot -> pops -> proto_del ( cprot );\n\t\t\tp -> cprot = NULL;\n\t\t\tlp -> dops = NULL;\n\t\t\t/* ... , prepare for configuration of new one ... */\n\t\t\tswitch ( cfg -> p_encap ){\n\t\t\tcase ISDN_NET_ENCAP_X25IFACE:\n\t\t\t\tlp -> dops = &isdn_concap_reliable_dl_dops;\n\t\t\t}\n\t\t\t/* ... and allocate new one ... */\n\t\t\tp -> cprot = isdn_concap_new( cfg -> p_encap );\n\t\t\t/* p -> cprot == NULL now if p_encap is not supported\n\t\t\t by means of the concap_proto mechanism */\n\t\t\t/* the protocol is not configured yet; this will\n\t\t\t happen later when isdn_net_reset() is called */\n#endif\n\t\t}\n\t\tswitch ( cfg->p_encap ) {\n\t\tcase ISDN_NET_ENCAP_SYNCPPP:\n#ifndef CONFIG_ISDN_PPP\n\t\t\tprintk(KERN_WARNING \"%s: SyncPPP support not configured\\n\",\n\t\t\t p->dev->name);\n\t\t\treturn -EINVAL;\n#else\n\t\t\tp->dev->type = ARPHRD_PPP;\t/* change ARP type */\n\t\t\tp->dev->addr_len = 0;\n\t\t\tp->dev->do_ioctl = isdn_ppp_dev_ioctl;\n#endif\n\t\t\tbreak;\n\t\tcase ISDN_NET_ENCAP_X25IFACE:\n#ifndef CONFIG_ISDN_X25\n\t\t\tprintk(KERN_WARNING \"%s: isdn-x25 support not configured\\n\",\n\t\t\t p->dev->name);\n\t\t\treturn -EINVAL;\n#else\n\t\t\tp->dev->type = ARPHRD_X25;\t/* change ARP type */\n\t\t\tp->dev->addr_len = 0;\n#endif\n\t\t\tbreak;\n\t\tcase ISDN_NET_ENCAP_CISCOHDLCK:\n\t\t\tp->dev->do_ioctl = isdn_ciscohdlck_dev_ioctl;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif( cfg->p_encap >= 0 &&\n\t\t\t cfg->p_encap <= ISDN_NET_ENCAP_MAX_ENCAP )\n\t\t\t\tbreak;\n\t\t\tprintk(KERN_WARNING\n\t\t\t \"%s: encapsulation protocol %d not supported\\n\",\n\t\t\t p->dev->name, cfg->p_encap);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (strlen(cfg->drvid)) {\n\t\t\t/* A bind has been requested ... */\n\t\t\tchar *c,\n\t\t\t*e;\n\n\t\t\tdrvidx = -1;\n\t\t\tchidx = -1;\n\t\t\tstrcpy(drvid, cfg->drvid);\n\t\t\tif ((c = strchr(drvid, ','))) {\n\t\t\t\t/* The channel-number is appended to the driver-Id with a comma */\n\t\t\t\tchidx = (int) simple_strtoul(c + 1, &e, 10);\n\t\t\t\tif (e == c)\n\t\t\t\t\tchidx = -1;\n\t\t\t\t*c = '\\0';\n\t\t\t}\n\t\t\tfor (i = 0; i < ISDN_MAX_DRIVERS; i++)\n\t\t\t\t/* Lookup driver-Id in array */\n\t\t\t\tif (!(strcmp(dev->drvid[i], drvid))) {\n\t\t\t\t\tdrvidx = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tif ((drvidx == -1) || (chidx == -1))\n\t\t\t\t/* Either driver-Id or channel-number invalid */\n\t\t\t\treturn -ENODEV;\n\t\t} else {\n\t\t\t/* Parameters are valid, so get them */\n\t\t\tdrvidx = lp->pre_device;\n\t\t\tchidx = lp->pre_channel;\n\t\t}\n\t\tif (cfg->exclusive > 0) {\n\t\t\tunsigned long flags;\n\n\t\t\t/* If binding is exclusive, try to grab the channel */\n\t\t\tspin_lock_irqsave(&dev->lock, flags);\n\t\t\tif ((i = isdn_get_free_channel(ISDN_USAGE_NET,\n\t\t\t\tlp->l2_proto, lp->l3_proto, drvidx,\n\t\t\t\tchidx, lp->msn)) < 0) {\n\t\t\t\t/* Grab failed, because desired channel is in use */\n\t\t\t\tlp->exclusive = -1;\n\t\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\t\treturn -EBUSY;\n\t\t\t}\n\t\t\t/* All went ok, so update isdninfo */\n\t\t\tdev->usage[i] = ISDN_USAGE_EXCLUSIVE;\n\t\t\tisdn_info_update();\n\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\tlp->exclusive = i;\n\t\t} else {\n\t\t\t/* Non-exclusive binding or unbind. */\n\t\t\tlp->exclusive = -1;\n\t\t\tif ((lp->pre_device != -1) && (cfg->exclusive == -1)) {\n\t\t\t\tisdn_unexclusive_channel(lp->pre_device, lp->pre_channel);\n\t\t\t\tisdn_free_channel(lp->pre_device, lp->pre_channel, ISDN_USAGE_NET);\n\t\t\t\tdrvidx = -1;\n\t\t\t\tchidx = -1;\n\t\t\t}\n\t\t}\n\t\tstrcpy(lp->msn, cfg->eaz);\n\t\tlp->pre_device = drvidx;\n\t\tlp->pre_channel = chidx;\n\t\tlp->onhtime = cfg->onhtime;\n\t\tlp->charge = cfg->charge;\n\t\tlp->l2_proto = cfg->l2_proto;\n\t\tlp->l3_proto = cfg->l3_proto;\n\t\tlp->cbdelay = cfg->cbdelay;\n\t\tlp->dialmax = cfg->dialmax;\n\t\tlp->triggercps = cfg->triggercps;\n\t\tlp->slavedelay = cfg->slavedelay * HZ;\n\t\tlp->pppbind = cfg->pppbind;\n\t\tlp->dialtimeout = cfg->dialtimeout >= 0 ? cfg->dialtimeout * HZ : -1;\n\t\tlp->dialwait = cfg->dialwait * HZ;\n\t\tif (cfg->secure)\n\t\t\tlp->flags |= ISDN_NET_SECURE;\n\t\telse\n\t\t\tlp->flags &= ~ISDN_NET_SECURE;\n\t\tif (cfg->cbhup)\n\t\t\tlp->flags |= ISDN_NET_CBHUP;\n\t\telse\n\t\t\tlp->flags &= ~ISDN_NET_CBHUP;\n\t\tswitch (cfg->callback) {\n\t\t\tcase 0:\n\t\t\t\tlp->flags &= ~(ISDN_NET_CALLBACK | ISDN_NET_CBOUT);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tlp->flags |= ISDN_NET_CALLBACK;\n\t\t\t\tlp->flags &= ~ISDN_NET_CBOUT;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tlp->flags |= ISDN_NET_CBOUT;\n\t\t\t\tlp->flags &= ~ISDN_NET_CALLBACK;\n\t\t\t\tbreak;\n\t\t}\n\t\tlp->flags &= ~ISDN_NET_DIALMODE_MASK;\t/* first all bits off */\n\t\tif (cfg->dialmode && !(cfg->dialmode & ISDN_NET_DIALMODE_MASK)) {\n\t\t\t/* old isdnctrl version, where only 0 or 1 is given */\n\t\t\tprintk(KERN_WARNING\n\t\t\t \"Old isdnctrl version detected! Please update.\\n\");\n\t\t\tlp->flags |= ISDN_NET_DM_OFF; /* turn on `off' bit */\n\t\t}\n\t\telse {\n\t\t\tlp->flags |= cfg->dialmode; /* turn on selected bits */\n\t\t}\n\t\tif (cfg->chargehup)\n\t\t\tlp->hupflags |= ISDN_CHARGEHUP;\n\t\telse\n\t\t\tlp->hupflags &= ~ISDN_CHARGEHUP;\n\t\tif (cfg->ihup)\n\t\t\tlp->hupflags |= ISDN_INHUP;\n\t\telse\n\t\t\tlp->hupflags &= ~ISDN_INHUP;\n\t\tif (cfg->chargeint > 10) {\n\t\t\tlp->hupflags |= ISDN_CHARGEHUP | ISDN_HAVECHARGE | ISDN_MANCHARGE;\n\t\t\tlp->chargeint = cfg->chargeint * HZ;\n\t\t}\n\t\tif (cfg->p_encap != lp->p_encap) {\n\t\t\tif (cfg->p_encap == ISDN_NET_ENCAP_RAWIP) {\n\t\t\t\tp->dev->header_ops = NULL;\n\t\t\t\tp->dev->flags = IFF_NOARP|IFF_POINTOPOINT;\n\t\t\t} else {\n\t\t\t\tp->dev->header_ops = &isdn_header_ops;\n\t\t\t\tif (cfg->p_encap == ISDN_NET_ENCAP_ETHER)\n\t\t\t\t\tp->dev->flags = IFF_BROADCAST | IFF_MULTICAST;\n\t\t\t\telse\n\t\t\t\t\tp->dev->flags = IFF_NOARP|IFF_POINTOPOINT;\n\t\t\t}\n\t\t}\n\t\tlp->p_encap = cfg->p_encap;\n\t\treturn 0;\n\t}\n\treturn -ENODEV;\n}", "target": 1, "cwe": ["CWE-119"], "project": "linux-2.6", "commit_id": "0f13864e5b24d9cbe18d125d41bfa4b726a82e40", "hash": 80796293720356790057810511838637183896, "size": 215, "message": "isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil <kkeil@suse.de>\nSigned-off-by: Andrew Morton <akpm@linux-foundation.org>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "dataset": "other", "idx": 215300}
  1022. {"func": "isdn_net_setcfg(isdn_net_ioctl_cfg * cfg)\n{\n\tisdn_net_dev *p = isdn_net_findif(cfg->name);\n\tulong features;\n\tint i;\n\tint drvidx;\n\tint chidx;\n\tchar drvid[25];\n\n\tif (p) {\n\t\tisdn_net_local *lp = p->local;\n\n\t\t/* See if any registered driver supports the features we want */\n\t\tfeatures = ((1 << cfg->l2_proto) << ISDN_FEATURE_L2_SHIFT) |\n\t\t\t((1 << cfg->l3_proto) << ISDN_FEATURE_L3_SHIFT);\n\t\tfor (i = 0; i < ISDN_MAX_DRIVERS; i++)\n\t\t\tif (dev->drv[i])\n\t\t\t\tif ((dev->drv[i]->interface->features & features) == features)\n\t\t\t\t\tbreak;\n\t\tif (i == ISDN_MAX_DRIVERS) {\n\t\t\tprintk(KERN_WARNING \"isdn_net: No driver with selected features\\n\");\n\t\t\treturn -ENODEV;\n\t\t}\n\t\tif (lp->p_encap != cfg->p_encap){\n#ifdef CONFIG_ISDN_X25\n\t\t\tstruct concap_proto * cprot = p -> cprot;\n#endif\n\t\t\tif (isdn_net_device_started(p)) {\n\t\t\t\tprintk(KERN_WARNING \"%s: cannot change encap when if is up\\n\",\n\t\t\t\t p->dev->name);\n\t\t\t\treturn -EBUSY;\n\t\t\t}\n#ifdef CONFIG_ISDN_X25\n\t\t\tif( cprot && cprot -> pops )\n\t\t\t\tcprot -> pops -> proto_del ( cprot );\n\t\t\tp -> cprot = NULL;\n\t\t\tlp -> dops = NULL;\n\t\t\t/* ... , prepare for configuration of new one ... */\n\t\t\tswitch ( cfg -> p_encap ){\n\t\t\tcase ISDN_NET_ENCAP_X25IFACE:\n\t\t\t\tlp -> dops = &isdn_concap_reliable_dl_dops;\n\t\t\t}\n\t\t\t/* ... and allocate new one ... */\n\t\t\tp -> cprot = isdn_concap_new( cfg -> p_encap );\n\t\t\t/* p -> cprot == NULL now if p_encap is not supported\n\t\t\t by means of the concap_proto mechanism */\n\t\t\t/* the protocol is not configured yet; this will\n\t\t\t happen later when isdn_net_reset() is called */\n#endif\n\t\t}\n\t\tswitch ( cfg->p_encap ) {\n\t\tcase ISDN_NET_ENCAP_SYNCPPP:\n#ifndef CONFIG_ISDN_PPP\n\t\t\tprintk(KERN_WARNING \"%s: SyncPPP support not configured\\n\",\n\t\t\t p->dev->name);\n\t\t\treturn -EINVAL;\n#else\n\t\t\tp->dev->type = ARPHRD_PPP;\t/* change ARP type */\n\t\t\tp->dev->addr_len = 0;\n\t\t\tp->dev->do_ioctl = isdn_ppp_dev_ioctl;\n#endif\n\t\t\tbreak;\n\t\tcase ISDN_NET_ENCAP_X25IFACE:\n#ifndef CONFIG_ISDN_X25\n\t\t\tprintk(KERN_WARNING \"%s: isdn-x25 support not configured\\n\",\n\t\t\t p->dev->name);\n\t\t\treturn -EINVAL;\n#else\n\t\t\tp->dev->type = ARPHRD_X25;\t/* change ARP type */\n\t\t\tp->dev->addr_len = 0;\n#endif\n\t\t\tbreak;\n\t\tcase ISDN_NET_ENCAP_CISCOHDLCK:\n\t\t\tp->dev->do_ioctl = isdn_ciscohdlck_dev_ioctl;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif( cfg->p_encap >= 0 &&\n\t\t\t cfg->p_encap <= ISDN_NET_ENCAP_MAX_ENCAP )\n\t\t\t\tbreak;\n\t\t\tprintk(KERN_WARNING\n\t\t\t \"%s: encapsulation protocol %d not supported\\n\",\n\t\t\t p->dev->name, cfg->p_encap);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (strlen(cfg->drvid)) {\n\t\t\t/* A bind has been requested ... */\n\t\t\tchar *c,\n\t\t\t*e;\n\n\t\t\tdrvidx = -1;\n\t\t\tchidx = -1;\n\t\t\tstrcpy(drvid, cfg->drvid);\n\t\t\tif ((c = strchr(drvid, ','))) {\n\t\t\t\t/* The channel-number is appended to the driver-Id with a comma */\n\t\t\t\tchidx = (int) simple_strtoul(c + 1, &e, 10);\n\t\t\t\tif (e == c)\n\t\t\t\t\tchidx = -1;\n\t\t\t\t*c = '\\0';\n\t\t\t}\n\t\t\tfor (i = 0; i < ISDN_MAX_DRIVERS; i++)\n\t\t\t\t/* Lookup driver-Id in array */\n\t\t\t\tif (!(strcmp(dev->drvid[i], drvid))) {\n\t\t\t\t\tdrvidx = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tif ((drvidx == -1) || (chidx == -1))\n\t\t\t\t/* Either driver-Id or channel-number invalid */\n\t\t\t\treturn -ENODEV;\n\t\t} else {\n\t\t\t/* Parameters are valid, so get them */\n\t\t\tdrvidx = lp->pre_device;\n\t\t\tchidx = lp->pre_channel;\n\t\t}\n\t\tif (cfg->exclusive > 0) {\n\t\t\tunsigned long flags;\n\n\t\t\t/* If binding is exclusive, try to grab the channel */\n\t\t\tspin_lock_irqsave(&dev->lock, flags);\n\t\t\tif ((i = isdn_get_free_channel(ISDN_USAGE_NET,\n\t\t\t\tlp->l2_proto, lp->l3_proto, drvidx,\n\t\t\t\tchidx, lp->msn)) < 0) {\n\t\t\t\t/* Grab failed, because desired channel is in use */\n\t\t\t\tlp->exclusive = -1;\n\t\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\t\treturn -EBUSY;\n\t\t\t}\n\t\t\t/* All went ok, so update isdninfo */\n\t\t\tdev->usage[i] = ISDN_USAGE_EXCLUSIVE;\n\t\t\tisdn_info_update();\n\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\tlp->exclusive = i;\n\t\t} else {\n\t\t\t/* Non-exclusive binding or unbind. */\n\t\t\tlp->exclusive = -1;\n\t\t\tif ((lp->pre_device != -1) && (cfg->exclusive == -1)) {\n\t\t\t\tisdn_unexclusive_channel(lp->pre_device, lp->pre_channel);\n\t\t\t\tisdn_free_channel(lp->pre_device, lp->pre_channel, ISDN_USAGE_NET);\n\t\t\t\tdrvidx = -1;\n\t\t\t\tchidx = -1;\n\t\t\t}\n\t\t}\n\t\tstrlcpy(lp->msn, cfg->eaz, sizeof(lp->msn));\n\t\tlp->pre_device = drvidx;\n\t\tlp->pre_channel = chidx;\n\t\tlp->onhtime = cfg->onhtime;\n\t\tlp->charge = cfg->charge;\n\t\tlp->l2_proto = cfg->l2_proto;\n\t\tlp->l3_proto = cfg->l3_proto;\n\t\tlp->cbdelay = cfg->cbdelay;\n\t\tlp->dialmax = cfg->dialmax;\n\t\tlp->triggercps = cfg->triggercps;\n\t\tlp->slavedelay = cfg->slavedelay * HZ;\n\t\tlp->pppbind = cfg->pppbind;\n\t\tlp->dialtimeout = cfg->dialtimeout >= 0 ? cfg->dialtimeout * HZ : -1;\n\t\tlp->dialwait = cfg->dialwait * HZ;\n\t\tif (cfg->secure)\n\t\t\tlp->flags |= ISDN_NET_SECURE;\n\t\telse\n\t\t\tlp->flags &= ~ISDN_NET_SECURE;\n\t\tif (cfg->cbhup)\n\t\t\tlp->flags |= ISDN_NET_CBHUP;\n\t\telse\n\t\t\tlp->flags &= ~ISDN_NET_CBHUP;\n\t\tswitch (cfg->callback) {\n\t\t\tcase 0:\n\t\t\t\tlp->flags &= ~(ISDN_NET_CALLBACK | ISDN_NET_CBOUT);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tlp->flags |= ISDN_NET_CALLBACK;\n\t\t\t\tlp->flags &= ~ISDN_NET_CBOUT;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tlp->flags |= ISDN_NET_CBOUT;\n\t\t\t\tlp->flags &= ~ISDN_NET_CALLBACK;\n\t\t\t\tbreak;\n\t\t}\n\t\tlp->flags &= ~ISDN_NET_DIALMODE_MASK;\t/* first all bits off */\n\t\tif (cfg->dialmode && !(cfg->dialmode & ISDN_NET_DIALMODE_MASK)) {\n\t\t\t/* old isdnctrl version, where only 0 or 1 is given */\n\t\t\tprintk(KERN_WARNING\n\t\t\t \"Old isdnctrl version detected! Please update.\\n\");\n\t\t\tlp->flags |= ISDN_NET_DM_OFF; /* turn on `off' bit */\n\t\t}\n\t\telse {\n\t\t\tlp->flags |= cfg->dialmode; /* turn on selected bits */\n\t\t}\n\t\tif (cfg->chargehup)\n\t\t\tlp->hupflags |= ISDN_CHARGEHUP;\n\t\telse\n\t\t\tlp->hupflags &= ~ISDN_CHARGEHUP;\n\t\tif (cfg->ihup)\n\t\t\tlp->hupflags |= ISDN_INHUP;\n\t\telse\n\t\t\tlp->hupflags &= ~ISDN_INHUP;\n\t\tif (cfg->chargeint > 10) {\n\t\t\tlp->hupflags |= ISDN_CHARGEHUP | ISDN_HAVECHARGE | ISDN_MANCHARGE;\n\t\t\tlp->chargeint = cfg->chargeint * HZ;\n\t\t}\n\t\tif (cfg->p_encap != lp->p_encap) {\n\t\t\tif (cfg->p_encap == ISDN_NET_ENCAP_RAWIP) {\n\t\t\t\tp->dev->header_ops = NULL;\n\t\t\t\tp->dev->flags = IFF_NOARP|IFF_POINTOPOINT;\n\t\t\t} else {\n\t\t\t\tp->dev->header_ops = &isdn_header_ops;\n\t\t\t\tif (cfg->p_encap == ISDN_NET_ENCAP_ETHER)\n\t\t\t\t\tp->dev->flags = IFF_BROADCAST | IFF_MULTICAST;\n\t\t\t\telse\n\t\t\t\t\tp->dev->flags = IFF_NOARP|IFF_POINTOPOINT;\n\t\t\t}\n\t\t}\n\t\tlp->p_encap = cfg->p_encap;\n\t\treturn 0;\n\t}\n\treturn -ENODEV;\n}", "target": 0, "cwe": ["CWE-119"], "project": "linux-2.6", "commit_id": "0f13864e5b24d9cbe18d125d41bfa4b726a82e40", "hash": 155181909137210519302296943237798383854, "size": 215, "message": "isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil <kkeil@suse.de>\nSigned-off-by: Andrew Morton <akpm@linux-foundation.org>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "dataset": "other", "idx": 487418}
  1023. {"func": "static int dccp_setsockopt_change(struct sock *sk, int type,\n\t\t\t\t struct dccp_so_feat __user *optval)\n{\n\tstruct dccp_so_feat opt;\n\tu8 *val;\n\tint rc;\n\n\tif (copy_from_user(&opt, optval, sizeof(opt)))\n\t\treturn -EFAULT;\n\n\tval = kmalloc(opt.dccpsf_len, GFP_KERNEL);\n\tif (!val)\n\t\treturn -ENOMEM;\n\n\tif (copy_from_user(val, opt.dccpsf_val, opt.dccpsf_len)) {\n\t\trc = -EFAULT;\n\t\tgoto out_free_val;\n\t}\n\n\trc = dccp_feat_change(dccp_msk(sk), type, opt.dccpsf_feat,\n\t\t\t val, opt.dccpsf_len, GFP_KERNEL);\n\tif (rc)\n\t\tgoto out_free_val;\n\nout:\n\treturn rc;\n\nout_free_val:\n\tkfree(val);\n\tgoto out;\n}", "target": 1, "cwe": ["CWE-189"], "project": "linux-2.6", "commit_id": "3e8a0a559c66ee9e7468195691a56fefc3589740", "hash": 235127973499082598612098670784403396457, "size": 31, "message": "dccp: change L/R must have at least one byte in the dccpsf_val field\n \nThanks to Eugene Teo for reporting this problem.\n \nSigned-off-by: Eugene Teo <eugenete@kernel.sg>\nSigned-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>\nSigned-off-by: Gerrit Renker <gerrit@erg.abdn.ac.uk>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "dataset": "other", "idx": 215361}
  1024. {"func": "static int dccp_setsockopt_change(struct sock *sk, int type,\n\t\t\t\t struct dccp_so_feat __user *optval)\n{\n\tstruct dccp_so_feat opt;\n\tu8 *val;\n\tint rc;\n\n\tif (copy_from_user(&opt, optval, sizeof(opt)))\n\t\treturn -EFAULT;\n\t/*\n\t * rfc4340: 6.1. Change Options\n\t */\n\tif (opt.dccpsf_len < 1)\n\t\treturn -EINVAL;\n\n\tval = kmalloc(opt.dccpsf_len, GFP_KERNEL);\n\tif (!val)\n\t\treturn -ENOMEM;\n\n\tif (copy_from_user(val, opt.dccpsf_val, opt.dccpsf_len)) {\n\t\trc = -EFAULT;\n\t\tgoto out_free_val;\n\t}\n\n\trc = dccp_feat_change(dccp_msk(sk), type, opt.dccpsf_feat,\n\t\t\t val, opt.dccpsf_len, GFP_KERNEL);\n\tif (rc)\n\t\tgoto out_free_val;\n\nout:\n\treturn rc;\n\nout_free_val:\n\tkfree(val);\n\tgoto out;\n}", "target": 0, "cwe": ["CWE-189"], "project": "linux-2.6", "commit_id": "3e8a0a559c66ee9e7468195691a56fefc3589740", "hash": 78779612884963753154791824378443907712, "size": 36, "message": "dccp: change L/R must have at least one byte in the dccpsf_val field\n \nThanks to Eugene Teo for reporting this problem.\n \nSigned-off-by: Eugene Teo <eugenete@kernel.sg>\nSigned-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>\nSigned-off-by: Gerrit Renker <gerrit@erg.abdn.ac.uk>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "dataset": "other", "idx": 488804}
  1025. {"func": "sbni_ioctl( struct net_device *dev, struct ifreq *ifr, int cmd )\n{\n\tstruct net_local *nl = (struct net_local *) dev->priv; \n\tstruct sbni_flags flags;\n\tint error = 0;\n\n#ifdef CONFIG_SBNI_MULTILINE\n\tstruct net_device *slave_dev;\n\tchar slave_name[ 8 ];\n#endif\n \n\tswitch( cmd ) {\n\tcase SIOCDEVGETINSTATS :\n\t\tif (copy_to_user( ifr->ifr_data, &nl->in_stats,\n\t\t\t\t\tsizeof(struct sbni_in_stats) ))\n\t\t\terror = -EFAULT;\n\t\tbreak;\n\n\tcase SIOCDEVRESINSTATS :\n\t\tif( current->euid != 0 )\t/* root only */\n\t\t\treturn -EPERM;\n\t\tmemset( &nl->in_stats, 0, sizeof(struct sbni_in_stats) );\n\t\tbreak;\n\n\tcase SIOCDEVGHWSTATE :\n\t\tflags.mac_addr\t= *(u32 *)(dev->dev_addr + 3);\n\t\tflags.rate\t= nl->csr1.rate;\n\t\tflags.slow_mode\t= (nl->state & FL_SLOW_MODE) != 0;\n\t\tflags.rxl\t= nl->cur_rxl_index;\n\t\tflags.fixed_rxl\t= nl->delta_rxl == 0;\n\n\t\tif (copy_to_user( ifr->ifr_data, &flags, sizeof flags ))\n\t\t\terror = -EFAULT;\n\t\tbreak;\n\n\tcase SIOCDEVSHWSTATE :\n\t\tif( current->euid != 0 )\t/* root only */\n\t\t\treturn -EPERM;\n\n\t\tspin_lock( &nl->lock );\n\t\tflags = *(struct sbni_flags*) &ifr->ifr_ifru;\n\t\tif( flags.fixed_rxl )\n\t\t\tnl->delta_rxl = 0,\n\t\t\tnl->cur_rxl_index = flags.rxl;\n\t\telse\n\t\t\tnl->delta_rxl = DEF_RXL_DELTA,\n\t\t\tnl->cur_rxl_index = DEF_RXL;\n\n\t\tnl->csr1.rxl = rxl_tab[ nl->cur_rxl_index ];\n\t\tnl->csr1.rate = flags.rate;\n\t\toutb( *(u8 *)&nl->csr1 | PR_RES, dev->base_addr + CSR1 );\n\t\tspin_unlock( &nl->lock );\n\t\tbreak;\n\n#ifdef CONFIG_SBNI_MULTILINE\n\n\tcase SIOCDEVENSLAVE :\n\t\tif( current->euid != 0 )\t/* root only */\n\t\t\treturn -EPERM;\n\n\t\tif (copy_from_user( slave_name, ifr->ifr_data, sizeof slave_name ))\n\t\t\treturn -EFAULT;\n\t\tslave_dev = dev_get_by_name(&init_net, slave_name );\n\t\tif( !slave_dev || !(slave_dev->flags & IFF_UP) ) {\n\t\t\tprintk( KERN_ERR \"%s: trying to enslave non-active \"\n\t\t\t\t\"device %s\\n\", dev->name, slave_name );\n\t\t\treturn -EPERM;\n\t\t}\n\n\t\treturn enslave( dev, slave_dev );\n\n\tcase SIOCDEVEMANSIPATE :\n\t\tif( current->euid != 0 )\t/* root only */\n\t\t\treturn -EPERM;\n\n\t\treturn emancipate( dev );\n\n#endif\t/* CONFIG_SBNI_MULTILINE */\n\n\tdefault :\n\t\treturn -EOPNOTSUPP;\n\t}\n\n\treturn error;\n}", "target": 1, "cwe": ["CWE-264"], "project": "linux-2.6", "commit_id": "f2455eb176ac87081bbfc9a44b21c7cd2bc1967e", "hash": 334362285214514794810840380680596988050, "size": 85, "message": "wan: Missing capability checks in sbni_ioctl()\n\nThere are missing capability checks in the following code:\n\n1300 static int\n1301 sbni_ioctl( struct net_device *dev, struct ifreq *ifr, int cmd)\n1302 {\n[...]\n1319 case SIOCDEVRESINSTATS :\n1320 if( current->euid != 0 ) /* root only */\n1321 return -EPERM;\n[...]\n1336 case SIOCDEVSHWSTATE :\n1337 if( current->euid != 0 ) /* root only */\n1338 return -EPERM;\n[...]\n1357 case SIOCDEVENSLAVE :\n1358 if( current->euid != 0 ) /* root only */\n1359 return -EPERM;\n[...]\n1372 case SIOCDEVEMANSIPATE :\n1373 if( current->euid != 0 ) /* root only */\n1374 return -EPERM;\n\nHere's my proposed fix:\n\nMissing capability checks.\n\nSigned-off-by: Eugene Teo <eugeneteo@kernel.sg>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "dataset": "other", "idx": 215379}
  1026. {"func": "sbni_ioctl( struct net_device *dev, struct ifreq *ifr, int cmd )\n{\n\tstruct net_local *nl = (struct net_local *) dev->priv; \n\tstruct sbni_flags flags;\n\tint error = 0;\n\n#ifdef CONFIG_SBNI_MULTILINE\n\tstruct net_device *slave_dev;\n\tchar slave_name[ 8 ];\n#endif\n \n\tswitch( cmd ) {\n\tcase SIOCDEVGETINSTATS :\n\t\tif (copy_to_user( ifr->ifr_data, &nl->in_stats,\n\t\t\t\t\tsizeof(struct sbni_in_stats) ))\n\t\t\terror = -EFAULT;\n\t\tbreak;\n\n\tcase SIOCDEVRESINSTATS :\n\t\tif (!capable(CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\t\tmemset( &nl->in_stats, 0, sizeof(struct sbni_in_stats) );\n\t\tbreak;\n\n\tcase SIOCDEVGHWSTATE :\n\t\tflags.mac_addr\t= *(u32 *)(dev->dev_addr + 3);\n\t\tflags.rate\t= nl->csr1.rate;\n\t\tflags.slow_mode\t= (nl->state & FL_SLOW_MODE) != 0;\n\t\tflags.rxl\t= nl->cur_rxl_index;\n\t\tflags.fixed_rxl\t= nl->delta_rxl == 0;\n\n\t\tif (copy_to_user( ifr->ifr_data, &flags, sizeof flags ))\n\t\t\terror = -EFAULT;\n\t\tbreak;\n\n\tcase SIOCDEVSHWSTATE :\n\t\tif (!capable(CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\n\t\tspin_lock( &nl->lock );\n\t\tflags = *(struct sbni_flags*) &ifr->ifr_ifru;\n\t\tif( flags.fixed_rxl )\n\t\t\tnl->delta_rxl = 0,\n\t\t\tnl->cur_rxl_index = flags.rxl;\n\t\telse\n\t\t\tnl->delta_rxl = DEF_RXL_DELTA,\n\t\t\tnl->cur_rxl_index = DEF_RXL;\n\n\t\tnl->csr1.rxl = rxl_tab[ nl->cur_rxl_index ];\n\t\tnl->csr1.rate = flags.rate;\n\t\toutb( *(u8 *)&nl->csr1 | PR_RES, dev->base_addr + CSR1 );\n\t\tspin_unlock( &nl->lock );\n\t\tbreak;\n\n#ifdef CONFIG_SBNI_MULTILINE\n\n\tcase SIOCDEVENSLAVE :\n\t\tif (!capable(CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\n\t\tif (copy_from_user( slave_name, ifr->ifr_data, sizeof slave_name ))\n\t\t\treturn -EFAULT;\n\t\tslave_dev = dev_get_by_name(&init_net, slave_name );\n\t\tif( !slave_dev || !(slave_dev->flags & IFF_UP) ) {\n\t\t\tprintk( KERN_ERR \"%s: trying to enslave non-active \"\n\t\t\t\t\"device %s\\n\", dev->name, slave_name );\n\t\t\treturn -EPERM;\n\t\t}\n\n\t\treturn enslave( dev, slave_dev );\n\n\tcase SIOCDEVEMANSIPATE :\n\t\tif (!capable(CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\n\t\treturn emancipate( dev );\n\n#endif\t/* CONFIG_SBNI_MULTILINE */\n\n\tdefault :\n\t\treturn -EOPNOTSUPP;\n\t}\n\n\treturn error;\n}", "target": 0, "cwe": ["CWE-264"], "project": "linux-2.6", "commit_id": "f2455eb176ac87081bbfc9a44b21c7cd2bc1967e", "hash": 232324628272873095618685062531940041066, "size": 85, "message": "wan: Missing capability checks in sbni_ioctl()\n\nThere are missing capability checks in the following code:\n\n1300 static int\n1301 sbni_ioctl( struct net_device *dev, struct ifreq *ifr, int cmd)\n1302 {\n[...]\n1319 case SIOCDEVRESINSTATS :\n1320 if( current->euid != 0 ) /* root only */\n1321 return -EPERM;\n[...]\n1336 case SIOCDEVSHWSTATE :\n1337 if( current->euid != 0 ) /* root only */\n1338 return -EPERM;\n[...]\n1357 case SIOCDEVENSLAVE :\n1358 if( current->euid != 0 ) /* root only */\n1359 return -EPERM;\n[...]\n1372 case SIOCDEVEMANSIPATE :\n1373 if( current->euid != 0 ) /* root only */\n1374 return -EPERM;\n\nHere's my proposed fix:\n\nMissing capability checks.\n\nSigned-off-by: Eugene Teo <eugeneteo@kernel.sg>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "dataset": "other", "idx": 488945}
  1027. {"func": "static int svc_listen(struct socket *sock,int backlog)\n{\n\tDEFINE_WAIT(wait);\n\tstruct sock *sk = sock->sk;\n\tstruct atm_vcc *vcc = ATM_SD(sock);\n\tint error;\n\n\tpr_debug(\"svc_listen %p\\n\",vcc);\n\tlock_sock(sk);\n\t/* let server handle listen on unbound sockets */\n\tif (test_bit(ATM_VF_SESSION,&vcc->flags)) {\n\t\terror = -EINVAL;\n\t\tgoto out;\n\t}\n\tvcc_insert_socket(sk);\n\tset_bit(ATM_VF_WAITING, &vcc->flags);\n\tprepare_to_wait(sk->sk_sleep, &wait, TASK_UNINTERRUPTIBLE);\n\tsigd_enq(vcc,as_listen,NULL,NULL,&vcc->local);\n\twhile (test_bit(ATM_VF_WAITING, &vcc->flags) && sigd) {\n\t\tschedule();\n\t\tprepare_to_wait(sk->sk_sleep, &wait, TASK_UNINTERRUPTIBLE);\n\t}\n\tfinish_wait(sk->sk_sleep, &wait);\n\tif (!sigd) {\n\t\terror = -EUNATCH;\n\t\tgoto out;\n\t}\n\tset_bit(ATM_VF_LISTEN,&vcc->flags);\n\tsk->sk_max_ack_backlog = backlog > 0 ? backlog : ATM_BACKLOG_DEFAULT;\n\terror = -sk->sk_err;\nout:\n\trelease_sock(sk);\n\treturn error;\n}", "target": 1, "cwe": ["CWE-399"], "project": "linux-2.6", "commit_id": "17b24b3c97498935a2ef9777370b1151dfed3f6f", "hash": 319036396244354828165290676039011878041, "size": 34, "message": "ATM: CVE-2008-5079: duplicate listen() on socket corrupts the vcc table\n\nAs reported by Hugo Dias that it is possible to cause a local denial\nof service attack by calling the svc_listen function twice on the same\nsocket and reading /proc/net/atm/*vc\n\nSigned-off-by: Chas Williams <chas@cmf.nrl.navy.mil>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "dataset": "other", "idx": 215446}
  1028. {"func": "static int svc_listen(struct socket *sock,int backlog)\n{\n\tDEFINE_WAIT(wait);\n\tstruct sock *sk = sock->sk;\n\tstruct atm_vcc *vcc = ATM_SD(sock);\n\tint error;\n\n\tpr_debug(\"svc_listen %p\\n\",vcc);\n\tlock_sock(sk);\n\t/* let server handle listen on unbound sockets */\n\tif (test_bit(ATM_VF_SESSION,&vcc->flags)) {\n\t\terror = -EINVAL;\n\t\tgoto out;\n\t}\n\tif (test_bit(ATM_VF_LISTEN, &vcc->flags)) {\n\t\terror = -EADDRINUSE;\n\t\tgoto out;\n }\n\tset_bit(ATM_VF_WAITING, &vcc->flags);\n\tprepare_to_wait(sk->sk_sleep, &wait, TASK_UNINTERRUPTIBLE);\n\tsigd_enq(vcc,as_listen,NULL,NULL,&vcc->local);\n\twhile (test_bit(ATM_VF_WAITING, &vcc->flags) && sigd) {\n\t\tschedule();\n\t\tprepare_to_wait(sk->sk_sleep, &wait, TASK_UNINTERRUPTIBLE);\n\t}\n\tfinish_wait(sk->sk_sleep, &wait);\n\tif (!sigd) {\n\t\terror = -EUNATCH;\n\t\tgoto out;\n\t}\n\tset_bit(ATM_VF_LISTEN,&vcc->flags);\n\tvcc_insert_socket(sk);\n\tsk->sk_max_ack_backlog = backlog > 0 ? backlog : ATM_BACKLOG_DEFAULT;\n\terror = -sk->sk_err;\nout:\n\trelease_sock(sk);\n\treturn error;\n}", "target": 0, "cwe": ["CWE-399"], "project": "linux-2.6", "commit_id": "17b24b3c97498935a2ef9777370b1151dfed3f6f", "hash": 124880737917680262812022112240721930476, "size": 38, "message": "ATM: CVE-2008-5079: duplicate listen() on socket corrupts the vcc table\n\nAs reported by Hugo Dias that it is possible to cause a local denial\nof service attack by calling the svc_listen function twice on the same\nsocket and reading /proc/net/atm/*vc\n\nSigned-off-by: Chas Williams <chas@cmf.nrl.navy.mil>\nSigned-off-by: David S. Miller <davem@davemloft.net>", "dataset": "other", "idx": 489598}
  1029. {"func": "int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\tstruct ext4_super_block *es = sbi->s_es;\n\tint reserved_gdb = ext4_bg_has_super(sb, input->group) ?\n\t\tle16_to_cpu(es->s_reserved_gdt_blocks) : 0;\n\tstruct buffer_head *primary = NULL;\n\tstruct ext4_group_desc *gdp;\n\tstruct inode *inode = NULL;\n\thandle_t *handle;\n\tint gdb_off, gdb_num;\n\tint num_grp_locked = 0;\n\tint err, err2;\n\n\tgdb_num = input->group / EXT4_DESC_PER_BLOCK(sb);\n\tgdb_off = input->group % EXT4_DESC_PER_BLOCK(sb);\n\n\tif (gdb_off == 0 && !EXT4_HAS_RO_COMPAT_FEATURE(sb,\n\t\t\t\t\tEXT4_FEATURE_RO_COMPAT_SPARSE_SUPER)) {\n\t\text4_warning(sb, __func__,\n\t\t\t \"Can't resize non-sparse filesystem further\");\n\t\treturn -EPERM;\n\t}\n\n\tif (ext4_blocks_count(es) + input->blocks_count <\n\t ext4_blocks_count(es)) {\n\t\text4_warning(sb, __func__, \"blocks_count overflow\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (le32_to_cpu(es->s_inodes_count) + EXT4_INODES_PER_GROUP(sb) <\n\t le32_to_cpu(es->s_inodes_count)) {\n\t\text4_warning(sb, __func__, \"inodes_count overflow\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (reserved_gdb || gdb_off == 0) {\n\t\tif (!EXT4_HAS_COMPAT_FEATURE(sb,\n\t\t\t\t\t EXT4_FEATURE_COMPAT_RESIZE_INODE)\n\t\t || !le16_to_cpu(es->s_reserved_gdt_blocks)) {\n\t\t\text4_warning(sb, __func__,\n\t\t\t\t \"No reserved GDT blocks, can't resize\");\n\t\t\treturn -EPERM;\n\t\t}\n\t\tinode = ext4_iget(sb, EXT4_RESIZE_INO);\n\t\tif (IS_ERR(inode)) {\n\t\t\text4_warning(sb, __func__,\n\t\t\t\t \"Error opening resize inode\");\n\t\t\treturn PTR_ERR(inode);\n\t\t}\n\t}\n\n\n\tif ((err = verify_group_input(sb, input)))\n\t\tgoto exit_put;\n\n\tif ((err = setup_new_group_blocks(sb, input)))\n\t\tgoto exit_put;\n\n\t/*\n\t * We will always be modifying at least the superblock and a GDT\n\t * block. If we are adding a group past the last current GDT block,\n\t * we will also modify the inode and the dindirect block. If we\n\t * are adding a group with superblock/GDT backups we will also\n\t * modify each of the reserved GDT dindirect blocks.\n\t */\n\thandle = ext4_journal_start_sb(sb,\n\t\t\t\t ext4_bg_has_super(sb, input->group) ?\n\t\t\t\t 3 + reserved_gdb : 4);\n\tif (IS_ERR(handle)) {\n\t\terr = PTR_ERR(handle);\n\t\tgoto exit_put;\n\t}\n\n\tlock_super(sb);\n\tif (input->group != sbi->s_groups_count) {\n\t\text4_warning(sb, __func__,\n\t\t\t \"multiple resizers run on filesystem!\");\n\t\terr = -EBUSY;\n\t\tgoto exit_journal;\n\t}\n\n\tif ((err = ext4_journal_get_write_access(handle, sbi->s_sbh)))\n\t\tgoto exit_journal;\n\n /*\n * We will only either add reserved group blocks to a backup group\n * or remove reserved blocks for the first group in a new group block.\n * Doing both would be mean more complex code, and sane people don't\n * use non-sparse filesystems anymore. This is already checked above.\n */\n\tif (gdb_off) {\n\t\tprimary = sbi->s_group_desc[gdb_num];\n\t\tif ((err = ext4_journal_get_write_access(handle, primary)))\n\t\t\tgoto exit_journal;\n\n\t\tif (reserved_gdb && ext4_bg_num_gdb(sb, input->group) &&\n\t\t (err = reserve_backup_gdb(handle, inode, input)))\n\t\t\tgoto exit_journal;\n\t} else if ((err = add_new_gdb(handle, inode, input, &primary)))\n\t\tgoto exit_journal;\n\n /*\n * OK, now we've set up the new group. Time to make it active.\n *\n * Current kernels don't lock all allocations via lock_super(),\n * so we have to be safe wrt. concurrent accesses the group\n * data. So we need to be careful to set all of the relevant\n * group descriptor data etc. *before* we enable the group.\n *\n * The key field here is sbi->s_groups_count: as long as\n * that retains its old value, nobody is going to access the new\n * group.\n *\n * So first we update all the descriptor metadata for the new\n * group; then we update the total disk blocks count; then we\n * update the groups count to enable the group; then finally we\n * update the free space counts so that the system can start\n * using the new disk blocks.\n */\n\n\tnum_grp_locked = ext4_mb_get_buddy_cache_lock(sb, input->group);\n\t/* Update group descriptor block for new group */\n\tgdp = (struct ext4_group_desc *)((char *)primary->b_data +\n\t\t\t\t\t gdb_off * EXT4_DESC_SIZE(sb));\n\n\text4_block_bitmap_set(sb, gdp, input->block_bitmap); /* LV FIXME */\n\text4_inode_bitmap_set(sb, gdp, input->inode_bitmap); /* LV FIXME */\n\text4_inode_table_set(sb, gdp, input->inode_table); /* LV FIXME */\n\text4_free_blks_set(sb, gdp, input->free_blocks_count);\n\text4_free_inodes_set(sb, gdp, EXT4_INODES_PER_GROUP(sb));\n\tgdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED);\n\tgdp->bg_checksum = ext4_group_desc_csum(sbi, input->group, gdp);\n\n\t/*\n\t * We can allocate memory for mb_alloc based on the new group\n\t * descriptor\n\t */\n\terr = ext4_mb_add_groupinfo(sb, input->group, gdp);\n\tif (err) {\n\t\text4_mb_put_buddy_cache_lock(sb, input->group, num_grp_locked);\n\t\tgoto exit_journal;\n\t}\n\n\t/*\n\t * Make the new blocks and inodes valid next. We do this before\n\t * increasing the group count so that once the group is enabled,\n\t * all of its blocks and inodes are already valid.\n\t *\n\t * We always allocate group-by-group, then block-by-block or\n\t * inode-by-inode within a group, so enabling these\n\t * blocks/inodes before the group is live won't actually let us\n\t * allocate the new space yet.\n\t */\n\text4_blocks_count_set(es, ext4_blocks_count(es) +\n\t\tinput->blocks_count);\n\tle32_add_cpu(&es->s_inodes_count, EXT4_INODES_PER_GROUP(sb));\n\n\t/*\n\t * We need to protect s_groups_count against other CPUs seeing\n\t * inconsistent state in the superblock.\n\t *\n\t * The precise rules we use are:\n\t *\n\t * * Writers of s_groups_count *must* hold lock_super\n\t * AND\n\t * * Writers must perform a smp_wmb() after updating all dependent\n\t * data and before modifying the groups count\n\t *\n\t * * Readers must hold lock_super() over the access\n\t * OR\n\t * * Readers must perform an smp_rmb() after reading the groups count\n\t * and before reading any dependent data.\n\t *\n\t * NB. These rules can be relaxed when checking the group count\n\t * while freeing data, as we can only allocate from a block\n\t * group after serialising against the group count, and we can\n\t * only then free after serialising in turn against that\n\t * allocation.\n\t */\n\tsmp_wmb();\n\n\t/* Update the global fs size fields */\n\tsbi->s_groups_count++;\n\text4_mb_put_buddy_cache_lock(sb, input->group, num_grp_locked);\n\n\text4_handle_dirty_metadata(handle, NULL, primary);\n\n\t/* Update the reserved block counts only once the new group is\n\t * active. */\n\text4_r_blocks_count_set(es, ext4_r_blocks_count(es) +\n\t\tinput->reserved_blocks);\n\n\t/* Update the free space counts */\n\tpercpu_counter_add(&sbi->s_freeblocks_counter,\n\t\t\t input->free_blocks_count);\n\tpercpu_counter_add(&sbi->s_freeinodes_counter,\n\t\t\t EXT4_INODES_PER_GROUP(sb));\n\n\tif (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {\n\t\text4_group_t flex_group;\n\t\tflex_group = ext4_flex_group(sbi, input->group);\n\t\tsbi->s_flex_groups[flex_group].free_blocks +=\n\t\t\tinput->free_blocks_count;\n\t\tsbi->s_flex_groups[flex_group].free_inodes +=\n\t\t\tEXT4_INODES_PER_GROUP(sb);\n\t}\n\n\text4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);\n\tsb->s_dirt = 1;\n\nexit_journal:\n\tunlock_super(sb);\n\tif ((err2 = ext4_journal_stop(handle)) && !err)\n\t\terr = err2;\n\tif (!err) {\n\t\tupdate_backups(sb, sbi->s_sbh->b_blocknr, (char *)es,\n\t\t\t sizeof(struct ext4_super_block));\n\t\tupdate_backups(sb, primary->b_blocknr, primary->b_data,\n\t\t\t primary->b_size);\n\t}\nexit_put:\n\tiput(inode);\n\treturn err;\n} /* ext4_group_add */", "target": 1, "cwe": ["CWE-20"], "project": "linux-2.6", "commit_id": "fdff73f094e7220602cc3f8959c7230517976412", "hash": 281245565929730846006190005126700543134, "size": 225, "message": "ext4: Initialize the new group descriptor when resizing the filesystem\n\nMake sure all of the fields of the group descriptor are properly\ninitialized. Previously, we allowed bg_flags field to be contain\nrandom garbage, which could trigger non-deterministic behavior,\nincluding a kernel OOPS.\n\nhttp://bugzilla.kernel.org/show_bug.cgi?id=12433\n\nSigned-off-by: \"Theodore Ts'o\" <tytso@mit.edu>\nCc: stable@kernel.org", "dataset": "other", "idx": 215458}
  1030. {"func": "int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\tstruct ext4_super_block *es = sbi->s_es;\n\tint reserved_gdb = ext4_bg_has_super(sb, input->group) ?\n\t\tle16_to_cpu(es->s_reserved_gdt_blocks) : 0;\n\tstruct buffer_head *primary = NULL;\n\tstruct ext4_group_desc *gdp;\n\tstruct inode *inode = NULL;\n\thandle_t *handle;\n\tint gdb_off, gdb_num;\n\tint num_grp_locked = 0;\n\tint err, err2;\n\n\tgdb_num = input->group / EXT4_DESC_PER_BLOCK(sb);\n\tgdb_off = input->group % EXT4_DESC_PER_BLOCK(sb);\n\n\tif (gdb_off == 0 && !EXT4_HAS_RO_COMPAT_FEATURE(sb,\n\t\t\t\t\tEXT4_FEATURE_RO_COMPAT_SPARSE_SUPER)) {\n\t\text4_warning(sb, __func__,\n\t\t\t \"Can't resize non-sparse filesystem further\");\n\t\treturn -EPERM;\n\t}\n\n\tif (ext4_blocks_count(es) + input->blocks_count <\n\t ext4_blocks_count(es)) {\n\t\text4_warning(sb, __func__, \"blocks_count overflow\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (le32_to_cpu(es->s_inodes_count) + EXT4_INODES_PER_GROUP(sb) <\n\t le32_to_cpu(es->s_inodes_count)) {\n\t\text4_warning(sb, __func__, \"inodes_count overflow\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (reserved_gdb || gdb_off == 0) {\n\t\tif (!EXT4_HAS_COMPAT_FEATURE(sb,\n\t\t\t\t\t EXT4_FEATURE_COMPAT_RESIZE_INODE)\n\t\t || !le16_to_cpu(es->s_reserved_gdt_blocks)) {\n\t\t\text4_warning(sb, __func__,\n\t\t\t\t \"No reserved GDT blocks, can't resize\");\n\t\t\treturn -EPERM;\n\t\t}\n\t\tinode = ext4_iget(sb, EXT4_RESIZE_INO);\n\t\tif (IS_ERR(inode)) {\n\t\t\text4_warning(sb, __func__,\n\t\t\t\t \"Error opening resize inode\");\n\t\t\treturn PTR_ERR(inode);\n\t\t}\n\t}\n\n\n\tif ((err = verify_group_input(sb, input)))\n\t\tgoto exit_put;\n\n\tif ((err = setup_new_group_blocks(sb, input)))\n\t\tgoto exit_put;\n\n\t/*\n\t * We will always be modifying at least the superblock and a GDT\n\t * block. If we are adding a group past the last current GDT block,\n\t * we will also modify the inode and the dindirect block. If we\n\t * are adding a group with superblock/GDT backups we will also\n\t * modify each of the reserved GDT dindirect blocks.\n\t */\n\thandle = ext4_journal_start_sb(sb,\n\t\t\t\t ext4_bg_has_super(sb, input->group) ?\n\t\t\t\t 3 + reserved_gdb : 4);\n\tif (IS_ERR(handle)) {\n\t\terr = PTR_ERR(handle);\n\t\tgoto exit_put;\n\t}\n\n\tlock_super(sb);\n\tif (input->group != sbi->s_groups_count) {\n\t\text4_warning(sb, __func__,\n\t\t\t \"multiple resizers run on filesystem!\");\n\t\terr = -EBUSY;\n\t\tgoto exit_journal;\n\t}\n\n\tif ((err = ext4_journal_get_write_access(handle, sbi->s_sbh)))\n\t\tgoto exit_journal;\n\n /*\n * We will only either add reserved group blocks to a backup group\n * or remove reserved blocks for the first group in a new group block.\n * Doing both would be mean more complex code, and sane people don't\n * use non-sparse filesystems anymore. This is already checked above.\n */\n\tif (gdb_off) {\n\t\tprimary = sbi->s_group_desc[gdb_num];\n\t\tif ((err = ext4_journal_get_write_access(handle, primary)))\n\t\t\tgoto exit_journal;\n\n\t\tif (reserved_gdb && ext4_bg_num_gdb(sb, input->group) &&\n\t\t (err = reserve_backup_gdb(handle, inode, input)))\n\t\t\tgoto exit_journal;\n\t} else if ((err = add_new_gdb(handle, inode, input, &primary)))\n\t\tgoto exit_journal;\n\n /*\n * OK, now we've set up the new group. Time to make it active.\n *\n * Current kernels don't lock all allocations via lock_super(),\n * so we have to be safe wrt. concurrent accesses the group\n * data. So we need to be careful to set all of the relevant\n * group descriptor data etc. *before* we enable the group.\n *\n * The key field here is sbi->s_groups_count: as long as\n * that retains its old value, nobody is going to access the new\n * group.\n *\n * So first we update all the descriptor metadata for the new\n * group; then we update the total disk blocks count; then we\n * update the groups count to enable the group; then finally we\n * update the free space counts so that the system can start\n * using the new disk blocks.\n */\n\n\tnum_grp_locked = ext4_mb_get_buddy_cache_lock(sb, input->group);\n\t/* Update group descriptor block for new group */\n\tgdp = (struct ext4_group_desc *)((char *)primary->b_data +\n\t\t\t\t\t gdb_off * EXT4_DESC_SIZE(sb));\n\n\tmemset(gdp, 0, EXT4_DESC_SIZE(sb));\n\text4_block_bitmap_set(sb, gdp, input->block_bitmap); /* LV FIXME */\n\text4_inode_bitmap_set(sb, gdp, input->inode_bitmap); /* LV FIXME */\n\text4_inode_table_set(sb, gdp, input->inode_table); /* LV FIXME */\n\text4_free_blks_set(sb, gdp, input->free_blocks_count);\n\text4_free_inodes_set(sb, gdp, EXT4_INODES_PER_GROUP(sb));\n\tgdp->bg_flags = cpu_to_le16(EXT4_BG_INODE_ZEROED);\n\tgdp->bg_checksum = ext4_group_desc_csum(sbi, input->group, gdp);\n\n\t/*\n\t * We can allocate memory for mb_alloc based on the new group\n\t * descriptor\n\t */\n\terr = ext4_mb_add_groupinfo(sb, input->group, gdp);\n\tif (err) {\n\t\text4_mb_put_buddy_cache_lock(sb, input->group, num_grp_locked);\n\t\tgoto exit_journal;\n\t}\n\n\t/*\n\t * Make the new blocks and inodes valid next. We do this before\n\t * increasing the group count so that once the group is enabled,\n\t * all of its blocks and inodes are already valid.\n\t *\n\t * We always allocate group-by-group, then block-by-block or\n\t * inode-by-inode within a group, so enabling these\n\t * blocks/inodes before the group is live won't actually let us\n\t * allocate the new space yet.\n\t */\n\text4_blocks_count_set(es, ext4_blocks_count(es) +\n\t\tinput->blocks_count);\n\tle32_add_cpu(&es->s_inodes_count, EXT4_INODES_PER_GROUP(sb));\n\n\t/*\n\t * We need to protect s_groups_count against other CPUs seeing\n\t * inconsistent state in the superblock.\n\t *\n\t * The precise rules we use are:\n\t *\n\t * * Writers of s_groups_count *must* hold lock_super\n\t * AND\n\t * * Writers must perform a smp_wmb() after updating all dependent\n\t * data and before modifying the groups count\n\t *\n\t * * Readers must hold lock_super() over the access\n\t * OR\n\t * * Readers must perform an smp_rmb() after reading the groups count\n\t * and before reading any dependent data.\n\t *\n\t * NB. These rules can be relaxed when checking the group count\n\t * while freeing data, as we can only allocate from a block\n\t * group after serialising against the group count, and we can\n\t * only then free after serialising in turn against that\n\t * allocation.\n\t */\n\tsmp_wmb();\n\n\t/* Update the global fs size fields */\n\tsbi->s_groups_count++;\n\text4_mb_put_buddy_cache_lock(sb, input->group, num_grp_locked);\n\n\text4_handle_dirty_metadata(handle, NULL, primary);\n\n\t/* Update the reserved block counts only once the new group is\n\t * active. */\n\text4_r_blocks_count_set(es, ext4_r_blocks_count(es) +\n\t\tinput->reserved_blocks);\n\n\t/* Update the free space counts */\n\tpercpu_counter_add(&sbi->s_freeblocks_counter,\n\t\t\t input->free_blocks_count);\n\tpercpu_counter_add(&sbi->s_freeinodes_counter,\n\t\t\t EXT4_INODES_PER_GROUP(sb));\n\n\tif (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {\n\t\text4_group_t flex_group;\n\t\tflex_group = ext4_flex_group(sbi, input->group);\n\t\tsbi->s_flex_groups[flex_group].free_blocks +=\n\t\t\tinput->free_blocks_count;\n\t\tsbi->s_flex_groups[flex_group].free_inodes +=\n\t\t\tEXT4_INODES_PER_GROUP(sb);\n\t}\n\n\text4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);\n\tsb->s_dirt = 1;\n\nexit_journal:\n\tunlock_super(sb);\n\tif ((err2 = ext4_journal_stop(handle)) && !err)\n\t\terr = err2;\n\tif (!err) {\n\t\tupdate_backups(sb, sbi->s_sbh->b_blocknr, (char *)es,\n\t\t\t sizeof(struct ext4_super_block));\n\t\tupdate_backups(sb, primary->b_blocknr, primary->b_data,\n\t\t\t primary->b_size);\n\t}\nexit_put:\n\tiput(inode);\n\treturn err;\n} /* ext4_group_add */", "target": 0, "cwe": ["CWE-20"], "project": "linux-2.6", "commit_id": "fdff73f094e7220602cc3f8959c7230517976412", "hash": 193067835456666808284941587516352105575, "size": 226, "message": "ext4: Initialize the new group descriptor when resizing the filesystem\n\nMake sure all of the fields of the group descriptor are properly\ninitialized. Previously, we allowed bg_flags field to be contain\nrandom garbage, which could trigger non-deterministic behavior,\nincluding a kernel OOPS.\n\nhttp://bugzilla.kernel.org/show_bug.cgi?id=12433\n\nSigned-off-by: \"Theodore Ts'o\" <tytso@mit.edu>\nCc: stable@kernel.org", "dataset": "other", "idx": 489876}
  1031. {"func": "ecryptfs_write_metadata_to_contents(struct ecryptfs_crypt_stat *crypt_stat,\n\t\t\t\t struct dentry *ecryptfs_dentry,\n\t\t\t\t char *virt)\n{\n\tint rc;\n\n\trc = ecryptfs_write_lower(ecryptfs_dentry->d_inode, virt,\n\t\t\t\t 0, crypt_stat->num_header_bytes_at_front);\n\tif (rc)\n\t\tprintk(KERN_ERR \"%s: Error attempting to write header \"\n\t\t \"information to lower file; rc = [%d]\\n\", __func__,\n\t\t rc);\n\treturn rc;\n}", "target": 1, "cwe": ["CWE-189"], "project": "linux-2.6", "commit_id": "8faece5f906725c10e7a1f6caf84452abadbdc7b", "hash": 51541081489523491690380425150429530165, "size": 14, "message": "eCryptfs: Allocate a variable number of pages for file headers\n\nWhen allocating the memory used to store the eCryptfs header contents, a\nsingle, zeroed page was being allocated with get_zeroed_page().\nHowever, the size of an eCryptfs header is either PAGE_CACHE_SIZE or\nECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE (8192), whichever is larger, and is\nstored in the file's private_data->crypt_stat->num_header_bytes_at_front\nfield.\n\necryptfs_write_metadata_to_contents() was using\nnum_header_bytes_at_front to decide how many bytes should be written to\nthe lower filesystem for the file header. Unfortunately, at least 8K\nwas being written from the page, despite the chance of the single,\nzeroed page being smaller than 8K. This resulted in random areas of\nkernel memory being written between the 0x1000 and 0x1FFF bytes offsets\nin the eCryptfs file headers if PAGE_SIZE was 4K.\n\nThis patch allocates a variable number of pages, calculated with\nnum_header_bytes_at_front, and passes the number of allocated pages\nalong to ecryptfs_write_metadata_to_contents().\n\nThanks to Florian Streibelt for reporting the data leak and working with\nme to find the problem. 2.6.28 is the only kernel release with this\nvulnerability. Corresponds to CVE-2009-0787\n\nSigned-off-by: Tyler Hicks <tyhicks@linux.vnet.ibm.com>\nAcked-by: Dustin Kirkland <kirkland@canonical.com>\nReviewed-by: Eric Sandeen <sandeen@redhat.com>\nReviewed-by: Eugene Teo <eugeneteo@kernel.sg>\nCc: Greg KH <greg@kroah.com>\nCc: dann frazier <dannf@dannf.org>\nCc: Serge E. Hallyn <serue@us.ibm.com>\nCc: Florian Streibelt <florian@f-streibelt.de>\nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "dataset": "other", "idx": 215467}
  1032. {"func": "ecryptfs_write_metadata_to_contents(struct dentry *ecryptfs_dentry,\n\t\t\t\t char *virt, size_t virt_len)\n{\n\tint rc;\n\n\trc = ecryptfs_write_lower(ecryptfs_dentry->d_inode, virt,\n\t\t\t\t 0, virt_len);\n\tif (rc)\n\t\tprintk(KERN_ERR \"%s: Error attempting to write header \"\n\t\t \"information to lower file; rc = [%d]\\n\", __func__,\n\t\t rc);\n\treturn rc;\n}", "target": 0, "cwe": ["CWE-189"], "project": "linux-2.6", "commit_id": "8faece5f906725c10e7a1f6caf84452abadbdc7b", "hash": 39007406608263614536820566580045545541, "size": 13, "message": "eCryptfs: Allocate a variable number of pages for file headers\n\nWhen allocating the memory used to store the eCryptfs header contents, a\nsingle, zeroed page was being allocated with get_zeroed_page().\nHowever, the size of an eCryptfs header is either PAGE_CACHE_SIZE or\nECRYPTFS_MINIMUM_HEADER_EXTENT_SIZE (8192), whichever is larger, and is\nstored in the file's private_data->crypt_stat->num_header_bytes_at_front\nfield.\n\necryptfs_write_metadata_to_contents() was using\nnum_header_bytes_at_front to decide how many bytes should be written to\nthe lower filesystem for the file header. Unfortunately, at least 8K\nwas being written from the page, despite the chance of the single,\nzeroed page being smaller than 8K. This resulted in random areas of\nkernel memory being written between the 0x1000 and 0x1FFF bytes offsets\nin the eCryptfs file headers if PAGE_SIZE was 4K.\n\nThis patch allocates a variable number of pages, calculated with\nnum_header_bytes_at_front, and passes the number of allocated pages\nalong to ecryptfs_write_metadata_to_contents().\n\nThanks to Florian Streibelt for reporting the data leak and working with\nme to find the problem. 2.6.28 is the only kernel release with this\nvulnerability. Corresponds to CVE-2009-0787\n\nSigned-off-by: Tyler Hicks <tyhicks@linux.vnet.ibm.com>\nAcked-by: Dustin Kirkland <kirkland@canonical.com>\nReviewed-by: Eric Sandeen <sandeen@redhat.com>\nReviewed-by: Eugene Teo <eugeneteo@kernel.sg>\nCc: Greg KH <greg@kroah.com>\nCc: dann frazier <dannf@dannf.org>\nCc: Serge E. Hallyn <serue@us.ibm.com>\nCc: Florian Streibelt <florian@f-streibelt.de>\nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "dataset": "other", "idx": 490193}
  1033. {"func": "size_t util_path_encode(char *s, size_t len)\n{\n\tchar t[(len * 3)+1];\n\tsize_t i, j;\n\n\tfor (i = 0, j = 0; s[i] != '\\0'; i++) {\n\t\tif (s[i] == '/') {\n\t\t\tmemcpy(&t[j], \"\\\\x2f\", 4);\n\t\t\tj += 4;\n\t\t} else if (s[i] == '\\\\') {\n\t\t\tmemcpy(&t[j], \"\\\\x5c\", 4);\n\t\t\tj += 4;\n\t\t} else {\n\t\t\tt[j] = s[i];\n\t\t\tj++;\n\t\t}\n\t}\n\tif (len == 0)\n\t\treturn j;\n\ti = (j < len - 1) ? j : len - 1;\n\tmemcpy(s, t, i);\n\ts[i] = '\\0';\n\treturn j;\n}", "target": 1, "cwe": ["CWE-120"], "project": "udev", "commit_id": "662c3110803bd8c1aedacc36788e6fd028944314", "hash": 255890177997629526431555852871596671591, "size": 24, "message": "path_encode: fix max length calculation\n\nSebastian Krahmer wrote:\n> it should reserve 4 times not 3 times len :)", "dataset": "other", "idx": 215481}
  1034. {"func": "size_t util_path_encode(char *s, size_t len)\n{\n\tchar t[(len * 4)+1];\n\tsize_t i, j;\n\n\tfor (i = 0, j = 0; s[i] != '\\0'; i++) {\n\t\tif (s[i] == '/') {\n\t\t\tmemcpy(&t[j], \"\\\\x2f\", 4);\n\t\t\tj += 4;\n\t\t} else if (s[i] == '\\\\') {\n\t\t\tmemcpy(&t[j], \"\\\\x5c\", 4);\n\t\t\tj += 4;\n\t\t} else {\n\t\t\tt[j] = s[i];\n\t\t\tj++;\n\t\t}\n\t}\n\tif (len == 0)\n\t\treturn j;\n\ti = (j < len - 1) ? j : len - 1;\n\tmemcpy(s, t, i);\n\ts[i] = '\\0';\n\treturn j;\n}", "target": 0, "cwe": ["CWE-120"], "project": "udev", "commit_id": "662c3110803bd8c1aedacc36788e6fd028944314", "hash": 108373855040332074515926363142152806355, "size": 24, "message": "path_encode: fix max length calculation\n\nSebastian Krahmer wrote:\n> it should reserve 4 times not 3 times len :)", "dataset": "other", "idx": 490328}
  1035. {"func": "static int futex_lock_pi(u32 __user *uaddr, int fshared,\n\t\t\t int detect, ktime_t *time, int trylock)\n{\n\tstruct hrtimer_sleeper timeout, *to = NULL;\n\tstruct futex_hash_bucket *hb;\n\tstruct futex_q q;\n\tint res, ret;\n\n\tif (refill_pi_state_cache())\n\t\treturn -ENOMEM;\n\n\tif (time) {\n\t\tto = &timeout;\n\t\thrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,\n\t\t\t\t HRTIMER_MODE_ABS);\n\t\thrtimer_init_sleeper(to, current);\n\t\thrtimer_set_expires(&to->timer, *time);\n\t}\n\n\tq.pi_state = NULL;\n\tq.rt_waiter = NULL;\n\tq.requeue_pi_key = NULL;\nretry:\n\tq.key = FUTEX_KEY_INIT;\n\tret = get_futex_key(uaddr, fshared, &q.key);\n\tif (unlikely(ret != 0))\n\t\tgoto out;\n\nretry_private:\n\thb = queue_lock(&q);\n\n\tret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);\n\tif (unlikely(ret)) {\n\t\tswitch (ret) {\n\t\tcase 1:\n\t\t\t/* We got the lock. */\n\t\t\tret = 0;\n\t\t\tgoto out_unlock_put_key;\n\t\tcase -EFAULT:\n\t\t\tgoto uaddr_faulted;\n\t\tcase -EAGAIN:\n\t\t\t/*\n\t\t\t * Task is exiting and we just wait for the\n\t\t\t * exit to complete.\n\t\t\t */\n\t\t\tqueue_unlock(&q, hb);\n\t\t\tput_futex_key(fshared, &q.key);\n\t\t\tcond_resched();\n\t\t\tgoto retry;\n\t\tdefault:\n\t\t\tgoto out_unlock_put_key;\n\t\t}\n\t}\n\n\t/*\n\t * Only actually queue now that the atomic ops are done:\n\t */\n\tqueue_me(&q, hb);\n\n\tWARN_ON(!q.pi_state);\n\t/*\n\t * Block on the PI mutex:\n\t */\n\tif (!trylock)\n\t\tret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);\n\telse {\n\t\tret = rt_mutex_trylock(&q.pi_state->pi_mutex);\n\t\t/* Fixup the trylock return value: */\n\t\tret = ret ? 0 : -EWOULDBLOCK;\n\t}\n\n\tspin_lock(q.lock_ptr);\n\t/*\n\t * Fixup the pi_state owner and possibly acquire the lock if we\n\t * haven't already.\n\t */\n\tres = fixup_owner(uaddr, fshared, &q, !ret);\n\t/*\n\t * If fixup_owner() returned an error, proprogate that. If it acquired\n\t * the lock, clear our -ETIMEDOUT or -EINTR.\n\t */\n\tif (res)\n\t\tret = (res < 0) ? res : 0;\n\n\t/*\n\t * If fixup_owner() faulted and was unable to handle the fault, unlock\n\t * it and return the fault to userspace.\n\t */\n\tif (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))\n\t\trt_mutex_unlock(&q.pi_state->pi_mutex);\n\n\t/* Unqueue and drop the lock */\n\tunqueue_me_pi(&q);\n\n\tgoto out;\n\nout_unlock_put_key:\n\tqueue_unlock(&q, hb);\n\nout_put_key:\n\tput_futex_key(fshared, &q.key);\nout:\n\tif (to)\n\t\tdestroy_hrtimer_on_stack(&to->timer);\n\treturn ret != -EINTR ? ret : -ERESTARTNOINTR;\n\nuaddr_faulted:\n\tqueue_unlock(&q, hb);\n\n\tret = fault_in_user_writeable(uaddr);\n\tif (ret)\n\t\tgoto out_put_key;\n\n\tif (!fshared)\n\t\tgoto retry_private;\n\n\tput_futex_key(fshared, &q.key);\n\tgoto retry;\n}", "target": 1, "cwe": [], "project": "linux-2.6", "commit_id": "5ecb01cfdf96c5f465192bdb2a4fd4a61a24c6cc", "hash": 229495631557006192714814605323704821133, "size": 119, "message": "futex_lock_pi() key refcnt fix\n\nThis fixes a futex key reference count bug in futex_lock_pi(),\nwhere a key's reference count is incremented twice but decremented\nonly once, causing the backing object to not be released.\n\nIf the futex is created in a temporary file in an ext3 file system,\nthis bug causes the file's inode to become an \"undead\" orphan,\nwhich causes an oops from a BUG_ON() in ext3_put_super() when the\nfile system is unmounted. glibc's test suite is known to trigger this,\nsee <http://bugzilla.kernel.org/show_bug.cgi?id=14256>.\n\nThe bug is a regression from 2.6.28-git3, namely Peter Zijlstra's\n38d47c1b7075bd7ec3881141bb3629da58f88dab \"[PATCH] futex: rely on\nget_user_pages() for shared futexes\". That commit made get_futex_key()\nalso increment the reference count of the futex key, and updated its\ncallers to decrement the key's reference count before returning.\nUnfortunately the normal exit path in futex_lock_pi() wasn't corrected:\nthe reference count is incremented by get_futex_key() and queue_lock(),\nbut the normal exit path only decrements once, via unqueue_me_pi().\nThe fix is to put_futex_key() after unqueue_me_pi(), since 2.6.31\nthis is easily done by 'goto out_put_key' rather than 'goto out'.\n\nSigned-off-by: Mikael Pettersson <mikpe@it.uu.se>\nAcked-by: Peter Zijlstra <a.p.zijlstra@chello.nl>\nAcked-by: Darren Hart <dvhltc@us.ibm.com>\nSigned-off-by: Thomas Gleixner <tglx@linutronix.de>\nCc: <stable@kernel.org>", "dataset": "other", "idx": 215572}
  1036. {"func": "static int futex_lock_pi(u32 __user *uaddr, int fshared,\n\t\t\t int detect, ktime_t *time, int trylock)\n{\n\tstruct hrtimer_sleeper timeout, *to = NULL;\n\tstruct futex_hash_bucket *hb;\n\tstruct futex_q q;\n\tint res, ret;\n\n\tif (refill_pi_state_cache())\n\t\treturn -ENOMEM;\n\n\tif (time) {\n\t\tto = &timeout;\n\t\thrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,\n\t\t\t\t HRTIMER_MODE_ABS);\n\t\thrtimer_init_sleeper(to, current);\n\t\thrtimer_set_expires(&to->timer, *time);\n\t}\n\n\tq.pi_state = NULL;\n\tq.rt_waiter = NULL;\n\tq.requeue_pi_key = NULL;\nretry:\n\tq.key = FUTEX_KEY_INIT;\n\tret = get_futex_key(uaddr, fshared, &q.key);\n\tif (unlikely(ret != 0))\n\t\tgoto out;\n\nretry_private:\n\thb = queue_lock(&q);\n\n\tret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);\n\tif (unlikely(ret)) {\n\t\tswitch (ret) {\n\t\tcase 1:\n\t\t\t/* We got the lock. */\n\t\t\tret = 0;\n\t\t\tgoto out_unlock_put_key;\n\t\tcase -EFAULT:\n\t\t\tgoto uaddr_faulted;\n\t\tcase -EAGAIN:\n\t\t\t/*\n\t\t\t * Task is exiting and we just wait for the\n\t\t\t * exit to complete.\n\t\t\t */\n\t\t\tqueue_unlock(&q, hb);\n\t\t\tput_futex_key(fshared, &q.key);\n\t\t\tcond_resched();\n\t\t\tgoto retry;\n\t\tdefault:\n\t\t\tgoto out_unlock_put_key;\n\t\t}\n\t}\n\n\t/*\n\t * Only actually queue now that the atomic ops are done:\n\t */\n\tqueue_me(&q, hb);\n\n\tWARN_ON(!q.pi_state);\n\t/*\n\t * Block on the PI mutex:\n\t */\n\tif (!trylock)\n\t\tret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);\n\telse {\n\t\tret = rt_mutex_trylock(&q.pi_state->pi_mutex);\n\t\t/* Fixup the trylock return value: */\n\t\tret = ret ? 0 : -EWOULDBLOCK;\n\t}\n\n\tspin_lock(q.lock_ptr);\n\t/*\n\t * Fixup the pi_state owner and possibly acquire the lock if we\n\t * haven't already.\n\t */\n\tres = fixup_owner(uaddr, fshared, &q, !ret);\n\t/*\n\t * If fixup_owner() returned an error, proprogate that. If it acquired\n\t * the lock, clear our -ETIMEDOUT or -EINTR.\n\t */\n\tif (res)\n\t\tret = (res < 0) ? res : 0;\n\n\t/*\n\t * If fixup_owner() faulted and was unable to handle the fault, unlock\n\t * it and return the fault to userspace.\n\t */\n\tif (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))\n\t\trt_mutex_unlock(&q.pi_state->pi_mutex);\n\n\t/* Unqueue and drop the lock */\n\tunqueue_me_pi(&q);\n\n\tgoto out_put_key;\n\nout_unlock_put_key:\n\tqueue_unlock(&q, hb);\n\nout_put_key:\n\tput_futex_key(fshared, &q.key);\nout:\n\tif (to)\n\t\tdestroy_hrtimer_on_stack(&to->timer);\n\treturn ret != -EINTR ? ret : -ERESTARTNOINTR;\n\nuaddr_faulted:\n\tqueue_unlock(&q, hb);\n\n\tret = fault_in_user_writeable(uaddr);\n\tif (ret)\n\t\tgoto out_put_key;\n\n\tif (!fshared)\n\t\tgoto retry_private;\n\n\tput_futex_key(fshared, &q.key);\n\tgoto retry;\n}", "target": 0, "cwe": [], "project": "linux-2.6", "commit_id": "5ecb01cfdf96c5f465192bdb2a4fd4a61a24c6cc", "hash": 243045543915221577830247168819573698971, "size": 119, "message": "futex_lock_pi() key refcnt fix\n\nThis fixes a futex key reference count bug in futex_lock_pi(),\nwhere a key's reference count is incremented twice but decremented\nonly once, causing the backing object to not be released.\n\nIf the futex is created in a temporary file in an ext3 file system,\nthis bug causes the file's inode to become an \"undead\" orphan,\nwhich causes an oops from a BUG_ON() in ext3_put_super() when the\nfile system is unmounted. glibc's test suite is known to trigger this,\nsee <http://bugzilla.kernel.org/show_bug.cgi?id=14256>.\n\nThe bug is a regression from 2.6.28-git3, namely Peter Zijlstra's\n38d47c1b7075bd7ec3881141bb3629da58f88dab \"[PATCH] futex: rely on\nget_user_pages() for shared futexes\". That commit made get_futex_key()\nalso increment the reference count of the futex key, and updated its\ncallers to decrement the key's reference count before returning.\nUnfortunately the normal exit path in futex_lock_pi() wasn't corrected:\nthe reference count is incremented by get_futex_key() and queue_lock(),\nbut the normal exit path only decrements once, via unqueue_me_pi().\nThe fix is to put_futex_key() after unqueue_me_pi(), since 2.6.31\nthis is easily done by 'goto out_put_key' rather than 'goto out'.\n\nSigned-off-by: Mikael Pettersson <mikpe@it.uu.se>\nAcked-by: Peter Zijlstra <a.p.zijlstra@chello.nl>\nAcked-by: Darren Hart <dvhltc@us.ibm.com>\nSigned-off-by: Thomas Gleixner <tglx@linutronix.de>\nCc: <stable@kernel.org>", "dataset": "other", "idx": 492307}
  1037. {"func": "long keyctl_session_to_parent(void)\n{\n#ifdef TIF_NOTIFY_RESUME\n\tstruct task_struct *me, *parent;\n\tconst struct cred *mycred, *pcred;\n\tstruct cred *cred, *oldcred;\n\tkey_ref_t keyring_r;\n\tint ret;\n\n\tkeyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_LINK);\n\tif (IS_ERR(keyring_r))\n\t\treturn PTR_ERR(keyring_r);\n\n\t/* our parent is going to need a new cred struct, a new tgcred struct\n\t * and new security data, so we allocate them here to prevent ENOMEM in\n\t * our parent */\n\tret = -ENOMEM;\n\tcred = cred_alloc_blank();\n\tif (!cred)\n\t\tgoto error_keyring;\n\n\tcred->tgcred->session_keyring = key_ref_to_ptr(keyring_r);\n\tkeyring_r = NULL;\n\n\tme = current;\n\trcu_read_lock();\n\twrite_lock_irq(&tasklist_lock);\n\n\tparent = me->real_parent;\n\tret = -EPERM;\n\n\t/* the parent mustn't be init and mustn't be a kernel thread */\n\tif (parent->pid <= 1 || !parent->mm)\n\t\tgoto not_permitted;\n\n\t/* the parent must be single threaded */\n\tif (!thread_group_empty(parent))\n\t\tgoto not_permitted;\n\n\t/* the parent and the child must have different session keyrings or\n\t * there's no point */\n\tmycred = current_cred();\n\tpcred = __task_cred(parent);\n\tif (mycred == pcred ||\n\t mycred->tgcred->session_keyring == pcred->tgcred->session_keyring)\n\t\tgoto already_same;\n\n\t/* the parent must have the same effective ownership and mustn't be\n\t * SUID/SGID */\n\tif (pcred->uid\t!= mycred->euid\t||\n\t pcred->euid\t!= mycred->euid\t||\n\t pcred->suid\t!= mycred->euid\t||\n\t pcred->gid\t!= mycred->egid\t||\n\t pcred->egid\t!= mycred->egid\t||\n\t pcred->sgid\t!= mycred->egid)\n\t\tgoto not_permitted;\n\n\t/* the keyrings must have the same UID */\n\tif (pcred->tgcred->session_keyring->uid != mycred->euid ||\n\t mycred->tgcred->session_keyring->uid != mycred->euid)\n\t\tgoto not_permitted;\n\n\t/* if there's an already pending keyring replacement, then we replace\n\t * that */\n\toldcred = parent->replacement_session_keyring;\n\n\t/* the replacement session keyring is applied just prior to userspace\n\t * restarting */\n\tparent->replacement_session_keyring = cred;\n\tcred = NULL;\n\tset_ti_thread_flag(task_thread_info(parent), TIF_NOTIFY_RESUME);\n\n\twrite_unlock_irq(&tasklist_lock);\n\trcu_read_unlock();\n\tif (oldcred)\n\t\tput_cred(oldcred);\n\treturn 0;\n\nalready_same:\n\tret = 0;\nnot_permitted:\n\twrite_unlock_irq(&tasklist_lock);\n\trcu_read_unlock();\n\tput_cred(cred);\n\treturn ret;\n\nerror_keyring:\n\tkey_ref_put(keyring_r);\n\treturn ret;\n\n#else /* !TIF_NOTIFY_RESUME */\n\t/*\n\t * To be removed when TIF_NOTIFY_RESUME has been implemented on\n\t * m68k/xtensa\n\t */\n#warning TIF_NOTIFY_RESUME not implemented\n\treturn -EOPNOTSUPP;\n#endif /* !TIF_NOTIFY_RESUME */\n}", "target": 1, "cwe": ["CWE-476"], "project": "linux-2.6", "commit_id": "3d96406c7da1ed5811ea52a3b0905f4f0e295376", "hash": 32494453156495132678173766772202466555, "size": 99, "message": "KEYS: Fix bug in keyctl_session_to_parent() if parent has no session keyring\n\nFix a bug in keyctl_session_to_parent() whereby it tries to check the ownership\nof the parent process's session keyring whether or not the parent has a session\nkeyring [CVE-2010-2960].\n\nThis results in the following oops:\n\n BUG: unable to handle kernel NULL pointer dereference at 00000000000000a0\n IP: [<ffffffff811ae4dd>] keyctl_session_to_parent+0x251/0x443\n ...\n Call Trace:\n [<ffffffff811ae2f3>] ? keyctl_session_to_parent+0x67/0x443\n [<ffffffff8109d286>] ? __do_fault+0x24b/0x3d0\n [<ffffffff811af98c>] sys_keyctl+0xb4/0xb8\n [<ffffffff81001eab>] system_call_fastpath+0x16/0x1b\n\nif the parent process has no session keyring.\n\nIf the system is using pam_keyinit then it mostly protected against this as all\nprocesses derived from a login will have inherited the session keyring created\nby pam_keyinit during the log in procedure.\n\nTo test this, pam_keyinit calls need to be commented out in /etc/pam.d/.\n\nReported-by: Tavis Ormandy <taviso@cmpxchg8b.com>\nSigned-off-by: David Howells <dhowells@redhat.com>\nAcked-by: Tavis Ormandy <taviso@cmpxchg8b.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "dataset": "other", "idx": 215590}
  1038. {"func": "long keyctl_session_to_parent(void)\n{\n#ifdef TIF_NOTIFY_RESUME\n\tstruct task_struct *me, *parent;\n\tconst struct cred *mycred, *pcred;\n\tstruct cred *cred, *oldcred;\n\tkey_ref_t keyring_r;\n\tint ret;\n\n\tkeyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_LINK);\n\tif (IS_ERR(keyring_r))\n\t\treturn PTR_ERR(keyring_r);\n\n\t/* our parent is going to need a new cred struct, a new tgcred struct\n\t * and new security data, so we allocate them here to prevent ENOMEM in\n\t * our parent */\n\tret = -ENOMEM;\n\tcred = cred_alloc_blank();\n\tif (!cred)\n\t\tgoto error_keyring;\n\n\tcred->tgcred->session_keyring = key_ref_to_ptr(keyring_r);\n\tkeyring_r = NULL;\n\n\tme = current;\n\trcu_read_lock();\n\twrite_lock_irq(&tasklist_lock);\n\n\tparent = me->real_parent;\n\tret = -EPERM;\n\n\t/* the parent mustn't be init and mustn't be a kernel thread */\n\tif (parent->pid <= 1 || !parent->mm)\n\t\tgoto not_permitted;\n\n\t/* the parent must be single threaded */\n\tif (!thread_group_empty(parent))\n\t\tgoto not_permitted;\n\n\t/* the parent and the child must have different session keyrings or\n\t * there's no point */\n\tmycred = current_cred();\n\tpcred = __task_cred(parent);\n\tif (mycred == pcred ||\n\t mycred->tgcred->session_keyring == pcred->tgcred->session_keyring)\n\t\tgoto already_same;\n\n\t/* the parent must have the same effective ownership and mustn't be\n\t * SUID/SGID */\n\tif (pcred->uid\t!= mycred->euid\t||\n\t pcred->euid\t!= mycred->euid\t||\n\t pcred->suid\t!= mycred->euid\t||\n\t pcred->gid\t!= mycred->egid\t||\n\t pcred->egid\t!= mycred->egid\t||\n\t pcred->sgid\t!= mycred->egid)\n\t\tgoto not_permitted;\n\n\t/* the keyrings must have the same UID */\n\tif ((pcred->tgcred->session_keyring &&\n\t pcred->tgcred->session_keyring->uid != mycred->euid) ||\n\t mycred->tgcred->session_keyring->uid != mycred->euid)\n\t\tgoto not_permitted;\n\n\t/* if there's an already pending keyring replacement, then we replace\n\t * that */\n\toldcred = parent->replacement_session_keyring;\n\n\t/* the replacement session keyring is applied just prior to userspace\n\t * restarting */\n\tparent->replacement_session_keyring = cred;\n\tcred = NULL;\n\tset_ti_thread_flag(task_thread_info(parent), TIF_NOTIFY_RESUME);\n\n\twrite_unlock_irq(&tasklist_lock);\n\trcu_read_unlock();\n\tif (oldcred)\n\t\tput_cred(oldcred);\n\treturn 0;\n\nalready_same:\n\tret = 0;\nnot_permitted:\n\twrite_unlock_irq(&tasklist_lock);\n\trcu_read_unlock();\n\tput_cred(cred);\n\treturn ret;\n\nerror_keyring:\n\tkey_ref_put(keyring_r);\n\treturn ret;\n\n#else /* !TIF_NOTIFY_RESUME */\n\t/*\n\t * To be removed when TIF_NOTIFY_RESUME has been implemented on\n\t * m68k/xtensa\n\t */\n#warning TIF_NOTIFY_RESUME not implemented\n\treturn -EOPNOTSUPP;\n#endif /* !TIF_NOTIFY_RESUME */\n}", "target": 0, "cwe": ["CWE-476"], "project": "linux-2.6", "commit_id": "3d96406c7da1ed5811ea52a3b0905f4f0e295376", "hash": 215543301000421930365201907714146972341, "size": 100, "message": "KEYS: Fix bug in keyctl_session_to_parent() if parent has no session keyring\n\nFix a bug in keyctl_session_to_parent() whereby it tries to check the ownership\nof the parent process's session keyring whether or not the parent has a session\nkeyring [CVE-2010-2960].\n\nThis results in the following oops:\n\n BUG: unable to handle kernel NULL pointer dereference at 00000000000000a0\n IP: [<ffffffff811ae4dd>] keyctl_session_to_parent+0x251/0x443\n ...\n Call Trace:\n [<ffffffff811ae2f3>] ? keyctl_session_to_parent+0x67/0x443\n [<ffffffff8109d286>] ? __do_fault+0x24b/0x3d0\n [<ffffffff811af98c>] sys_keyctl+0xb4/0xb8\n [<ffffffff81001eab>] system_call_fastpath+0x16/0x1b\n\nif the parent process has no session keyring.\n\nIf the system is using pam_keyinit then it mostly protected against this as all\nprocesses derived from a login will have inherited the session keyring created\nby pam_keyinit during the log in procedure.\n\nTo test this, pam_keyinit calls need to be commented out in /etc/pam.d/.\n\nReported-by: Tavis Ormandy <taviso@cmpxchg8b.com>\nSigned-off-by: David Howells <dhowells@redhat.com>\nAcked-by: Tavis Ormandy <taviso@cmpxchg8b.com>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "dataset": "other", "idx": 492806}
  1039. {"func": "grep (int fd, char const *file, struct stats *stats)\n{\n int nlines, i;\n int not_text;\n size_t residue, save;\n char oldc;\n char *beg;\n char *lim;\n char eol = eolbyte;\n\n if (!reset (fd, file, stats))\n return 0;\n\n if (file && directories == RECURSE_DIRECTORIES\n && S_ISDIR (stats->stat.st_mode))\n {\n /* Close fd now, so that we don't open a lot of file descriptors\n when we recurse deeply. */\n if (close (fd) != 0)\n suppressible_error (file, errno);\n return grepdir (file, stats) - 2;\n }\n\n totalcc = 0;\n lastout = 0;\n totalnl = 0;\n outleft = max_count;\n after_last_match = 0;\n pending = 0;\n\n nlines = 0;\n residue = 0;\n save = 0;\n\n if (! fillbuf (save, stats))\n {\n suppressible_error (filename, errno);\n return 0;\n }\n\n not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)\n || binary_files == WITHOUT_MATCH_BINARY_FILES)\n && memchr (bufbeg, eol ? '\\0' : '\\200', buflim - bufbeg));\n if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)\n return 0;\n done_on_match += not_text;\n out_quiet += not_text;\n\n for (;;)\n {\n lastnl = bufbeg;\n if (lastout)\n lastout = bufbeg;\n\n beg = bufbeg + save;\n\n /* no more data to scan (eof) except for maybe a residue -> break */\n if (beg == buflim)\n break;\n\n /* Determine new residue (the length of an incomplete line at the end of\n the buffer, 0 means there is no incomplete last line). */\n oldc = beg[-1];\n beg[-1] = eol;\n for (lim = buflim; lim[-1] != eol; lim--)\n continue;\n beg[-1] = oldc;\n if (lim == beg)\n lim = beg - residue;\n beg -= residue;\n residue = buflim - lim;\n\n if (beg < lim)\n {\n if (outleft)\n nlines += grepbuf (beg, lim);\n if (pending)\n prpending (lim);\n if ((!outleft && !pending) || (nlines && done_on_match && !out_invert))\n goto finish_grep;\n }\n\n /* The last OUT_BEFORE lines at the end of the buffer will be needed as\n leading context if there is a matching line at the begin of the\n next data. Make beg point to their begin. */\n i = 0;\n beg = lim;\n while (i < out_before && beg > bufbeg && beg != lastout)\n {\n ++i;\n do\n --beg;\n while (beg[-1] != eol);\n }\n\n /* detect if leading context is discontinuous from last printed line. */\n if (beg != lastout)\n lastout = 0;\n\n /* Handle some details and read more data to scan. */\n save = residue + lim - beg;\n if (out_byte)\n totalcc = add_count (totalcc, buflim - bufbeg - save);\n if (out_line)\n nlscan (beg);\n if (! fillbuf (save, stats))\n {\n suppressible_error (filename, errno);\n goto finish_grep;\n }\n }\n if (residue)\n {\n *buflim++ = eol;\n if (outleft)\n nlines += grepbuf (bufbeg + save - residue, buflim);\n if (pending)\n prpending (buflim);\n }\n\n finish_grep:\n done_on_match -= not_text;\n out_quiet -= not_text;\n if ((not_text & ~out_quiet) && nlines != 0)\n printf (_(\"Binary file %s matches\\n\"), filename);\n return nlines;\n}", "target": 1, "cwe": ["CWE-189"], "project": "grep", "commit_id": "8fcf61523644df42e1905c81bed26838e0b04f91", "hash": 127493158851729294951078837033344135674, "size": 127, "message": "grep: fix integer-overflow issues in main program\n\n* NEWS: Document this.\n* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.\nRemove xstrtoumax.\n* src/main.c: Include <inttypes.h>, for INTMAX_MAX, PRIdMAX.\n(context_length_arg, prtext, grepbuf, grep, grepfile)\n(get_nondigit_option, main):\nUse intmax_t, not int, for line counts.\n(context_length_arg, main): Silently ceiling line counts\nto maximum value, since there's no practical difference between\ndoing that and using infinite-precision arithmetic.\n(out_before, out_after, pending): Now intmax_t, not int.\n(max_count, outleft): Now intmax_t, not off_t.\n(prepend_args, prepend_default_options, main):\nUse size_t, not int, for sizes.\n(prepend_default_options): Check for int and size_t overflow.", "dataset": "other", "idx": 215830}
  1040. {"func": "grep (int fd, char const *file, struct stats *stats)\n{\n intmax_t nlines, i;\n int not_text;\n size_t residue, save;\n char oldc;\n char *beg;\n char *lim;\n char eol = eolbyte;\n\n if (!reset (fd, file, stats))\n return 0;\n\n if (file && directories == RECURSE_DIRECTORIES\n && S_ISDIR (stats->stat.st_mode))\n {\n /* Close fd now, so that we don't open a lot of file descriptors\n when we recurse deeply. */\n if (close (fd) != 0)\n suppressible_error (file, errno);\n return grepdir (file, stats) - 2;\n }\n\n totalcc = 0;\n lastout = 0;\n totalnl = 0;\n outleft = max_count;\n after_last_match = 0;\n pending = 0;\n\n nlines = 0;\n residue = 0;\n save = 0;\n\n if (! fillbuf (save, stats))\n {\n suppressible_error (filename, errno);\n return 0;\n }\n\n not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)\n || binary_files == WITHOUT_MATCH_BINARY_FILES)\n && memchr (bufbeg, eol ? '\\0' : '\\200', buflim - bufbeg));\n if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)\n return 0;\n done_on_match += not_text;\n out_quiet += not_text;\n\n for (;;)\n {\n lastnl = bufbeg;\n if (lastout)\n lastout = bufbeg;\n\n beg = bufbeg + save;\n\n /* no more data to scan (eof) except for maybe a residue -> break */\n if (beg == buflim)\n break;\n\n /* Determine new residue (the length of an incomplete line at the end of\n the buffer, 0 means there is no incomplete last line). */\n oldc = beg[-1];\n beg[-1] = eol;\n for (lim = buflim; lim[-1] != eol; lim--)\n continue;\n beg[-1] = oldc;\n if (lim == beg)\n lim = beg - residue;\n beg -= residue;\n residue = buflim - lim;\n\n if (beg < lim)\n {\n if (outleft)\n nlines += grepbuf (beg, lim);\n if (pending)\n prpending (lim);\n if ((!outleft && !pending) || (nlines && done_on_match && !out_invert))\n goto finish_grep;\n }\n\n /* The last OUT_BEFORE lines at the end of the buffer will be needed as\n leading context if there is a matching line at the begin of the\n next data. Make beg point to their begin. */\n i = 0;\n beg = lim;\n while (i < out_before && beg > bufbeg && beg != lastout)\n {\n ++i;\n do\n --beg;\n while (beg[-1] != eol);\n }\n\n /* detect if leading context is discontinuous from last printed line. */\n if (beg != lastout)\n lastout = 0;\n\n /* Handle some details and read more data to scan. */\n save = residue + lim - beg;\n if (out_byte)\n totalcc = add_count (totalcc, buflim - bufbeg - save);\n if (out_line)\n nlscan (beg);\n if (! fillbuf (save, stats))\n {\n suppressible_error (filename, errno);\n goto finish_grep;\n }\n }\n if (residue)\n {\n *buflim++ = eol;\n if (outleft)\n nlines += grepbuf (bufbeg + save - residue, buflim);\n if (pending)\n prpending (buflim);\n }\n\n finish_grep:\n done_on_match -= not_text;\n out_quiet -= not_text;\n if ((not_text & ~out_quiet) && nlines != 0)\n printf (_(\"Binary file %s matches\\n\"), filename);\n return nlines;\n}", "target": 0, "cwe": ["CWE-189"], "project": "grep", "commit_id": "8fcf61523644df42e1905c81bed26838e0b04f91", "hash": 271423593932472745351308763697044508813, "size": 127, "message": "grep: fix integer-overflow issues in main program\n\n* NEWS: Document this.\n* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.\nRemove xstrtoumax.\n* src/main.c: Include <inttypes.h>, for INTMAX_MAX, PRIdMAX.\n(context_length_arg, prtext, grepbuf, grep, grepfile)\n(get_nondigit_option, main):\nUse intmax_t, not int, for line counts.\n(context_length_arg, main): Silently ceiling line counts\nto maximum value, since there's no practical difference between\ndoing that and using infinite-precision arithmetic.\n(out_before, out_after, pending): Now intmax_t, not int.\n(max_count, outleft): Now intmax_t, not off_t.\n(prepend_args, prepend_default_options, main):\nUse size_t, not int, for sizes.\n(prepend_default_options): Check for int and size_t overflow.", "dataset": "other", "idx": 496454}
  1041. {"func": "translate_hierarchy_event (ClutterBackendX11 *backend_x11,\n ClutterDeviceManagerXI2 *manager_xi2,\n XIHierarchyEvent *ev)\n{\n int i;\n\n for (i = 0; i < ev->num_info; i++)\n {\n if (ev->info[i].flags & XIDeviceEnabled)\n {\n XIDeviceInfo *info;\n int n_devices;\n\n CLUTTER_NOTE (EVENT, \"Hierarchy event: device enabled\");\n\n info = XIQueryDevice (backend_x11->xdpy,\n ev->info[i].deviceid,\n &n_devices);\n add_device (manager_xi2, backend_x11, &info[0], FALSE);\n }\n else if (ev->info[i].flags & XIDeviceDisabled)\n {\n CLUTTER_NOTE (EVENT, \"Hierarchy event: device disabled\");\n\n remove_device (manager_xi2, ev->info[i].deviceid);\n }\n else if ((ev->info[i].flags & XISlaveAttached) ||\n (ev->info[i].flags & XISlaveDetached))\n {\n ClutterInputDevice *master, *slave;\n XIDeviceInfo *info;\n int n_devices;\n gboolean send_changed = FALSE;\n\n CLUTTER_NOTE (EVENT, \"Hierarchy event: slave %s\",\n (ev->info[i].flags & XISlaveAttached)\n ? \"attached\"\n : \"detached\");\n\n slave = g_hash_table_lookup (manager_xi2->devices_by_id,\n GINT_TO_POINTER (ev->info[i].deviceid));\n master = clutter_input_device_get_associated_device (slave);\n\n /* detach the slave in both cases */\n if (master != NULL)\n {\n _clutter_input_device_remove_slave (master, slave);\n _clutter_input_device_set_associated_device (slave, NULL);\n\n send_changed = TRUE;\n }\n\n /* and attach the slave to the new master if needed */\n if (ev->info[i].flags & XISlaveAttached)\n {\n info = XIQueryDevice (backend_x11->xdpy,\n ev->info[i].deviceid,\n &n_devices);\n master = g_hash_table_lookup (manager_xi2->devices_by_id,\n GINT_TO_POINTER (info->attachment));\n _clutter_input_device_set_associated_device (slave, master);\n _clutter_input_device_add_slave (master, slave);\n\n send_changed = TRUE;\n XIFreeDeviceInfo (info);\n }\n\n if (send_changed)\n {\n ClutterStage *stage = _clutter_input_device_get_stage (master);\n if (stage != NULL)\n _clutter_stage_x11_events_device_changed (CLUTTER_STAGE_X11 (_clutter_stage_get_window (stage)), \n master,\n CLUTTER_DEVICE_MANAGER (manager_xi2));\n }\n }\n }\n}", "target": 1, "cwe": ["CWE-264"], "project": "clutter", "commit_id": "e310c68d7b38d521e341f4e8a36f54303079d74e", "hash": 20403663631467032878668258860120289189, "size": 78, "message": "x11: trap errors when calling XIQueryDevice\n\nDevices can disappear at any time, causing XIQueryDevice\nto throw an error. At the same time, plug a memory leak.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=701974", "dataset": "other", "idx": 215902}
  1042. {"func": "translate_hierarchy_event (ClutterBackendX11 *backend_x11,\n ClutterDeviceManagerXI2 *manager_xi2,\n XIHierarchyEvent *ev)\n{\n int i;\n\n for (i = 0; i < ev->num_info; i++)\n {\n if (ev->info[i].flags & XIDeviceEnabled)\n {\n XIDeviceInfo *info;\n int n_devices;\n\n CLUTTER_NOTE (EVENT, \"Hierarchy event: device enabled\");\n\n clutter_x11_trap_x_errors ();\n info = XIQueryDevice (backend_x11->xdpy,\n ev->info[i].deviceid,\n &n_devices);\n clutter_x11_untrap_x_errors ();\n if (info != NULL)\n {\n add_device (manager_xi2, backend_x11, &info[0], FALSE);\n XIFreeDeviceInfo (info);\n }\n }\n else if (ev->info[i].flags & XIDeviceDisabled)\n {\n CLUTTER_NOTE (EVENT, \"Hierarchy event: device disabled\");\n\n remove_device (manager_xi2, ev->info[i].deviceid);\n }\n else if ((ev->info[i].flags & XISlaveAttached) ||\n (ev->info[i].flags & XISlaveDetached))\n {\n ClutterInputDevice *master, *slave;\n XIDeviceInfo *info;\n int n_devices;\n gboolean send_changed = FALSE;\n\n CLUTTER_NOTE (EVENT, \"Hierarchy event: slave %s\",\n (ev->info[i].flags & XISlaveAttached)\n ? \"attached\"\n : \"detached\");\n\n slave = g_hash_table_lookup (manager_xi2->devices_by_id,\n GINT_TO_POINTER (ev->info[i].deviceid));\n master = clutter_input_device_get_associated_device (slave);\n\n /* detach the slave in both cases */\n if (master != NULL)\n {\n _clutter_input_device_remove_slave (master, slave);\n _clutter_input_device_set_associated_device (slave, NULL);\n\n send_changed = TRUE;\n }\n\n /* and attach the slave to the new master if needed */\n if (ev->info[i].flags & XISlaveAttached)\n {\n clutter_x11_trap_x_errors ();\n info = XIQueryDevice (backend_x11->xdpy,\n ev->info[i].deviceid,\n &n_devices);\n clutter_x11_untrap_x_errors ();\n if (info != NULL)\n {\n master = g_hash_table_lookup (manager_xi2->devices_by_id,\n GINT_TO_POINTER (info->attachment));\n if (master != NULL)\n {\n _clutter_input_device_set_associated_device (slave, master);\n _clutter_input_device_add_slave (master, slave);\n\n send_changed = TRUE;\n }\n XIFreeDeviceInfo (info);\n }\n }\n\n if (send_changed)\n {\n ClutterStage *stage = _clutter_input_device_get_stage (master);\n if (stage != NULL)\n _clutter_stage_x11_events_device_changed (CLUTTER_STAGE_X11 (_clutter_stage_get_window (stage)), \n master,\n CLUTTER_DEVICE_MANAGER (manager_xi2));\n }\n }\n }\n}", "target": 0, "cwe": ["CWE-264"], "project": "clutter", "commit_id": "e310c68d7b38d521e341f4e8a36f54303079d74e", "hash": 270833825451384971935526577161445293974, "size": 92, "message": "x11: trap errors when calling XIQueryDevice\n\nDevices can disappear at any time, causing XIQueryDevice\nto throw an error. At the same time, plug a memory leak.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=701974", "dataset": "other", "idx": 497483}
  1043. {"func": "ms_escher_get_data (MSEscherState *state,\n\t\t gint offset,\t/* bytes from logical start of the stream */\n\t\t gint num_bytes,\t/*how many bytes we want, NOT incl prefix */\n\t\t gboolean * needs_free)\n{\n\tBiffQuery *q = state->q;\n\tguint8 *res;\n\n\tg_return_val_if_fail (offset >= state->start_offset, NULL);\n\n\t/* find the 1st containing record */\n\twhile (offset >= state->end_offset) {\n\t\tif (!ms_biff_query_next (q)) {\n\t\t\tg_warning (\"unexpected end of stream;\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (q->opcode != BIFF_MS_O_DRAWING &&\n\t\t q->opcode != BIFF_MS_O_DRAWING_GROUP &&\n\t\t q->opcode != BIFF_MS_O_DRAWING_SELECTION &&\n\t\t q->opcode != BIFF_CHART_gelframe &&\n\t\t q->opcode != BIFF_CONTINUE) {\n\t\t g_warning (\"Unexpected record type 0x%x len=0x%x @ 0x%lx;\", q->opcode, q->length, (long)q->streamPos);\n\t\t\treturn NULL;\n\t\t}\n\n\t\td (1, g_printerr (\"Target is 0x%x bytes at 0x%x, current = 0x%x..0x%x;\\n\"\n\t\t\t \"Adding biff-0x%x of length 0x%x;\\n\",\n\t\t\t num_bytes, offset,\n\t\t\t state->start_offset,\n\t\t\t state->end_offset,\n\t\t\t q->opcode, q->length););\n\n\t\tstate->start_offset = state->end_offset;\n\t\tstate->end_offset += q->length;\n\t\tstate->segment_len = q->length;\n\t}\n\n\tg_return_val_if_fail (offset >= state->start_offset, NULL);\n\tg_return_val_if_fail ((size_t)(offset - state->start_offset) < q->length, NULL);\n\n\tres = q->data + offset - state->start_offset;\n\tif ((*needs_free = ((offset + num_bytes) > state->end_offset))) {\n\t\tguint8 *buffer = g_malloc (num_bytes);\n\t\tguint8 *tmp = buffer;\n\n\t\t/* Setup front stub */\n\t\tint len = q->length - (res - q->data);\n\t\tint counter = 0;\n\n\t\td (1, g_printerr (\"MERGE needed (%d) which is >= %d + %d;\\n\",\n\t\t\t num_bytes, offset, state->end_offset););\n\n\t\tdo {\n\t\t\td (1, g_printerr (\"record %d) add %d bytes;\\n\", ++counter, len););\n\t\t\t/* copy necessary portion of current record */\n\t\t\tmemcpy (tmp, res, len);\n\t\t\ttmp += len;\n\n\t\t\t/* Get next record */\n\t\t\tif (!ms_biff_query_next (q)) {\n\t\t\t\tg_warning (\"unexpected end of stream;\");\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\t/* We should only see DRAW records now */\n\t\t\tif (q->opcode != BIFF_MS_O_DRAWING &&\n\t\t\t q->opcode != BIFF_MS_O_DRAWING_GROUP &&\n\t\t\t q->opcode != BIFF_MS_O_DRAWING_SELECTION &&\n\t\t\t q->opcode != BIFF_CHART_gelframe &&\n\t\t\t q->opcode != BIFF_CONTINUE) {\n\t\t\t g_warning (\"Unexpected record type 0x%x @ 0x%lx;\", q->opcode, (long)q->streamPos);\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\tstate->start_offset = state->end_offset;\n\t\t\tstate->end_offset += q->length;\n\t\t\tstate->segment_len = q->length;\n\n\t\t\tres = q->data;\n\t\t\tlen = q->length;\n\n\t\t} while ((num_bytes - (tmp - buffer)) > len);\n\n\t\t/* Copy back stub */\n\t\tmemcpy (tmp, res, num_bytes - (tmp-buffer));\n\t\td (1, g_printerr (\"record %d) add %d bytes;\\n\",\n\t\t\t ++counter,\n\t\t\t num_bytes - (int)(tmp-buffer)););\n\t\treturn buffer;\n\t}\n\n\treturn res;\n}", "target": 1, "cwe": ["CWE-119"], "project": "gnumeric", "commit_id": "b5480b69345b3c6d56ee0ed9c9e9880bb2a08cdc", "hash": 257840832045771375406916626167501889085, "size": 94, "message": "xls: fuzzed file crash.", "dataset": "other", "idx": 215903}
  1044. {"func": "ms_escher_get_data (MSEscherState *state,\n\t\t gint offset,\t/* bytes from logical start of the stream */\n\t\t gint num_bytes,\t/*how many bytes we want, NOT incl prefix */\n\t\t gboolean * needs_free)\n{\n\tBiffQuery *q = state->q;\n\tguint8 *res;\n\n\tg_return_val_if_fail (offset >= state->start_offset, NULL);\n\n\t/* find the 1st containing record */\n\twhile (offset >= state->end_offset) {\n\t\tif (!ms_biff_query_next (q)) {\n\t\t\tg_warning (\"unexpected end of stream;\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (q->opcode != BIFF_MS_O_DRAWING &&\n\t\t q->opcode != BIFF_MS_O_DRAWING_GROUP &&\n\t\t q->opcode != BIFF_MS_O_DRAWING_SELECTION &&\n\t\t q->opcode != BIFF_CHART_gelframe &&\n\t\t q->opcode != BIFF_CONTINUE) {\n\t\t g_warning (\"Unexpected record type 0x%x len=0x%x @ 0x%lx;\", q->opcode, q->length, (long)q->streamPos);\n\t\t\treturn NULL;\n\t\t}\n\n\t\td (1, g_printerr (\"Target is 0x%x bytes at 0x%x, current = 0x%x..0x%x;\\n\"\n\t\t\t \"Adding biff-0x%x of length 0x%x;\\n\",\n\t\t\t num_bytes, offset,\n\t\t\t state->start_offset,\n\t\t\t state->end_offset,\n\t\t\t q->opcode, q->length););\n\n\t\tstate->start_offset = state->end_offset;\n\t\tstate->end_offset += q->length;\n\t\tstate->segment_len = q->length;\n\t}\n\n\tg_return_val_if_fail (offset >= state->start_offset, NULL);\n\tg_return_val_if_fail ((size_t)(offset - state->start_offset) < q->length, NULL);\n\n\tres = q->data + offset - state->start_offset;\n\tif ((*needs_free = ((offset + num_bytes) > state->end_offset))) {\n\t\tguint8 *buffer = g_malloc (num_bytes);\n\t\tguint8 *tmp = buffer;\n\n\t\t/* Setup front stub */\n\t\tint len = q->length - (res - q->data);\n\t\tint counter = 0;\n\n\t\td (1, g_printerr (\"MERGE needed (%d) which is >= -%d + %d;\\n\",\n\t\t\t num_bytes, offset, state->end_offset););\n\n\t\tdo {\n\t\t\tint maxlen = (buffer + num_bytes) - tmp;\n\t\t\tlen = MIN (len, maxlen);\n\t\t\td (1, g_printerr (\"record %d) add %d bytes;\\n\", ++counter, len););\n\n\t\t\t/* copy necessary portion of current record */\n\t\t\tmemcpy (tmp, res, len);\n\t\t\ttmp += len;\n\n\t\t\t/* Get next record */\n\t\t\tif (!ms_biff_query_next (q)) {\n\t\t\t\tg_warning (\"unexpected end of stream;\");\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\t/* We should only see DRAW records now */\n\t\t\tif (q->opcode != BIFF_MS_O_DRAWING &&\n\t\t\t q->opcode != BIFF_MS_O_DRAWING_GROUP &&\n\t\t\t q->opcode != BIFF_MS_O_DRAWING_SELECTION &&\n\t\t\t q->opcode != BIFF_CHART_gelframe &&\n\t\t\t q->opcode != BIFF_CONTINUE) {\n\t\t\t\tg_warning (\"Unexpected record type 0x%x @ 0x%lx;\", q->opcode, (long)q->streamPos);\n\t\t\t\tg_free (buffer);\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\tstate->start_offset = state->end_offset;\n\t\t\tstate->end_offset += q->length;\n\t\t\tstate->segment_len = q->length;\n\n\t\t\tres = q->data;\n\t\t\tlen = q->length;\n\n\t\t} while ((num_bytes - (tmp - buffer)) > len);\n\n\t\t/* Copy back stub */\n\t\tmemcpy (tmp, res, num_bytes - (tmp-buffer));\n\t\td (1, g_printerr (\"record %d) add %d bytes;\\n\",\n\t\t\t ++counter,\n\t\t\t num_bytes - (int)(tmp-buffer)););\n\t\treturn buffer;\n\t}\n\n\treturn res;\n}", "target": 0, "cwe": ["CWE-119"], "project": "gnumeric", "commit_id": "b5480b69345b3c6d56ee0ed9c9e9880bb2a08cdc", "hash": 70824620653332871173225127729054253170, "size": 98, "message": "xls: fuzzed file crash.", "dataset": "other", "idx": 497531}
  1045. {"func": "int ssh_bind_accept_fd(ssh_bind sshbind, ssh_session session, socket_t fd){\n int i, rc;\n\n if (session == NULL){\n ssh_set_error(sshbind, SSH_FATAL,\"session is null\");\n return SSH_ERROR;\n }\n\n session->server = 1;\n session->version = 2;\n\n /* copy options */\n for (i = 0; i < 10; ++i) {\n if (sshbind->wanted_methods[i]) {\n session->opts.wanted_methods[i] = strdup(sshbind->wanted_methods[i]);\n if (session->opts.wanted_methods[i] == NULL) {\n return SSH_ERROR;\n }\n }\n }\n\n if (sshbind->bindaddr == NULL)\n session->opts.bindaddr = NULL;\n else {\n SAFE_FREE(session->opts.bindaddr);\n session->opts.bindaddr = strdup(sshbind->bindaddr);\n if (session->opts.bindaddr == NULL) {\n return SSH_ERROR;\n }\n }\n\n session->common.log_verbosity = sshbind->common.log_verbosity;\n if(sshbind->banner != NULL)\n \tsession->opts.custombanner = strdup(sshbind->banner);\n ssh_socket_free(session->socket);\n session->socket = ssh_socket_new(session);\n if (session->socket == NULL) {\n /* perhaps it may be better to copy the error from session to sshbind */\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n ssh_socket_set_fd(session->socket, fd);\n ssh_socket_get_poll_handle_out(session->socket);\n\n /* We must try to import any keys that could be imported in case\n * we are not using ssh_bind_listen (which is the other place\n * where keys can be imported) on this ssh_bind and are instead\n * only using ssh_bind_accept_fd to manage sockets ourselves.\n */\n rc = ssh_bind_import_keys(sshbind);\n if (rc != SSH_OK) {\n return SSH_ERROR;\n }\n\n#ifdef HAVE_ECC\n if (sshbind->ecdsa) {\n session->srv.ecdsa_key = ssh_key_dup(sshbind->ecdsa);\n if (session->srv.ecdsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n#endif\n if (sshbind->dsa) {\n session->srv.dsa_key = ssh_key_dup(sshbind->dsa);\n if (session->srv.dsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n if (sshbind->rsa) {\n session->srv.rsa_key = ssh_key_dup(sshbind->rsa);\n if (session->srv.rsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n return SSH_OK;\n}", "target": 1, "cwe": ["CWE-310"], "project": "libssh", "commit_id": "e99246246b4061f7e71463f8806b9dcad65affa0", "hash": 155342663606614956692829213292082664878, "size": 79, "message": "security: fix for vulnerability CVE-2014-0017\n\nWhen accepting a new connection, a forking server based on libssh forks\nand the child process handles the request. The RAND_bytes() function of\nopenssl doesn't reset its state after the fork, but simply adds the\ncurrent process id (getpid) to the PRNG state, which is not guaranteed\nto be unique.\nThis can cause several children to end up with same PRNG state which is\na security issue.", "dataset": "other", "idx": 215904}
  1046. {"func": "int ssh_bind_accept_fd(ssh_bind sshbind, ssh_session session, socket_t fd){\n int i, rc;\n\n if (session == NULL){\n ssh_set_error(sshbind, SSH_FATAL,\"session is null\");\n return SSH_ERROR;\n }\n\n session->server = 1;\n session->version = 2;\n\n /* copy options */\n for (i = 0; i < 10; ++i) {\n if (sshbind->wanted_methods[i]) {\n session->opts.wanted_methods[i] = strdup(sshbind->wanted_methods[i]);\n if (session->opts.wanted_methods[i] == NULL) {\n return SSH_ERROR;\n }\n }\n }\n\n if (sshbind->bindaddr == NULL)\n session->opts.bindaddr = NULL;\n else {\n SAFE_FREE(session->opts.bindaddr);\n session->opts.bindaddr = strdup(sshbind->bindaddr);\n if (session->opts.bindaddr == NULL) {\n return SSH_ERROR;\n }\n }\n\n session->common.log_verbosity = sshbind->common.log_verbosity;\n if(sshbind->banner != NULL)\n \tsession->opts.custombanner = strdup(sshbind->banner);\n ssh_socket_free(session->socket);\n session->socket = ssh_socket_new(session);\n if (session->socket == NULL) {\n /* perhaps it may be better to copy the error from session to sshbind */\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n ssh_socket_set_fd(session->socket, fd);\n ssh_socket_get_poll_handle_out(session->socket);\n\n /* We must try to import any keys that could be imported in case\n * we are not using ssh_bind_listen (which is the other place\n * where keys can be imported) on this ssh_bind and are instead\n * only using ssh_bind_accept_fd to manage sockets ourselves.\n */\n rc = ssh_bind_import_keys(sshbind);\n if (rc != SSH_OK) {\n return SSH_ERROR;\n }\n\n#ifdef HAVE_ECC\n if (sshbind->ecdsa) {\n session->srv.ecdsa_key = ssh_key_dup(sshbind->ecdsa);\n if (session->srv.ecdsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n#endif\n if (sshbind->dsa) {\n session->srv.dsa_key = ssh_key_dup(sshbind->dsa);\n if (session->srv.dsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n if (sshbind->rsa) {\n session->srv.rsa_key = ssh_key_dup(sshbind->rsa);\n if (session->srv.rsa_key == NULL) {\n ssh_set_error_oom(sshbind);\n return SSH_ERROR;\n }\n }\n /* force PRNG to change state in case we fork after ssh_bind_accept */\n ssh_reseed();\n return SSH_OK;\n}", "target": 0, "cwe": ["CWE-310"], "project": "libssh", "commit_id": "e99246246b4061f7e71463f8806b9dcad65affa0", "hash": 50685877395540749769671536212771341726, "size": 81, "message": "security: fix for vulnerability CVE-2014-0017\n\nWhen accepting a new connection, a forking server based on libssh forks\nand the child process handles the request. The RAND_bytes() function of\nopenssl doesn't reset its state after the fork, but simply adds the\ncurrent process id (getpid) to the PRNG state, which is not guaranteed\nto be unique.\nThis can cause several children to end up with same PRNG state which is\na security issue.", "dataset": "other", "idx": 497609}
  1047. {"func": "url_file_name (const struct url *u, char *replaced_filename)\n{\n struct growable fnres; /* stands for \"file name result\" */\n struct growable temp_fnres;\n\n const char *u_file;\n char *fname, *unique, *fname_len_check;\n const char *index_filename = \"index.html\"; /* The default index file is index.html */\n size_t max_length;\n\n fnres.base = NULL;\n fnres.size = 0;\n fnres.tail = 0;\n\n temp_fnres.base = NULL;\n temp_fnres.size = 0;\n temp_fnres.tail = 0;\n\n /* If an alternative index file was defined, change index_filename */\n if (opt.default_page)\n index_filename = opt.default_page;\n\n\n /* Start with the directory prefix, if specified. */\n if (opt.dir_prefix)\n append_string (opt.dir_prefix, &fnres);\n\n /* If \"dirstruct\" is turned on (typically the case with -r), add\n the host and port (unless those have been turned off) and\n directory structure. */\n if (opt.dirstruct)\n {\n if (opt.protocol_directories)\n {\n if (fnres.tail)\n append_char ('/', &fnres);\n append_string (supported_schemes[u->scheme].name, &fnres);\n }\n if (opt.add_hostdir)\n {\n if (fnres.tail)\n append_char ('/', &fnres);\n if (0 != strcmp (u->host, \"..\"))\n append_string (u->host, &fnres);\n else\n /* Host name can come from the network; malicious DNS may\n allow \"..\" to be resolved, causing us to write to\n \"../<file>\". Defang such host names. */\n append_string (\"%2E%2E\", &fnres);\n if (u->port != scheme_default_port (u->scheme))\n {\n char portstr[24];\n number_to_string (portstr, u->port);\n append_char (FN_PORT_SEP, &fnres);\n append_string (portstr, &fnres);\n }\n }\n\n append_dir_structure (u, &fnres);\n }\n\n if (!replaced_filename)\n {\n /* Create the filename. */\n u_file = *u->file ? u->file : index_filename;\n\n /* Append \"?query\" to the file name, even if empty,\n * and create fname_len_check. */\n if (u->query)\n fname_len_check = concat_strings (u_file, FN_QUERY_SEP_STR, u->query, NULL);\n else\n fname_len_check = strdupdelim (u_file, u_file + strlen (u_file));\n }\n else\n {\n u_file = replaced_filename;\n fname_len_check = strdupdelim (u_file, u_file + strlen (u_file));\n }\n\n append_uri_pathel (fname_len_check,\n fname_len_check + strlen (fname_len_check), false, &temp_fnres);\n\n /* Zero-terminate the temporary file name. */\n append_char ('\\0', &temp_fnres);\n\n /* Check that the length of the file name is acceptable. */\n#ifdef WINDOWS\n if (MAX_PATH > (fnres.tail + CHOMP_BUFFER + 2))\n {\n max_length = MAX_PATH - (fnres.tail + CHOMP_BUFFER + 2);\n /* FIXME: In Windows a filename is usually limited to 255 characters.\n To really be accurate you could call GetVolumeInformation() to get\n lpMaximumComponentLength\n */\n if (max_length > 255)\n {\n max_length = 255;\n }\n }\n else\n {\n max_length = 0;\n }\n#else\n max_length = get_max_length (fnres.base, fnres.tail, _PC_NAME_MAX) - CHOMP_BUFFER;\n#endif\n if (max_length > 0 && strlen (temp_fnres.base) > max_length)\n {\n logprintf (LOG_NOTQUIET, \"The name is too long, %lu chars total.\\n\",\n (unsigned long) strlen (temp_fnres.base));\n logprintf (LOG_NOTQUIET, \"Trying to shorten...\\n\");\n\n /* Shorten the file name. */\n temp_fnres.base[max_length] = '\\0';\n\n logprintf (LOG_NOTQUIET, \"New name is %s.\\n\", temp_fnres.base);\n }\n\n xfree (fname_len_check);\n\n /* The filename has already been 'cleaned' by append_uri_pathel() above. So,\n * just append it. */\n if (fnres.tail)\n append_char ('/', &fnres);\n append_string (temp_fnres.base, &fnres);\n\n fname = fnres.base;\n\n /* Make a final check that the path length is acceptable? */\n /* TODO: check fnres.base for path length problem */\n\n xfree (temp_fnres.base);\n\n /* Check the cases in which the unique extensions are not used:\n 1) Clobbering is turned off (-nc).\n 2) Retrieval with regetting.\n 3) Timestamping is used.\n 4) Hierarchy is built.\n 5) Backups are specified.\n\n The exception is the case when file does exist and is a\n directory (see `mkalldirs' for explanation). */\n\n if (ALLOW_CLOBBER\n && !(file_exists_p (fname) && !file_non_directory_p (fname)))\n {\n unique = fname;\n }\n else\n {\n unique = unique_name (fname, true);\n if (unique != fname)\n xfree (fname);\n }\n\n/* On VMS, alter the name as required. */\n#ifdef __VMS\n {\n char *unique2;\n\n unique2 = ods_conform( unique);\n if (unique2 != unique)\n {\n xfree (unique);\n unique = unique2;\n }\n }\n#endif /* def __VMS */\n\n return unique;\n}", "target": 1, "cwe": [], "project": "wget", "commit_id": "59b920874daa565a1323ffa1e756e80493190686", "hash": 248269352987592620345400062055884756082, "size": 171, "message": "Support non-ASCII URLs\n\n* src/url.c [HAVE_ICONV]: Include iconv.h and langinfo.h.\n(convert_fname): New function.\n[HAVE_ICONV]: Convert file name from remote encoding to local\nencoding.\n(url_file_name): Call convert_fname.\n(filechr_table): Don't consider bytes in 128..159 as control\ncharacters.\n\n* tests/Test-ftp-iri.px: Fix the expected file name to match the\nnew file-name recoding. State the remote encoding explicitly on\nthe Wget command line.\n\n* NEWS: Mention the URI recoding when built with libiconv.", "dataset": "other", "idx": 215957}
  1048. {"func": "url_file_name (const struct url *u, char *replaced_filename)\n{\n struct growable fnres; /* stands for \"file name result\" */\n struct growable temp_fnres;\n\n const char *u_file;\n char *fname, *unique, *fname_len_check;\n const char *index_filename = \"index.html\"; /* The default index file is index.html */\n size_t max_length;\n\n fnres.base = NULL;\n fnres.size = 0;\n fnres.tail = 0;\n\n temp_fnres.base = NULL;\n temp_fnres.size = 0;\n temp_fnres.tail = 0;\n\n /* If an alternative index file was defined, change index_filename */\n if (opt.default_page)\n index_filename = opt.default_page;\n\n\n /* Start with the directory prefix, if specified. */\n if (opt.dir_prefix)\n append_string (opt.dir_prefix, &fnres);\n\n /* If \"dirstruct\" is turned on (typically the case with -r), add\n the host and port (unless those have been turned off) and\n directory structure. */\n if (opt.dirstruct)\n {\n if (opt.protocol_directories)\n {\n if (fnres.tail)\n append_char ('/', &fnres);\n append_string (supported_schemes[u->scheme].name, &fnres);\n }\n if (opt.add_hostdir)\n {\n if (fnres.tail)\n append_char ('/', &fnres);\n if (0 != strcmp (u->host, \"..\"))\n append_string (u->host, &fnres);\n else\n /* Host name can come from the network; malicious DNS may\n allow \"..\" to be resolved, causing us to write to\n \"../<file>\". Defang such host names. */\n append_string (\"%2E%2E\", &fnres);\n if (u->port != scheme_default_port (u->scheme))\n {\n char portstr[24];\n number_to_string (portstr, u->port);\n append_char (FN_PORT_SEP, &fnres);\n append_string (portstr, &fnres);\n }\n }\n\n append_dir_structure (u, &fnres);\n }\n\n if (!replaced_filename)\n {\n /* Create the filename. */\n u_file = *u->file ? u->file : index_filename;\n\n /* Append \"?query\" to the file name, even if empty,\n * and create fname_len_check. */\n if (u->query)\n fname_len_check = concat_strings (u_file, FN_QUERY_SEP_STR, u->query, NULL);\n else\n fname_len_check = strdupdelim (u_file, u_file + strlen (u_file));\n }\n else\n {\n u_file = replaced_filename;\n fname_len_check = strdupdelim (u_file, u_file + strlen (u_file));\n }\n\n append_uri_pathel (fname_len_check,\n fname_len_check + strlen (fname_len_check), false, &temp_fnres);\n\n /* Zero-terminate the temporary file name. */\n append_char ('\\0', &temp_fnres);\n\n /* Check that the length of the file name is acceptable. */\n#ifdef WINDOWS\n if (MAX_PATH > (fnres.tail + CHOMP_BUFFER + 2))\n {\n max_length = MAX_PATH - (fnres.tail + CHOMP_BUFFER + 2);\n /* FIXME: In Windows a filename is usually limited to 255 characters.\n To really be accurate you could call GetVolumeInformation() to get\n lpMaximumComponentLength\n */\n if (max_length > 255)\n {\n max_length = 255;\n }\n }\n else\n {\n max_length = 0;\n }\n#else\n max_length = get_max_length (fnres.base, fnres.tail, _PC_NAME_MAX) - CHOMP_BUFFER;\n#endif\n if (max_length > 0 && strlen (temp_fnres.base) > max_length)\n {\n logprintf (LOG_NOTQUIET, \"The name is too long, %lu chars total.\\n\",\n (unsigned long) strlen (temp_fnres.base));\n logprintf (LOG_NOTQUIET, \"Trying to shorten...\\n\");\n\n /* Shorten the file name. */\n temp_fnres.base[max_length] = '\\0';\n\n logprintf (LOG_NOTQUIET, \"New name is %s.\\n\", temp_fnres.base);\n }\n\n xfree (fname_len_check);\n\n /* The filename has already been 'cleaned' by append_uri_pathel() above. So,\n * just append it. */\n if (fnres.tail)\n append_char ('/', &fnres);\n append_string (temp_fnres.base, &fnres);\n\n fname = fnres.base;\n\n /* Make a final check that the path length is acceptable? */\n /* TODO: check fnres.base for path length problem */\n\n xfree (temp_fnres.base);\n\n fname = convert_fname (fname);\n\n /* Check the cases in which the unique extensions are not used:\n 1) Clobbering is turned off (-nc).\n 2) Retrieval with regetting.\n 3) Timestamping is used.\n 4) Hierarchy is built.\n 5) Backups are specified.\n\n The exception is the case when file does exist and is a\n directory (see `mkalldirs' for explanation). */\n\n if (ALLOW_CLOBBER\n && !(file_exists_p (fname) && !file_non_directory_p (fname)))\n {\n unique = fname;\n }\n else\n {\n unique = unique_name (fname, true);\n if (unique != fname)\n xfree (fname);\n }\n\n/* On VMS, alter the name as required. */\n#ifdef __VMS\n {\n char *unique2;\n\n unique2 = ods_conform( unique);\n if (unique2 != unique)\n {\n xfree (unique);\n unique = unique2;\n }\n }\n#endif /* def __VMS */\n\n return unique;\n}", "target": 0, "cwe": [], "project": "wget", "commit_id": "59b920874daa565a1323ffa1e756e80493190686", "hash": 328521672192198944507160659111401695202, "size": 173, "message": "Support non-ASCII URLs\n\n* src/url.c [HAVE_ICONV]: Include iconv.h and langinfo.h.\n(convert_fname): New function.\n[HAVE_ICONV]: Convert file name from remote encoding to local\nencoding.\n(url_file_name): Call convert_fname.\n(filechr_table): Don't consider bytes in 128..159 as control\ncharacters.\n\n* tests/Test-ftp-iri.px: Fix the expected file name to match the\nnew file-name recoding. State the remote encoding explicitly on\nthe Wget command line.\n\n* NEWS: Mention the URI recoding when built with libiconv.", "dataset": "other", "idx": 498301}
  1049. {"func": "load_image (const gchar *filename,\n GError **error)\n{\n FILE *fp;\n tga_info info;\n guchar header[18];\n guchar footer[26];\n guchar extension[495];\n long offset;\n\n gint32 image_ID = -1;\n\n fp = g_fopen (filename, \"rb\");\n\n if (! fp)\n {\n g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),\n _(\"Could not open '%s' for reading: %s\"),\n gimp_filename_to_utf8 (filename), g_strerror (errno));\n return -1;\n }\n\n gimp_progress_init_printf (_(\"Opening '%s'\"),\n gimp_filename_to_utf8 (filename));\n\n /* Is file big enough for a footer? */\n if (!fseek (fp, -26L, SEEK_END))\n {\n if (fread (footer, sizeof (footer), 1, fp) != 1)\n {\n g_message (_(\"Cannot read footer from '%s'\"),\n gimp_filename_to_utf8 (filename));\n return -1;\n }\n else if (memcmp (footer + 8, magic, sizeof (magic)) == 0)\n {\n /* Check the signature. */\n\n offset = (footer[0] +\n footer[1] * 256L +\n footer[2] * 65536L +\n footer[3] * 16777216L);\n\n if (offset != 0)\n {\n if (fseek (fp, offset, SEEK_SET) ||\n fread (extension, sizeof (extension), 1, fp) != 1)\n {\n g_message (_(\"Cannot read extension from '%s'\"),\n gimp_filename_to_utf8 (filename));\n return -1;\n }\n /* Eventually actually handle version 2 TGA here */\n }\n }\n }\n\n if (fseek (fp, 0, SEEK_SET) ||\n fread (header, sizeof (header), 1, fp) != 1)\n {\n g_message (_(\"Cannot read header from '%s'\"),\n gimp_filename_to_utf8 (filename));\n return -1;\n }\n\n switch (header[2])\n {\n case 1:\n info.imageType = TGA_TYPE_MAPPED;\n info.imageCompression = TGA_COMP_NONE;\n break;\n case 2:\n info.imageType = TGA_TYPE_COLOR;\n info.imageCompression = TGA_COMP_NONE;\n break;\n case 3:\n info.imageType = TGA_TYPE_GRAY;\n info.imageCompression = TGA_COMP_NONE;\n break;\n\n case 9:\n info.imageType = TGA_TYPE_MAPPED;\n info.imageCompression = TGA_COMP_RLE;\n break;\n case 10:\n info.imageType = TGA_TYPE_COLOR;\n info.imageCompression = TGA_COMP_RLE;\n break;\n case 11:\n info.imageType = TGA_TYPE_GRAY;\n info.imageCompression = TGA_COMP_RLE;\n break;\n\n default:\n info.imageType = 0;\n }\n\n info.idLength = header[0];\n info.colorMapType = header[1];\n\n info.colorMapIndex = header[3] + header[4] * 256;\n info.colorMapLength = header[5] + header[6] * 256;\n info.colorMapSize = header[7];\n\n info.xOrigin = header[8] + header[9] * 256;\n info.yOrigin = header[10] + header[11] * 256;\n info.width = header[12] + header[13] * 256;\n info.height = header[14] + header[15] * 256;\n\n info.bpp = header[16];\n info.bytes = (info.bpp + 7) / 8;\n info.alphaBits = header[17] & 0x0f; /* Just the low 4 bits */\n info.flipHoriz = (header[17] & 0x10) ? 1 : 0;\n info.flipVert = (header[17] & 0x20) ? 0 : 1;\n\n /* hack to handle some existing files with incorrect headers, see bug #306675 */\n if (info.alphaBits == info.bpp)\n info.alphaBits = 0;\n\n /* hack to handle yet another flavor of incorrect headers, see bug #540969 */\n if (info.alphaBits == 0)\n {\n if (info.imageType == TGA_TYPE_COLOR && info.bpp == 32)\n info.alphaBits = 8;\n\n if (info.imageType == TGA_TYPE_GRAY && info.bpp == 16)\n info.alphaBits = 8;\n }\n\n switch (info.imageType)\n {\n case TGA_TYPE_MAPPED:\n if (info.bpp != 8)\n {\n g_message (\"Unhandled sub-format in '%s' (type = %u, bpp = %u)\",\n gimp_filename_to_utf8 (filename),\n info.imageType, info.bpp);\n return -1;\n }\n break;\n case TGA_TYPE_COLOR:\n if ((info.bpp != 15 && info.bpp != 16 &&\n info.bpp != 24 && info.bpp != 32) ||\n ((info.bpp == 15 || info.bpp == 24) &&\n info.alphaBits != 0) ||\n (info.bpp == 16 && info.alphaBits != 1) ||\n (info.bpp == 32 && info.alphaBits != 8))\n {\n g_message (\"Unhandled sub-format in '%s' (type = %u, bpp = %u, alpha = %u)\",\n gimp_filename_to_utf8 (filename),\n info.imageType, info.bpp, info.alphaBits);\n return -1;\n }\n break;\n case TGA_TYPE_GRAY:\n if (info.bpp != 8 &&\n (info.alphaBits != 8 || (info.bpp != 16 && info.bpp != 15)))\n {\n g_message (\"Unhandled sub-format in '%s' (type = %u, bpp = %u)\",\n gimp_filename_to_utf8 (filename),\n info.imageType, info.bpp);\n return -1;\n }\n break;\n\n default:\n g_message (\"Unknown image type %u for '%s'\",\n info.imageType, gimp_filename_to_utf8 (filename));\n return -1;\n }\n\n /* Plausible but unhandled formats */\n if (info.bytes * 8 != info.bpp && info.bpp != 15)\n {\n g_message (\"Unhandled sub-format in '%s' (type = %u, bpp = %u)\",\n gimp_filename_to_utf8 (filename),\n info.imageType, info.bpp);\n return -1;\n }\n\n /* Check that we have a color map only when we need it. */\n if (info.imageType == TGA_TYPE_MAPPED && info.colorMapType != 1)\n {\n g_message (\"Indexed image has invalid color map type %u\",\n info.colorMapType);\n return -1;\n }\n else if (info.imageType != TGA_TYPE_MAPPED && info.colorMapType != 0)\n {\n g_message (\"Non-indexed image has invalid color map type %u\",\n info.colorMapType);\n return -1;\n }\n\n /* Skip the image ID field. */\n if (info.idLength && fseek (fp, info.idLength, SEEK_CUR))\n {\n g_message (\"File '%s' is truncated or corrupted\",\n gimp_filename_to_utf8 (filename));\n return -1;\n }\n\n image_ID = ReadImage (fp, &info, filename);\n\n fclose (fp);\n\n return image_ID;\n}", "target": 1, "cwe": ["CWE-125"], "project": "GIMP", "commit_id": "22e2571c25425f225abdb11a566cc281fca6f366", "hash": 210802702046896555195187298959116285766, "size": 208, "message": "plug-ins: TGA 16-bit RGB (without alpha bit) is also valid.\n\nAccording to some spec on the web, 16-bit RGB is also valid. In this\ncase, the last bit is simply ignored (at least that's how it is\nimplemented right now).\n\n(cherry picked from commit 8ea316667c8a3296bce2832b3986b58d0fdfc077)", "dataset": "other", "idx": 215994}
  1050. {"func": "load_image (const gchar *filename,\n GError **error)\n{\n FILE *fp;\n tga_info info;\n guchar header[18];\n guchar footer[26];\n guchar extension[495];\n long offset;\n\n gint32 image_ID = -1;\n\n fp = g_fopen (filename, \"rb\");\n\n if (! fp)\n {\n g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),\n _(\"Could not open '%s' for reading: %s\"),\n gimp_filename_to_utf8 (filename), g_strerror (errno));\n return -1;\n }\n\n gimp_progress_init_printf (_(\"Opening '%s'\"),\n gimp_filename_to_utf8 (filename));\n\n /* Is file big enough for a footer? */\n if (!fseek (fp, -26L, SEEK_END))\n {\n if (fread (footer, sizeof (footer), 1, fp) != 1)\n {\n g_message (_(\"Cannot read footer from '%s'\"),\n gimp_filename_to_utf8 (filename));\n return -1;\n }\n else if (memcmp (footer + 8, magic, sizeof (magic)) == 0)\n {\n /* Check the signature. */\n\n offset = (footer[0] +\n footer[1] * 256L +\n footer[2] * 65536L +\n footer[3] * 16777216L);\n\n if (offset != 0)\n {\n if (fseek (fp, offset, SEEK_SET) ||\n fread (extension, sizeof (extension), 1, fp) != 1)\n {\n g_message (_(\"Cannot read extension from '%s'\"),\n gimp_filename_to_utf8 (filename));\n return -1;\n }\n /* Eventually actually handle version 2 TGA here */\n }\n }\n }\n\n if (fseek (fp, 0, SEEK_SET) ||\n fread (header, sizeof (header), 1, fp) != 1)\n {\n g_message (_(\"Cannot read header from '%s'\"),\n gimp_filename_to_utf8 (filename));\n return -1;\n }\n\n switch (header[2])\n {\n case 1:\n info.imageType = TGA_TYPE_MAPPED;\n info.imageCompression = TGA_COMP_NONE;\n break;\n case 2:\n info.imageType = TGA_TYPE_COLOR;\n info.imageCompression = TGA_COMP_NONE;\n break;\n case 3:\n info.imageType = TGA_TYPE_GRAY;\n info.imageCompression = TGA_COMP_NONE;\n break;\n\n case 9:\n info.imageType = TGA_TYPE_MAPPED;\n info.imageCompression = TGA_COMP_RLE;\n break;\n case 10:\n info.imageType = TGA_TYPE_COLOR;\n info.imageCompression = TGA_COMP_RLE;\n break;\n case 11:\n info.imageType = TGA_TYPE_GRAY;\n info.imageCompression = TGA_COMP_RLE;\n break;\n\n default:\n info.imageType = 0;\n }\n\n info.idLength = header[0];\n info.colorMapType = header[1];\n\n info.colorMapIndex = header[3] + header[4] * 256;\n info.colorMapLength = header[5] + header[6] * 256;\n info.colorMapSize = header[7];\n\n info.xOrigin = header[8] + header[9] * 256;\n info.yOrigin = header[10] + header[11] * 256;\n info.width = header[12] + header[13] * 256;\n info.height = header[14] + header[15] * 256;\n\n info.bpp = header[16];\n info.bytes = (info.bpp + 7) / 8;\n info.alphaBits = header[17] & 0x0f; /* Just the low 4 bits */\n info.flipHoriz = (header[17] & 0x10) ? 1 : 0;\n info.flipVert = (header[17] & 0x20) ? 0 : 1;\n\n /* hack to handle some existing files with incorrect headers, see bug #306675 */\n if (info.alphaBits == info.bpp)\n info.alphaBits = 0;\n\n /* hack to handle yet another flavor of incorrect headers, see bug #540969 */\n if (info.alphaBits == 0)\n {\n if (info.imageType == TGA_TYPE_COLOR && info.bpp == 32)\n info.alphaBits = 8;\n\n if (info.imageType == TGA_TYPE_GRAY && info.bpp == 16)\n info.alphaBits = 8;\n }\n\n switch (info.imageType)\n {\n case TGA_TYPE_MAPPED:\n if (info.bpp != 8)\n {\n g_message (\"Unhandled sub-format in '%s' (type = %u, bpp = %u)\",\n gimp_filename_to_utf8 (filename),\n info.imageType, info.bpp);\n return -1;\n }\n break;\n case TGA_TYPE_COLOR:\n if ((info.bpp != 15 && info.bpp != 16 &&\n info.bpp != 24 && info.bpp != 32) ||\n ((info.bpp == 15 || info.bpp == 24) &&\n info.alphaBits != 0) ||\n (info.bpp == 16 && info.alphaBits != 1 &&\n info.alphaBits != 0) ||\n (info.bpp == 32 && info.alphaBits != 8))\n {\n g_message (\"Unhandled sub-format in '%s' (type = %u, bpp = %u, alpha = %u)\",\n gimp_filename_to_utf8 (filename),\n info.imageType, info.bpp, info.alphaBits);\n return -1;\n }\n break;\n case TGA_TYPE_GRAY:\n if (info.bpp != 8 &&\n (info.alphaBits != 8 || (info.bpp != 16 && info.bpp != 15)))\n {\n g_message (\"Unhandled sub-format in '%s' (type = %u, bpp = %u)\",\n gimp_filename_to_utf8 (filename),\n info.imageType, info.bpp);\n return -1;\n }\n break;\n\n default:\n g_message (\"Unknown image type %u for '%s'\",\n info.imageType, gimp_filename_to_utf8 (filename));\n return -1;\n }\n\n /* Plausible but unhandled formats */\n if (info.bytes * 8 != info.bpp && info.bpp != 15)\n {\n g_message (\"Unhandled sub-format in '%s' (type = %u, bpp = %u)\",\n gimp_filename_to_utf8 (filename),\n info.imageType, info.bpp);\n return -1;\n }\n\n /* Check that we have a color map only when we need it. */\n if (info.imageType == TGA_TYPE_MAPPED && info.colorMapType != 1)\n {\n g_message (\"Indexed image has invalid color map type %u\",\n info.colorMapType);\n return -1;\n }\n else if (info.imageType != TGA_TYPE_MAPPED && info.colorMapType != 0)\n {\n g_message (\"Non-indexed image has invalid color map type %u\",\n info.colorMapType);\n return -1;\n }\n\n /* Skip the image ID field. */\n if (info.idLength && fseek (fp, info.idLength, SEEK_CUR))\n {\n g_message (\"File '%s' is truncated or corrupted\",\n gimp_filename_to_utf8 (filename));\n return -1;\n }\n\n image_ID = ReadImage (fp, &info, filename);\n\n fclose (fp);\n\n return image_ID;\n}", "target": 0, "cwe": ["CWE-125"], "project": "GIMP", "commit_id": "22e2571c25425f225abdb11a566cc281fca6f366", "hash": 112786509503859538202403338615754577633, "size": 209, "message": "plug-ins: TGA 16-bit RGB (without alpha bit) is also valid.\n\nAccording to some spec on the web, 16-bit RGB is also valid. In this\ncase, the last bit is simply ignored (at least that's how it is\nimplemented right now).\n\n(cherry picked from commit 8ea316667c8a3296bce2832b3986b58d0fdfc077)", "dataset": "other", "idx": 498639}
  1051. {"func": "do_ed_script (char const *inname, char const *outname,\n\t bool *outname_needs_removal, FILE *ofp)\n{\n static char const editor_program[] = EDITOR_PROGRAM;\n\n file_offset beginning_of_this_line;\n size_t chars_read;\n FILE *tmpfp = 0;\n char const *tmpname;\n int tmpfd;\n pid_t pid;\n\n if (! dry_run && ! skip_rest_of_patch)\n {\n\t/* Write ed script to a temporary file. This causes ed to abort on\n\t invalid commands such as when line numbers or ranges exceed the\n\t number of available lines. When ed reads from a pipe, it rejects\n\t invalid commands and treats the next line as a new command, which\n\t can lead to arbitrary command execution. */\n\n\ttmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0);\n\tif (tmpfd == -1)\n\t pfatal (\"Can't create temporary file %s\", quotearg (tmpname));\n\ttmpfp = fdopen (tmpfd, \"w+b\");\n\tif (! tmpfp)\n\t pfatal (\"Can't open stream for file %s\", quotearg (tmpname));\n }\n\n for (;;) {\n\tchar ed_command_letter;\n\tbeginning_of_this_line = file_tell (pfp);\n\tchars_read = get_line ();\n\tif (! chars_read) {\n\t next_intuit_at(beginning_of_this_line,p_input_line);\n\t break;\n\t}\n\ted_command_letter = get_ed_command_letter (buf);\n\tif (ed_command_letter) {\n\t if (tmpfp)\n\t\tif (! fwrite (buf, sizeof *buf, chars_read, tmpfp))\n\t\t write_fatal ();\n\t if (ed_command_letter != 'd' && ed_command_letter != 's') {\n\t p_pass_comments_through = true;\n\t\twhile ((chars_read = get_line ()) != 0) {\n\t\t if (tmpfp)\n\t\t\tif (! fwrite (buf, sizeof *buf, chars_read, tmpfp))\n\t\t\t write_fatal ();\n\t\t if (chars_read == 2 && strEQ (buf, \".\\n\"))\n\t\t\tbreak;\n\t\t}\n\t\tp_pass_comments_through = false;\n\t }\n\t}\n\telse {\n\t next_intuit_at(beginning_of_this_line,p_input_line);\n\t break;\n\t}\n }\n if (!tmpfp)\n return;\n if (fwrite (\"w\\nq\\n\", sizeof (char), (size_t) 4, tmpfp) == 0\n\t|| fflush (tmpfp) != 0)\n write_fatal ();\n\n if (lseek (tmpfd, 0, SEEK_SET) == -1)\n pfatal (\"Can't rewind to the beginning of file %s\", quotearg (tmpname));\n\n if (! dry_run && ! skip_rest_of_patch) {\n\tint exclusive = *outname_needs_removal ? 0 : O_EXCL;\n\t*outname_needs_removal = true;\n\tif (inerrno != ENOENT)\n\t {\n\t *outname_needs_removal = true;\n\t copy_file (inname, outname, 0, exclusive, instat.st_mode, true);\n\t }\n\tsprintf (buf, \"%s %s%s\", editor_program,\n\t\t verbosity == VERBOSE ? \"\" : \"- \",\n\t\t outname);\n\tfflush (stdout);\n\n\tpid = fork();\n\tif (pid == -1)\n\t pfatal (\"Can't fork\");\n\telse if (pid == 0)\n\t {\n\t dup2 (tmpfd, 0);\n\t execl (\"/bin/sh\", \"sh\", \"-c\", buf, (char *) 0);\n\t _exit (2);\n\t }\n\telse\n\t {\n\t int wstatus;\n\t if (waitpid (pid, &wstatus, 0) == -1\n\t || ! WIFEXITED (wstatus)\n\t\t|| WEXITSTATUS (wstatus) != 0)\n\t fatal (\"%s FAILED\", editor_program);\n\t }\n }\n\n fclose (tmpfp);\n safe_unlink (tmpname);\n\n if (ofp)\n {\n\tFILE *ifp = fopen (outname, binary_transput ? \"rb\" : \"r\");\n\tint c;\n\tif (!ifp)\n\t pfatal (\"can't open '%s'\", outname);\n\twhile ((c = getc (ifp)) != EOF)\n\t if (putc (c, ofp) == EOF)\n\t write_fatal ();\n\tif (ferror (ifp) || fclose (ifp) != 0)\n\t read_fatal ();\n }\n}", "target": 1, "cwe": ["CWE-78"], "project": "patch", "commit_id": "3fcd042d26d70856e826a42b5f93dc4854d80bf0", "hash": 338700816905051362992541803818419670330, "size": 115, "message": "Invoke ed directly instead of using the shell\n\n* src/pch.c (do_ed_script): Invoke ed directly instead of using a shell\ncommand to avoid quoting vulnerabilities.", "dataset": "other", "idx": 216036}
  1052. {"func": "do_ed_script (char const *inname, char const *outname,\n\t bool *outname_needs_removal, FILE *ofp)\n{\n static char const editor_program[] = EDITOR_PROGRAM;\n\n file_offset beginning_of_this_line;\n size_t chars_read;\n FILE *tmpfp = 0;\n char const *tmpname;\n int tmpfd;\n pid_t pid;\n\n if (! dry_run && ! skip_rest_of_patch)\n {\n\t/* Write ed script to a temporary file. This causes ed to abort on\n\t invalid commands such as when line numbers or ranges exceed the\n\t number of available lines. When ed reads from a pipe, it rejects\n\t invalid commands and treats the next line as a new command, which\n\t can lead to arbitrary command execution. */\n\n\ttmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0);\n\tif (tmpfd == -1)\n\t pfatal (\"Can't create temporary file %s\", quotearg (tmpname));\n\ttmpfp = fdopen (tmpfd, \"w+b\");\n\tif (! tmpfp)\n\t pfatal (\"Can't open stream for file %s\", quotearg (tmpname));\n }\n\n for (;;) {\n\tchar ed_command_letter;\n\tbeginning_of_this_line = file_tell (pfp);\n\tchars_read = get_line ();\n\tif (! chars_read) {\n\t next_intuit_at(beginning_of_this_line,p_input_line);\n\t break;\n\t}\n\ted_command_letter = get_ed_command_letter (buf);\n\tif (ed_command_letter) {\n\t if (tmpfp)\n\t\tif (! fwrite (buf, sizeof *buf, chars_read, tmpfp))\n\t\t write_fatal ();\n\t if (ed_command_letter != 'd' && ed_command_letter != 's') {\n\t p_pass_comments_through = true;\n\t\twhile ((chars_read = get_line ()) != 0) {\n\t\t if (tmpfp)\n\t\t\tif (! fwrite (buf, sizeof *buf, chars_read, tmpfp))\n\t\t\t write_fatal ();\n\t\t if (chars_read == 2 && strEQ (buf, \".\\n\"))\n\t\t\tbreak;\n\t\t}\n\t\tp_pass_comments_through = false;\n\t }\n\t}\n\telse {\n\t next_intuit_at(beginning_of_this_line,p_input_line);\n\t break;\n\t}\n }\n if (!tmpfp)\n return;\n if (fwrite (\"w\\nq\\n\", sizeof (char), (size_t) 4, tmpfp) == 0\n\t|| fflush (tmpfp) != 0)\n write_fatal ();\n\n if (lseek (tmpfd, 0, SEEK_SET) == -1)\n pfatal (\"Can't rewind to the beginning of file %s\", quotearg (tmpname));\n\n if (! dry_run && ! skip_rest_of_patch) {\n\tint exclusive = *outname_needs_removal ? 0 : O_EXCL;\n\t*outname_needs_removal = true;\n\tif (inerrno != ENOENT)\n\t {\n\t *outname_needs_removal = true;\n\t copy_file (inname, outname, 0, exclusive, instat.st_mode, true);\n\t }\n\tfflush (stdout);\n\n\tpid = fork();\n\tif (pid == -1)\n\t pfatal (\"Can't fork\");\n\telse if (pid == 0)\n\t {\n\t dup2 (tmpfd, 0);\n\t assert (outname[0] != '!' && outname[0] != '-');\n\t execlp (editor_program, editor_program, \"-\", outname, (char *) NULL);\n\t _exit (2);\n\t }\n\telse\n\t {\n\t int wstatus;\n\t if (waitpid (pid, &wstatus, 0) == -1\n\t || ! WIFEXITED (wstatus)\n\t\t|| WEXITSTATUS (wstatus) != 0)\n\t fatal (\"%s FAILED\", editor_program);\n\t }\n }\n\n fclose (tmpfp);\n safe_unlink (tmpname);\n\n if (ofp)\n {\n\tFILE *ifp = fopen (outname, binary_transput ? \"rb\" : \"r\");\n\tint c;\n\tif (!ifp)\n\t pfatal (\"can't open '%s'\", outname);\n\twhile ((c = getc (ifp)) != EOF)\n\t if (putc (c, ofp) == EOF)\n\t write_fatal ();\n\tif (ferror (ifp) || fclose (ifp) != 0)\n\t read_fatal ();\n }\n}", "target": 0, "cwe": ["CWE-78"], "project": "patch", "commit_id": "3fcd042d26d70856e826a42b5f93dc4854d80bf0", "hash": 164336965162787411663255462273976593275, "size": 113, "message": "Invoke ed directly instead of using the shell\n\n* src/pch.c (do_ed_script): Invoke ed directly instead of using a shell\ncommand to avoid quoting vulnerabilities.", "dataset": "other", "idx": 498970}
  1053. {"func": "_eddsa_hash (const struct ecc_modulo *m,\n\t mp_limb_t *rp, size_t digest_size, const uint8_t *digest)\n{\n mp_size_t nlimbs = (8*digest_size + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS;\n\n mpn_set_base256_le (rp, nlimbs, digest, digest_size);\n\n if (nlimbs > 2*m->size)\n {\n /* Special case for Ed448: reduce rp to 2*m->size limbs.\n\t After decoding rp from a hash of size 2*rn:\n\n\t rp = r2 || r1 || r0\n\n\t where r0 and r1 have m->size limbs. Reduce this to:\n\n\t rp = r1' || r0\n\n\t where r1' has m->size limbs. */\n mp_limb_t hi = rp[2*m->size];\n assert (nlimbs == 2*m->size + 1);\n\n hi = mpn_addmul_1 (rp + m->size, m->B, m->size, hi);\n assert (hi <= 1);\n hi = mpn_cnd_add_n (hi, rp + m->size, rp + m->size, m->B, m->size);\n assert (hi == 0);\n }\n m->mod (m, rp, rp);\n}", "target": 1, "cwe": ["CWE-787"], "project": "nettle", "commit_id": "ae3801a0e5cce276c270973214385c86048d5f7b", "hash": 268891952040565861726467544094713063054, "size": 29, "message": "Similar fix for eddsa.\n\n* eddsa-hash.c (_eddsa_hash): Ensure result is canonically\nreduced. Two of the three call sites need that.\n\n(cherry picked from commit d9b564e4b3b3a5691afb9328c7342b3f7ca64288)", "dataset": "other", "idx": 216084}
  1054. {"func": "_eddsa_hash (const struct ecc_modulo *m,\n\t mp_limb_t *rp, size_t digest_size, const uint8_t *digest)\n{\n mp_size_t nlimbs = (8*digest_size + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS;\n mp_limb_t cy;\n\n mpn_set_base256_le (rp, nlimbs, digest, digest_size);\n\n if (nlimbs > 2*m->size)\n {\n /* Special case for Ed448: reduce rp to 2*m->size limbs.\n\t After decoding rp from a hash of size 2*rn:\n\n\t rp = r2 || r1 || r0\n\n\t where r0 and r1 have m->size limbs. Reduce this to:\n\n\t rp = r1' || r0\n\n\t where r1' has m->size limbs. */\n mp_limb_t hi = rp[2*m->size];\n assert (nlimbs == 2*m->size + 1);\n\n hi = mpn_addmul_1 (rp + m->size, m->B, m->size, hi);\n assert (hi <= 1);\n hi = mpn_cnd_add_n (hi, rp + m->size, rp + m->size, m->B, m->size);\n assert (hi == 0);\n }\n m->mod (m, rp + m->size , rp);\n /* Ensure canonical reduction. */\n cy = mpn_sub_n (rp, rp + m->size, m->m, m->size);\n cnd_copy (cy, rp, rp + m->size, m->size);\n}", "target": 0, "cwe": ["CWE-787"], "project": "nettle", "commit_id": "ae3801a0e5cce276c270973214385c86048d5f7b", "hash": 184589664896563874284916719738565724397, "size": 33, "message": "Similar fix for eddsa.\n\n* eddsa-hash.c (_eddsa_hash): Ensure result is canonically\nreduced. Two of the three call sites need that.\n\n(cherry picked from commit d9b564e4b3b3a5691afb9328c7342b3f7ca64288)", "dataset": "other", "idx": 499623}
  1055. {"func": "ds_fgetstr (FILE *f, dynamic_string *s, char eos)\n{\n int insize;\t\t\t/* Amount needed for line. */\n int strsize;\t\t\t/* Amount allocated for S. */\n int next_ch;\n\n /* Initialize. */\n insize = 0;\n strsize = s->ds_length;\n\n /* Read the input string. */\n next_ch = getc (f);\n while (next_ch != eos && next_ch != EOF)\n {\n if (insize >= strsize - 1)\n\t{\n\t ds_resize (s, strsize * 2 + 2);\n\t strsize = s->ds_length;\n\t}\n s->ds_string[insize++] = next_ch;\n next_ch = getc (f);\n }\n s->ds_string[insize++] = '\\0';\n\n if (insize == 1 && next_ch == EOF)\n return NULL;\n else\n return s->ds_string;\n}", "target": 1, "cwe": ["CWE-190"], "project": "cpio", "commit_id": "dd96882877721703e19272fe25034560b794061b", "hash": 89622374372923890041979167530041250799, "size": 29, "message": "Rewrite dynamic string support.\n\n* src/dstring.c (ds_init): Take a single argument.\n(ds_free): New function.\n(ds_resize): Take a single argument. Use x2nrealloc to expand\nthe storage.\n(ds_reset,ds_append,ds_concat,ds_endswith): New function.\n(ds_fgetstr): Rewrite. In particular, this fixes integer overflow.\n* src/dstring.h (dynamic_string): Keep both the allocated length\n(ds_size) and index of the next free byte in the string (ds_idx).\n(ds_init,ds_resize): Change signature.\n(ds_len): New macro.\n(ds_free,ds_reset,ds_append,ds_concat,ds_endswith): New protos.\n* src/copyin.c: Use new ds_ functions.\n* src/copyout.c: Likewise.\n* src/copypass.c: Likewise.\n* src/util.c: Likewise.", "dataset": "other", "idx": 216101}
  1056. {"func": "ds_fgetstr (FILE *f, dynamic_string *s, char eos)\n{\n int next_ch;\n\n /* Initialize. */\n s->ds_idx = 0;\n\n /* Read the input string. */\n while ((next_ch = getc (f)) != eos && next_ch != EOF)\n {\n ds_resize (s);\n s->ds_string[s->ds_idx++] = next_ch;\n }\n ds_resize (s);\n s->ds_string[s->ds_idx] = '\\0';\n\n if (s->ds_idx == 0 && next_ch == EOF)\n return NULL;\n else\n return s->ds_string;\n}", "target": 0, "cwe": ["CWE-190"], "project": "cpio", "commit_id": "dd96882877721703e19272fe25034560b794061b", "hash": 38898591507161366429804741213308730595, "size": 21, "message": "Rewrite dynamic string support.\n\n* src/dstring.c (ds_init): Take a single argument.\n(ds_free): New function.\n(ds_resize): Take a single argument. Use x2nrealloc to expand\nthe storage.\n(ds_reset,ds_append,ds_concat,ds_endswith): New function.\n(ds_fgetstr): Rewrite. In particular, this fixes integer overflow.\n* src/dstring.h (dynamic_string): Keep both the allocated length\n(ds_size) and index of the next free byte in the string (ds_idx).\n(ds_init,ds_resize): Change signature.\n(ds_len): New macro.\n(ds_free,ds_reset,ds_append,ds_concat,ds_endswith): New protos.\n* src/copyin.c: Use new ds_ functions.\n* src/copyout.c: Likewise.\n* src/copypass.c: Likewise.\n* src/util.c: Likewise.", "dataset": "other", "idx": 499640}
  1057. {"func": "unsigned int get_random_int(void)\n{\n\t/*\n\t * Use IP's RNG. It suits our purpose perfectly: it re-keys itself\n\t * every second, from the entropy pool (and thus creates a limited\n\t * drain on it), and uses halfMD4Transform within the second. We\n\t * also mix it with jiffies and the PID:\n\t */\n\treturn secure_ip_id((__force __be32)(current->pid + jiffies));\n}", "target": 1, "cwe": ["CWE-310"], "project": "linux-2.6", "commit_id": "8a0a9bd4db63bc45e3017bedeafbd88d0eb84d02", "hash": 291941620665843470215173682867258940568, "size": 10, "message": "random: make get_random_int() more random\n\nIt's a really simple patch that basically just open-codes the current\n\"secure_ip_id()\" call, but when open-coding it we now use a _static_\nhashing area, so that it gets updated every time.\n\nAnd to make sure somebody can't just start from the same original seed of\nall-zeroes, and then do the \"half_md4_transform()\" over and over until\nthey get the same sequence as the kernel has, each iteration also mixes in\nthe same old \"current->pid + jiffies\" we used - so we should now have a\nregular strong pseudo-number generator, but we also have one that doesn't\nhave a single seed.\n\nNote: the \"pid + jiffies\" is just meant to be a tiny tiny bit of noise. It\nhas no real meaning. It could be anything. I just picked the previous\nseed, it's just that now we keep the state in between calls and that will\nfeed into the next result, and that should make all the difference.\n\nI made that hash be a per-cpu data just to avoid cache-line ping-pong:\nhaving multiple CPU's write to the same data would be fine for randomness,\nand add yet another layer of chaos to it, but since get_random_int() is\nsupposed to be a fast interface I did it that way instead. I considered\nusing \"__raw_get_cpu_var()\" to avoid any preemption overhead while still\ngetting the hash be _mostly_ ping-pong free, but in the end good taste won\nout.\n\nSigned-off-by: Ingo Molnar <mingo@elte.hu>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "dataset": "other", "idx": 216119}
  1058. {"func": "unsigned int get_random_int(void)\n{\n\tstruct keydata *keyptr;\n\t__u32 *hash = get_cpu_var(get_random_int_hash);\n\tint ret;\n\n\tkeyptr = get_keyptr();\n\thash[0] += current->pid + jiffies + get_cycles() + (int)(long)&ret;\n\n\tret = half_md4_transform(hash, keyptr->secret);\n\tput_cpu_var(get_random_int_hash);\n\n\treturn ret;\n}", "target": 0, "cwe": ["CWE-310"], "project": "linux-2.6", "commit_id": "8a0a9bd4db63bc45e3017bedeafbd88d0eb84d02", "hash": 134018116402125477535352207466632733436, "size": 14, "message": "random: make get_random_int() more random\n\nIt's a really simple patch that basically just open-codes the current\n\"secure_ip_id()\" call, but when open-coding it we now use a _static_\nhashing area, so that it gets updated every time.\n\nAnd to make sure somebody can't just start from the same original seed of\nall-zeroes, and then do the \"half_md4_transform()\" over and over until\nthey get the same sequence as the kernel has, each iteration also mixes in\nthe same old \"current->pid + jiffies\" we used - so we should now have a\nregular strong pseudo-number generator, but we also have one that doesn't\nhave a single seed.\n\nNote: the \"pid + jiffies\" is just meant to be a tiny tiny bit of noise. It\nhas no real meaning. It could be anything. I just picked the previous\nseed, it's just that now we keep the state in between calls and that will\nfeed into the next result, and that should make all the difference.\n\nI made that hash be a per-cpu data just to avoid cache-line ping-pong:\nhaving multiple CPU's write to the same data would be fine for randomness,\nand add yet another layer of chaos to it, but since get_random_int() is\nsupposed to be a fast interface I did it that way instead. I considered\nusing \"__raw_get_cpu_var()\" to avoid any preemption overhead while still\ngetting the hash be _mostly_ ping-pong free, but in the end good taste won\nout.\n\nSigned-off-by: Ingo Molnar <mingo@elte.hu>\nSigned-off-by: Linus Torvalds <torvalds@linux-foundation.org>", "dataset": "other", "idx": 499883}
  1059. {"func": "static int __init acpi_parse_hpet(unsigned long phys, unsigned long size)\n{\n\tstruct acpi_table_hpet *hpet_tbl;\n\n\tif (!phys || !size)\n\t\treturn -EINVAL;\n\n\thpet_tbl = (struct acpi_table_hpet *)__acpi_map_table(phys, size);\n\tif (!hpet_tbl) {\n\t\tprintk(KERN_WARNING PREFIX \"Unable to map HPET\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\tif (hpet_tbl->addr.space_id != ACPI_SPACE_MEM) {\n\t\tprintk(KERN_WARNING PREFIX \"HPET timers must be located in \"\n\t\t \"memory.\\n\");\n\t\treturn -1;\n\t}\n#ifdef\tCONFIG_X86_64\n\tvxtime.hpet_address = hpet_tbl->addr.addrl |\n\t ((long)hpet_tbl->addr.addrh << 32);\n\n\tprintk(KERN_INFO PREFIX \"HPET id: %#x base: %#lx\\n\",\n\t hpet_tbl->id, vxtime.hpet_address);\n#else\t\t\t\t/* X86 */\n\t{\n\t\textern unsigned long hpet_address;\n\n\t\thpet_address = hpet_tbl->addr.addrl;\n\t\tprintk(KERN_INFO PREFIX \"HPET id: %#x base: %#lx\\n\",\n\t\t hpet_tbl->id, hpet_address);\n\t}\n#endif\t\t\t\t/* X86 */\n\n\treturn 0;\n}", "target": 1, "cwe": [], "project": "linux-2.6", "commit_id": "f0f4c3432e5e1087b3a8c0e6bd4113d3c37497ff", "hash": 62909509703384276763101755339705010618, "size": 36, "message": "[PATCH] i386: add HPET(s) into resource map\n\nAdd HPET(s) into resource map. This will allow for the HPET(s) to be\nvisibile within /proc/iomem.\n\nSigned-off-by: Aaron Durbin <adurbin@google.com>\nSigned-off-by: Andi Kleen <ak@suse.de>", "dataset": "other", "idx": 216124}
  1060. {"func": "static int __init acpi_parse_hpet(unsigned long phys, unsigned long size)\n{\n\tstruct acpi_table_hpet *hpet_tbl;\n\tstruct resource *hpet_res;\n\tresource_size_t res_start;\n\n\tif (!phys || !size)\n\t\treturn -EINVAL;\n\n\thpet_tbl = (struct acpi_table_hpet *)__acpi_map_table(phys, size);\n\tif (!hpet_tbl) {\n\t\tprintk(KERN_WARNING PREFIX \"Unable to map HPET\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\tif (hpet_tbl->addr.space_id != ACPI_SPACE_MEM) {\n\t\tprintk(KERN_WARNING PREFIX \"HPET timers must be located in \"\n\t\t \"memory.\\n\");\n\t\treturn -1;\n\t}\n\n#define HPET_RESOURCE_NAME_SIZE 9\n\thpet_res = alloc_bootmem(sizeof(*hpet_res) + HPET_RESOURCE_NAME_SIZE);\n\tif (hpet_res) {\n\t\tmemset(hpet_res, 0, sizeof(*hpet_res));\n\t\thpet_res->name = (void *)&hpet_res[1];\n\t\thpet_res->flags = IORESOURCE_MEM | IORESOURCE_BUSY;\n\t\tsnprintf((char *)hpet_res->name, HPET_RESOURCE_NAME_SIZE,\n\t\t\t \"HPET %u\", hpet_tbl->number);\n\t\thpet_res->end = (1 * 1024) - 1;\n\t}\n\n#ifdef\tCONFIG_X86_64\n\tvxtime.hpet_address = hpet_tbl->addr.addrl |\n\t ((long)hpet_tbl->addr.addrh << 32);\n\n\tprintk(KERN_INFO PREFIX \"HPET id: %#x base: %#lx\\n\",\n\t hpet_tbl->id, vxtime.hpet_address);\n\n\tres_start = vxtime.hpet_address;\n#else\t\t\t\t/* X86 */\n\t{\n\t\textern unsigned long hpet_address;\n\n\t\thpet_address = hpet_tbl->addr.addrl;\n\t\tprintk(KERN_INFO PREFIX \"HPET id: %#x base: %#lx\\n\",\n\t\t hpet_tbl->id, hpet_address);\n\n\t\tres_start = hpet_address;\n\t}\n#endif\t\t\t\t/* X86 */\n\n\tif (hpet_res) {\n\t\thpet_res->start = res_start;\n\t\thpet_res->end += res_start;\n\t\tinsert_resource(&iomem_resource, hpet_res);\n\t}\n\n\treturn 0;\n}", "target": 0, "cwe": [], "project": "linux-2.6", "commit_id": "f0f4c3432e5e1087b3a8c0e6bd4113d3c37497ff", "hash": 73361527373490632346304437063543698062, "size": 60, "message": "[PATCH] i386: add HPET(s) into resource map\n\nAdd HPET(s) into resource map. This will allow for the HPET(s) to be\nvisibile within /proc/iomem.\n\nSigned-off-by: Aaron Durbin <adurbin@google.com>\nSigned-off-by: Andi Kleen <ak@suse.de>", "dataset": "other", "idx": 500008}
  1061. {"func": "int ssl3_send_client_key_exchange(SSL *s)\n\t{\n\tunsigned char *p,*d;\n\tint n;\n\tunsigned long l;\n#ifndef OPENSSL_NO_RSA\n\tunsigned char *q;\n\tEVP_PKEY *pkey=NULL;\n#endif\n#ifndef OPENSSL_NO_KRB5\n\tKSSL_ERR kssl_err;\n#endif /* OPENSSL_NO_KRB5 */\n#ifndef OPENSSL_NO_ECDH\n\tEC_KEY *clnt_ecdh = NULL;\n\tconst EC_POINT *srvr_ecpoint = NULL;\n\tEVP_PKEY *srvr_pub_pkey = NULL;\n\tunsigned char *encodedPoint = NULL;\n\tint encoded_pt_len = 0;\n\tBN_CTX * bn_ctx = NULL;\n#endif\n\n\tif (s->state == SSL3_ST_CW_KEY_EXCH_A)\n\t\t{\n\t\td=(unsigned char *)s->init_buf->data;\n\t\tp= &(d[4]);\n\n\t\tl=s->s3->tmp.new_cipher->algorithms;\n\n\t\t/* Fool emacs indentation */\n\t\tif (0) {}\n#ifndef OPENSSL_NO_RSA\n\t\telse if (l & SSL_kRSA)\n\t\t\t{\n\t\t\tRSA *rsa;\n\t\t\tunsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];\n\n\t\t\tif (s->session->sess_cert->peer_rsa_tmp != NULL)\n\t\t\t\trsa=s->session->sess_cert->peer_rsa_tmp;\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n\t\t\t\tif ((pkey == NULL) ||\n\t\t\t\t\t(pkey->type != EVP_PKEY_RSA) ||\n\t\t\t\t\t(pkey->pkey.rsa == NULL))\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\t\t\t\trsa=pkey->pkey.rsa;\n\t\t\t\tEVP_PKEY_free(pkey);\n\t\t\t\t}\n\t\t\t\t\n\t\t\ttmp_buf[0]=s->client_version>>8;\n\t\t\ttmp_buf[1]=s->client_version&0xff;\n\t\t\tif (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)\n\t\t\t\t\tgoto err;\n\n\t\t\ts->session->master_key_length=sizeof tmp_buf;\n\n\t\t\tq=p;\n\t\t\t/* Fix buf for TLS and beyond */\n\t\t\tif (s->version > SSL3_VERSION)\n\t\t\t\tp+=2;\n\t\t\tn=RSA_public_encrypt(sizeof tmp_buf,\n\t\t\t\ttmp_buf,p,rsa,RSA_PKCS1_PADDING);\n#ifdef PKCS1_CHECK\n\t\t\tif (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;\n\t\t\tif (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;\n#endif\n\t\t\tif (n <= 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* Fix buf for TLS and beyond */\n\t\t\tif (s->version > SSL3_VERSION)\n\t\t\t\t{\n\t\t\t\ts2n(n,q);\n\t\t\t\tn+=2;\n\t\t\t\t}\n\n\t\t\ts->session->master_key_length=\n\t\t\t\ts->method->ssl3_enc->generate_master_secret(s,\n\t\t\t\t\ts->session->master_key,\n\t\t\t\t\ttmp_buf,sizeof tmp_buf);\n\t\t\tOPENSSL_cleanse(tmp_buf,sizeof tmp_buf);\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_KRB5\n\t\telse if (l & SSL_kKRB5)\n\t\t\t{\n\t\t\tkrb5_error_code\tkrb5rc;\n\t\t\tKSSL_CTX\t*kssl_ctx = s->kssl_ctx;\n\t\t\t/* krb5_data\tkrb5_ap_req; */\n\t\t\tkrb5_data\t*enc_ticket;\n\t\t\tkrb5_data\tauthenticator, *authp = NULL;\n\t\t\tEVP_CIPHER_CTX\tciph_ctx;\n\t\t\tEVP_CIPHER\t*enc = NULL;\n\t\t\tunsigned char\tiv[EVP_MAX_IV_LENGTH];\n\t\t\tunsigned char\ttmp_buf[SSL_MAX_MASTER_KEY_LENGTH];\n\t\t\tunsigned char\tepms[SSL_MAX_MASTER_KEY_LENGTH \n\t\t\t\t\t\t+ EVP_MAX_IV_LENGTH];\n\t\t\tint \t\tpadl, outl = sizeof(epms);\n\n\t\t\tEVP_CIPHER_CTX_init(&ciph_ctx);\n\n#ifdef KSSL_DEBUG\n\t\t\tprintf(\"ssl3_send_client_key_exchange(%lx & %lx)\\n\",\n\t\t\t l, SSL_kKRB5);\n#endif\t/* KSSL_DEBUG */\n\n\t\t\tauthp = NULL;\n#ifdef KRB5SENDAUTH\n\t\t\tif (KRB5SENDAUTH) authp = &authenticator;\n#endif\t/* KRB5SENDAUTH */\n\n\t\t\tkrb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,\n\t\t\t\t&kssl_err);\n\t\t\tenc = kssl_map_enc(kssl_ctx->enctype);\n\t\t\tif (enc == NULL)\n\t\t\t goto err;\n#ifdef KSSL_DEBUG\n\t\t\t{\n\t\t\tprintf(\"kssl_cget_tkt rtn %d\\n\", krb5rc);\n\t\t\tif (krb5rc && kssl_err.text)\n\t\t\t printf(\"kssl_cget_tkt kssl_err=%s\\n\", kssl_err.text);\n\t\t\t}\n#endif\t/* KSSL_DEBUG */\n\n\t\t\tif (krb5rc)\n\t\t\t\t{\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,\n\t\t\t\t\t\tSSL_AD_HANDSHAKE_FAILURE);\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,\n\t\t\t\t\t\tkssl_err.reason);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* 20010406 VRS - Earlier versions used KRB5 AP_REQ\n\t\t\t** in place of RFC 2712 KerberosWrapper, as in:\n\t\t\t**\n\t\t\t** Send ticket (copy to *p, set n = length)\n\t\t\t** n = krb5_ap_req.length;\n\t\t\t** memcpy(p, krb5_ap_req.data, krb5_ap_req.length);\n\t\t\t** if (krb5_ap_req.data) \n\t\t\t** kssl_krb5_free_data_contents(NULL,&krb5_ap_req);\n\t\t\t**\n\t\t\t** Now using real RFC 2712 KerberosWrapper\n\t\t\t** (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)\n\t\t\t** Note: 2712 \"opaque\" types are here replaced\n\t\t\t** with a 2-byte length followed by the value.\n\t\t\t** Example:\n\t\t\t** KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms\n\t\t\t** Where \"xx xx\" = length bytes. Shown here with\n\t\t\t** optional authenticator omitted.\n\t\t\t*/\n\n\t\t\t/* KerberosWrapper.Ticket\t\t*/\n\t\t\ts2n(enc_ticket->length,p);\n\t\t\tmemcpy(p, enc_ticket->data, enc_ticket->length);\n\t\t\tp+= enc_ticket->length;\n\t\t\tn = enc_ticket->length + 2;\n\n\t\t\t/* KerberosWrapper.Authenticator\t*/\n\t\t\tif (authp && authp->length) \n\t\t\t\t{\n\t\t\t\ts2n(authp->length,p);\n\t\t\t\tmemcpy(p, authp->data, authp->length);\n\t\t\t\tp+= authp->length;\n\t\t\t\tn+= authp->length + 2;\n\t\t\t\t\n\t\t\t\tfree(authp->data);\n\t\t\t\tauthp->data = NULL;\n\t\t\t\tauthp->length = 0;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\ts2n(0,p);/* null authenticator length\t*/\n\t\t\t\tn+=2;\n\t\t\t\t}\n \n\t\t\t tmp_buf[0]=s->client_version>>8;\n\t\t\t tmp_buf[1]=s->client_version&0xff;\n\t\t\t if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)\n\t\t\t\tgoto err;\n\n\t\t\t/* 20010420 VRS. Tried it this way; failed.\n\t\t\t**\tEVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);\n\t\t\t**\tEVP_CIPHER_CTX_set_key_length(&ciph_ctx,\n\t\t\t**\t\t\t\tkssl_ctx->length);\n\t\t\t**\tEVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);\n\t\t\t*/\n\n\t\t\tmemset(iv, 0, sizeof iv); /* per RFC 1510 */\n\t\t\tEVP_EncryptInit_ex(&ciph_ctx,enc, NULL,\n\t\t\t\tkssl_ctx->key,iv);\n\t\t\tEVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,\n\t\t\t\tsizeof tmp_buf);\n\t\t\tEVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);\n\t\t\toutl += padl;\n\t\t\tif (outl > sizeof epms)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tEVP_CIPHER_CTX_cleanup(&ciph_ctx);\n\n\t\t\t/* KerberosWrapper.EncryptedPreMasterSecret\t*/\n\t\t\ts2n(outl,p);\n\t\t\tmemcpy(p, epms, outl);\n\t\t\tp+=outl;\n\t\t\tn+=outl + 2;\n\n\t\t\ts->session->master_key_length=\n\t\t\t s->method->ssl3_enc->generate_master_secret(s,\n\t\t\t\t\ts->session->master_key,\n\t\t\t\t\ttmp_buf, sizeof tmp_buf);\n\n\t\t\tOPENSSL_cleanse(tmp_buf, sizeof tmp_buf);\n\t\t\tOPENSSL_cleanse(epms, outl);\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_DH\n\t\telse if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))\n\t\t\t{\n\t\t\tDH *dh_srvr,*dh_clnt;\n\n\t\t\tif (s->session->sess_cert == NULL) \n\t\t\t\t{\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);\n\t\t\t\tgoto err;\n\t\t\t }\n\n\t\t\tif (s->session->sess_cert->peer_dh_tmp != NULL)\n\t\t\t\tdh_srvr=s->session->sess_cert->peer_dh_tmp;\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t/* we get them from the cert */\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t\n\t\t\t/* generate a new random key */\n\t\t\tif ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tif (!DH_generate_key(dh_clnt))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* use the 'p' output buffer for the DH key, but\n\t\t\t * make sure to clear it out afterwards */\n\n\t\t\tn=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);\n\n\t\t\tif (n <= 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* generate master key from the result */\n\t\t\ts->session->master_key_length=\n\t\t\t\ts->method->ssl3_enc->generate_master_secret(s,\n\t\t\t\t\ts->session->master_key,p,n);\n\t\t\t/* clean up */\n\t\t\tmemset(p,0,n);\n\n\t\t\t/* send off the data */\n\t\t\tn=BN_num_bytes(dh_clnt->pub_key);\n\t\t\ts2n(n,p);\n\t\t\tBN_bn2bin(dh_clnt->pub_key,p);\n\t\t\tn+=2;\n\n\t\t\tDH_free(dh_clnt);\n\n\t\t\t/* perhaps clean things up a bit EAY EAY EAY EAY*/\n\t\t\t}\n#endif\n\n#ifndef OPENSSL_NO_ECDH \n\t\telse if ((l & SSL_kECDH) || (l & SSL_kECDHE))\n\t\t\t{\n\t\t\tconst EC_GROUP *srvr_group = NULL;\n\t\t\tEC_KEY *tkey;\n\t\t\tint ecdh_clnt_cert = 0;\n\t\t\tint field_size = 0;\n\n\t\t\t/* Did we send out the client's\n\t\t\t * ECDH share for use in premaster\n\t\t\t * computation as part of client certificate?\n\t\t\t * If so, set ecdh_clnt_cert to 1.\n\t\t\t */\n\t\t\tif ((l & SSL_kECDH) && (s->cert != NULL)) \n\t\t\t\t{\n\t\t\t\t/* XXX: For now, we do not support client\n\t\t\t\t * authentication using ECDH certificates.\n\t\t\t\t * To add such support, one needs to add\n\t\t\t\t * code that checks for appropriate \n\t\t\t\t * conditions and sets ecdh_clnt_cert to 1.\n\t\t\t\t * For example, the cert have an ECC\n\t\t\t\t * key on the same curve as the server's\n\t\t\t\t * and the key should be authorized for\n\t\t\t\t * key agreement.\n\t\t\t\t *\n\t\t\t\t * One also needs to add code in ssl3_connect\n\t\t\t\t * to skip sending the certificate verify\n\t\t\t\t * message.\n\t\t\t\t *\n\t\t\t\t * if ((s->cert->key->privatekey != NULL) &&\n\t\t\t\t * (s->cert->key->privatekey->type ==\n\t\t\t\t * EVP_PKEY_EC) && ...)\n\t\t\t\t * ecdh_clnt_cert = 1;\n\t\t\t\t */\n\t\t\t\t}\n\n\t\t\tif (s->session->sess_cert->peer_ecdh_tmp != NULL)\n\t\t\t\t{\n\t\t\t\ttkey = s->session->sess_cert->peer_ecdh_tmp;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t/* Get the Server Public Key from Cert */\n\t\t\t\tsrvr_pub_pkey = X509_get_pubkey(s->session-> \\\n\t\t\t\t sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);\n\t\t\t\tif ((srvr_pub_pkey == NULL) ||\n\t\t\t\t (srvr_pub_pkey->type != EVP_PKEY_EC) ||\n\t\t\t\t (srvr_pub_pkey->pkey.ec == NULL))\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,\n\t\t\t\t\t ERR_R_INTERNAL_ERROR);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\n\t\t\t\ttkey = srvr_pub_pkey->pkey.ec;\n\t\t\t\t}\n\n\t\t\tsrvr_group = EC_KEY_get0_group(tkey);\n\t\t\tsrvr_ecpoint = EC_KEY_get0_public_key(tkey);\n\n\t\t\tif ((srvr_group == NULL) || (srvr_ecpoint == NULL))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,\n\t\t\t\t ERR_R_INTERNAL_ERROR);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\tif ((clnt_ecdh=EC_KEY_new()) == NULL) \n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\tif (!EC_KEY_set_group(clnt_ecdh, srvr_group))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tif (ecdh_clnt_cert) \n\t\t\t\t{ \n\t\t\t\t/* Reuse key info from our certificate\n\t\t\t\t * We only need our private key to perform\n\t\t\t\t * the ECDH computation.\n\t\t\t\t */\n\t\t\t\tconst BIGNUM *priv_key;\n\t\t\t\ttkey = s->cert->key->privatekey->pkey.ec;\n\t\t\t\tpriv_key = EC_KEY_get0_private_key(tkey);\n\t\t\t\tif (priv_key == NULL)\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\t\t\t\tif (!EC_KEY_set_private_key(clnt_ecdh, priv_key))\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\telse \n\t\t\t\t{\n\t\t\t\t/* Generate a new ECDH key pair */\n\t\t\t\tif (!(EC_KEY_generate_key(clnt_ecdh)))\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t/* use the 'p' output buffer for the ECDH key, but\n\t\t\t * make sure to clear it out afterwards\n\t\t\t */\n\n\t\t\tfield_size = EC_GROUP_get_degree(srvr_group);\n\t\t\tif (field_size <= 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, \n\t\t\t\t ERR_R_ECDH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tn=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);\n\t\t\tif (n <= 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, \n\t\t\t\t ERR_R_ECDH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* generate master key from the result */\n\t\t\ts->session->master_key_length = s->method->ssl3_enc \\\n\t\t\t -> generate_master_secret(s, \n\t\t\t\ts->session->master_key,\n\t\t\t\tp, n);\n\n\t\t\tmemset(p, 0, n); /* clean up */\n\n\t\t\tif (ecdh_clnt_cert) \n\t\t\t\t{\n\t\t\t\t/* Send empty client key exch message */\n\t\t\t\tn = 0;\n\t\t\t\t}\n\t\t\telse \n\t\t\t\t{\n\t\t\t\t/* First check the size of encoding and\n\t\t\t\t * allocate memory accordingly.\n\t\t\t\t */\n\t\t\t\tencoded_pt_len = \n\t\t\t\t EC_POINT_point2oct(srvr_group, \n\t\t\t\t\tEC_KEY_get0_public_key(clnt_ecdh), \n\t\t\t\t\tPOINT_CONVERSION_UNCOMPRESSED, \n\t\t\t\t\tNULL, 0, NULL);\n\n\t\t\t\tencodedPoint = (unsigned char *) \n\t\t\t\t OPENSSL_malloc(encoded_pt_len * \n\t\t\t\t\tsizeof(unsigned char)); \n\t\t\t\tbn_ctx = BN_CTX_new();\n\t\t\t\tif ((encodedPoint == NULL) || \n\t\t\t\t (bn_ctx == NULL)) \n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\n\t\t\t\t/* Encode the public key */\n\t\t\t\tn = EC_POINT_point2oct(srvr_group, \n\t\t\t\t EC_KEY_get0_public_key(clnt_ecdh), \n\t\t\t\t POINT_CONVERSION_UNCOMPRESSED, \n\t\t\t\t encodedPoint, encoded_pt_len, bn_ctx);\n\n\t\t\t\t*p = n; /* length of encoded point */\n\t\t\t\t/* Encoded point will be copied here */\n\t\t\t\tp += 1; \n\t\t\t\t/* copy the point */\n\t\t\t\tmemcpy((unsigned char *)p, encodedPoint, n);\n\t\t\t\t/* increment n to account for length field */\n\t\t\t\tn += 1; \n\t\t\t\t}\n\n\t\t\t/* Free allocated memory */\n\t\t\tBN_CTX_free(bn_ctx);\n\t\t\tif (encodedPoint != NULL) OPENSSL_free(encodedPoint);\n\t\t\tif (clnt_ecdh != NULL) \n\t\t\t\t EC_KEY_free(clnt_ecdh);\n\t\t\tEVP_PKEY_free(srvr_pub_pkey);\n\t\t\t}\n#endif /* !OPENSSL_NO_ECDH */\n\t\telse\n\t\t\t{\n\t\t\tssl3_send_alert(s, SSL3_AL_FATAL,\n\t\t\t SSL_AD_HANDSHAKE_FAILURE);\n\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,\n\t\t\t ERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t\t}\n\t\t\n\t\t*(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;\n\t\tl2n3(n,d);\n\n\t\ts->state=SSL3_ST_CW_KEY_EXCH_B;\n\t\t/* number of bytes to write */\n\t\ts->init_num=n+4;\n\t\ts->init_off=0;\n\t\t}\n\n\t/* SSL3_ST_CW_KEY_EXCH_B */\n\treturn(ssl3_do_write(s,SSL3_RT_HANDSHAKE));\nerr:\n#ifndef OPENSSL_NO_ECDH\n\tBN_CTX_free(bn_ctx);\n\tif (encodedPoint != NULL) OPENSSL_free(encodedPoint);\n\tif (clnt_ecdh != NULL) \n\t\tEC_KEY_free(clnt_ecdh);\n\tEVP_PKEY_free(srvr_pub_pkey);\n#endif\n\treturn(-1);\n\t}", "target": 1, "cwe": ["CWE-476"], "project": "openssl", "commit_id": "141a5482fdd1944804cc342c1c443362eed8501b", "hash": 77229545539009014294689173951026139347, "size": 502, "message": "Fix CVE-2014-3470\n\nCheck session_cert is not NULL before dereferencing it.", "dataset": "other", "idx": 216368}
  1062. {"func": "int ssl3_send_client_key_exchange(SSL *s)\n\t{\n\tunsigned char *p,*d;\n\tint n;\n\tunsigned long l;\n#ifndef OPENSSL_NO_RSA\n\tunsigned char *q;\n\tEVP_PKEY *pkey=NULL;\n#endif\n#ifndef OPENSSL_NO_KRB5\n\tKSSL_ERR kssl_err;\n#endif /* OPENSSL_NO_KRB5 */\n#ifndef OPENSSL_NO_ECDH\n\tEC_KEY *clnt_ecdh = NULL;\n\tconst EC_POINT *srvr_ecpoint = NULL;\n\tEVP_PKEY *srvr_pub_pkey = NULL;\n\tunsigned char *encodedPoint = NULL;\n\tint encoded_pt_len = 0;\n\tBN_CTX * bn_ctx = NULL;\n#endif\n\n\tif (s->state == SSL3_ST_CW_KEY_EXCH_A)\n\t\t{\n\t\td=(unsigned char *)s->init_buf->data;\n\t\tp= &(d[4]);\n\n\t\tl=s->s3->tmp.new_cipher->algorithms;\n\n\t\t/* Fool emacs indentation */\n\t\tif (0) {}\n#ifndef OPENSSL_NO_RSA\n\t\telse if (l & SSL_kRSA)\n\t\t\t{\n\t\t\tRSA *rsa;\n\t\t\tunsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];\n\n\t\t\tif (s->session->sess_cert->peer_rsa_tmp != NULL)\n\t\t\t\trsa=s->session->sess_cert->peer_rsa_tmp;\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tpkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);\n\t\t\t\tif ((pkey == NULL) ||\n\t\t\t\t\t(pkey->type != EVP_PKEY_RSA) ||\n\t\t\t\t\t(pkey->pkey.rsa == NULL))\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\t\t\t\trsa=pkey->pkey.rsa;\n\t\t\t\tEVP_PKEY_free(pkey);\n\t\t\t\t}\n\t\t\t\t\n\t\t\ttmp_buf[0]=s->client_version>>8;\n\t\t\ttmp_buf[1]=s->client_version&0xff;\n\t\t\tif (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)\n\t\t\t\t\tgoto err;\n\n\t\t\ts->session->master_key_length=sizeof tmp_buf;\n\n\t\t\tq=p;\n\t\t\t/* Fix buf for TLS and beyond */\n\t\t\tif (s->version > SSL3_VERSION)\n\t\t\t\tp+=2;\n\t\t\tn=RSA_public_encrypt(sizeof tmp_buf,\n\t\t\t\ttmp_buf,p,rsa,RSA_PKCS1_PADDING);\n#ifdef PKCS1_CHECK\n\t\t\tif (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;\n\t\t\tif (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;\n#endif\n\t\t\tif (n <= 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* Fix buf for TLS and beyond */\n\t\t\tif (s->version > SSL3_VERSION)\n\t\t\t\t{\n\t\t\t\ts2n(n,q);\n\t\t\t\tn+=2;\n\t\t\t\t}\n\n\t\t\ts->session->master_key_length=\n\t\t\t\ts->method->ssl3_enc->generate_master_secret(s,\n\t\t\t\t\ts->session->master_key,\n\t\t\t\t\ttmp_buf,sizeof tmp_buf);\n\t\t\tOPENSSL_cleanse(tmp_buf,sizeof tmp_buf);\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_KRB5\n\t\telse if (l & SSL_kKRB5)\n\t\t\t{\n\t\t\tkrb5_error_code\tkrb5rc;\n\t\t\tKSSL_CTX\t*kssl_ctx = s->kssl_ctx;\n\t\t\t/* krb5_data\tkrb5_ap_req; */\n\t\t\tkrb5_data\t*enc_ticket;\n\t\t\tkrb5_data\tauthenticator, *authp = NULL;\n\t\t\tEVP_CIPHER_CTX\tciph_ctx;\n\t\t\tEVP_CIPHER\t*enc = NULL;\n\t\t\tunsigned char\tiv[EVP_MAX_IV_LENGTH];\n\t\t\tunsigned char\ttmp_buf[SSL_MAX_MASTER_KEY_LENGTH];\n\t\t\tunsigned char\tepms[SSL_MAX_MASTER_KEY_LENGTH \n\t\t\t\t\t\t+ EVP_MAX_IV_LENGTH];\n\t\t\tint \t\tpadl, outl = sizeof(epms);\n\n\t\t\tEVP_CIPHER_CTX_init(&ciph_ctx);\n\n#ifdef KSSL_DEBUG\n\t\t\tprintf(\"ssl3_send_client_key_exchange(%lx & %lx)\\n\",\n\t\t\t l, SSL_kKRB5);\n#endif\t/* KSSL_DEBUG */\n\n\t\t\tauthp = NULL;\n#ifdef KRB5SENDAUTH\n\t\t\tif (KRB5SENDAUTH) authp = &authenticator;\n#endif\t/* KRB5SENDAUTH */\n\n\t\t\tkrb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,\n\t\t\t\t&kssl_err);\n\t\t\tenc = kssl_map_enc(kssl_ctx->enctype);\n\t\t\tif (enc == NULL)\n\t\t\t goto err;\n#ifdef KSSL_DEBUG\n\t\t\t{\n\t\t\tprintf(\"kssl_cget_tkt rtn %d\\n\", krb5rc);\n\t\t\tif (krb5rc && kssl_err.text)\n\t\t\t printf(\"kssl_cget_tkt kssl_err=%s\\n\", kssl_err.text);\n\t\t\t}\n#endif\t/* KSSL_DEBUG */\n\n\t\t\tif (krb5rc)\n\t\t\t\t{\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,\n\t\t\t\t\t\tSSL_AD_HANDSHAKE_FAILURE);\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,\n\t\t\t\t\t\tkssl_err.reason);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* 20010406 VRS - Earlier versions used KRB5 AP_REQ\n\t\t\t** in place of RFC 2712 KerberosWrapper, as in:\n\t\t\t**\n\t\t\t** Send ticket (copy to *p, set n = length)\n\t\t\t** n = krb5_ap_req.length;\n\t\t\t** memcpy(p, krb5_ap_req.data, krb5_ap_req.length);\n\t\t\t** if (krb5_ap_req.data) \n\t\t\t** kssl_krb5_free_data_contents(NULL,&krb5_ap_req);\n\t\t\t**\n\t\t\t** Now using real RFC 2712 KerberosWrapper\n\t\t\t** (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)\n\t\t\t** Note: 2712 \"opaque\" types are here replaced\n\t\t\t** with a 2-byte length followed by the value.\n\t\t\t** Example:\n\t\t\t** KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms\n\t\t\t** Where \"xx xx\" = length bytes. Shown here with\n\t\t\t** optional authenticator omitted.\n\t\t\t*/\n\n\t\t\t/* KerberosWrapper.Ticket\t\t*/\n\t\t\ts2n(enc_ticket->length,p);\n\t\t\tmemcpy(p, enc_ticket->data, enc_ticket->length);\n\t\t\tp+= enc_ticket->length;\n\t\t\tn = enc_ticket->length + 2;\n\n\t\t\t/* KerberosWrapper.Authenticator\t*/\n\t\t\tif (authp && authp->length) \n\t\t\t\t{\n\t\t\t\ts2n(authp->length,p);\n\t\t\t\tmemcpy(p, authp->data, authp->length);\n\t\t\t\tp+= authp->length;\n\t\t\t\tn+= authp->length + 2;\n\t\t\t\t\n\t\t\t\tfree(authp->data);\n\t\t\t\tauthp->data = NULL;\n\t\t\t\tauthp->length = 0;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\ts2n(0,p);/* null authenticator length\t*/\n\t\t\t\tn+=2;\n\t\t\t\t}\n \n\t\t\t tmp_buf[0]=s->client_version>>8;\n\t\t\t tmp_buf[1]=s->client_version&0xff;\n\t\t\t if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)\n\t\t\t\tgoto err;\n\n\t\t\t/* 20010420 VRS. Tried it this way; failed.\n\t\t\t**\tEVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);\n\t\t\t**\tEVP_CIPHER_CTX_set_key_length(&ciph_ctx,\n\t\t\t**\t\t\t\tkssl_ctx->length);\n\t\t\t**\tEVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);\n\t\t\t*/\n\n\t\t\tmemset(iv, 0, sizeof iv); /* per RFC 1510 */\n\t\t\tEVP_EncryptInit_ex(&ciph_ctx,enc, NULL,\n\t\t\t\tkssl_ctx->key,iv);\n\t\t\tEVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,\n\t\t\t\tsizeof tmp_buf);\n\t\t\tEVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);\n\t\t\toutl += padl;\n\t\t\tif (outl > sizeof epms)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tEVP_CIPHER_CTX_cleanup(&ciph_ctx);\n\n\t\t\t/* KerberosWrapper.EncryptedPreMasterSecret\t*/\n\t\t\ts2n(outl,p);\n\t\t\tmemcpy(p, epms, outl);\n\t\t\tp+=outl;\n\t\t\tn+=outl + 2;\n\n\t\t\ts->session->master_key_length=\n\t\t\t s->method->ssl3_enc->generate_master_secret(s,\n\t\t\t\t\ts->session->master_key,\n\t\t\t\t\ttmp_buf, sizeof tmp_buf);\n\n\t\t\tOPENSSL_cleanse(tmp_buf, sizeof tmp_buf);\n\t\t\tOPENSSL_cleanse(epms, outl);\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_DH\n\t\telse if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))\n\t\t\t{\n\t\t\tDH *dh_srvr,*dh_clnt;\n\n\t\t\tif (s->session->sess_cert == NULL) \n\t\t\t\t{\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);\n\t\t\t\tgoto err;\n\t\t\t }\n\n\t\t\tif (s->session->sess_cert->peer_dh_tmp != NULL)\n\t\t\t\tdh_srvr=s->session->sess_cert->peer_dh_tmp;\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t/* we get them from the cert */\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t\n\t\t\t/* generate a new random key */\n\t\t\tif ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tif (!DH_generate_key(dh_clnt))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* use the 'p' output buffer for the DH key, but\n\t\t\t * make sure to clear it out afterwards */\n\n\t\t\tn=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);\n\n\t\t\tif (n <= 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* generate master key from the result */\n\t\t\ts->session->master_key_length=\n\t\t\t\ts->method->ssl3_enc->generate_master_secret(s,\n\t\t\t\t\ts->session->master_key,p,n);\n\t\t\t/* clean up */\n\t\t\tmemset(p,0,n);\n\n\t\t\t/* send off the data */\n\t\t\tn=BN_num_bytes(dh_clnt->pub_key);\n\t\t\ts2n(n,p);\n\t\t\tBN_bn2bin(dh_clnt->pub_key,p);\n\t\t\tn+=2;\n\n\t\t\tDH_free(dh_clnt);\n\n\t\t\t/* perhaps clean things up a bit EAY EAY EAY EAY*/\n\t\t\t}\n#endif\n\n#ifndef OPENSSL_NO_ECDH \n\t\telse if ((l & SSL_kECDH) || (l & SSL_kECDHE))\n\t\t\t{\n\t\t\tconst EC_GROUP *srvr_group = NULL;\n\t\t\tEC_KEY *tkey;\n\t\t\tint ecdh_clnt_cert = 0;\n\t\t\tint field_size = 0;\n\n\t\t\tif (s->session->sess_cert == NULL) \n\t\t\t\t{\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* Did we send out the client's\n\t\t\t * ECDH share for use in premaster\n\t\t\t * computation as part of client certificate?\n\t\t\t * If so, set ecdh_clnt_cert to 1.\n\t\t\t */\n\t\t\tif ((l & SSL_kECDH) && (s->cert != NULL)) \n\t\t\t\t{\n\t\t\t\t/* XXX: For now, we do not support client\n\t\t\t\t * authentication using ECDH certificates.\n\t\t\t\t * To add such support, one needs to add\n\t\t\t\t * code that checks for appropriate \n\t\t\t\t * conditions and sets ecdh_clnt_cert to 1.\n\t\t\t\t * For example, the cert have an ECC\n\t\t\t\t * key on the same curve as the server's\n\t\t\t\t * and the key should be authorized for\n\t\t\t\t * key agreement.\n\t\t\t\t *\n\t\t\t\t * One also needs to add code in ssl3_connect\n\t\t\t\t * to skip sending the certificate verify\n\t\t\t\t * message.\n\t\t\t\t *\n\t\t\t\t * if ((s->cert->key->privatekey != NULL) &&\n\t\t\t\t * (s->cert->key->privatekey->type ==\n\t\t\t\t * EVP_PKEY_EC) && ...)\n\t\t\t\t * ecdh_clnt_cert = 1;\n\t\t\t\t */\n\t\t\t\t}\n\n\t\t\tif (s->session->sess_cert->peer_ecdh_tmp != NULL)\n\t\t\t\t{\n\t\t\t\ttkey = s->session->sess_cert->peer_ecdh_tmp;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t/* Get the Server Public Key from Cert */\n\t\t\t\tsrvr_pub_pkey = X509_get_pubkey(s->session-> \\\n\t\t\t\t sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);\n\t\t\t\tif ((srvr_pub_pkey == NULL) ||\n\t\t\t\t (srvr_pub_pkey->type != EVP_PKEY_EC) ||\n\t\t\t\t (srvr_pub_pkey->pkey.ec == NULL))\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,\n\t\t\t\t\t ERR_R_INTERNAL_ERROR);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\n\t\t\t\ttkey = srvr_pub_pkey->pkey.ec;\n\t\t\t\t}\n\n\t\t\tsrvr_group = EC_KEY_get0_group(tkey);\n\t\t\tsrvr_ecpoint = EC_KEY_get0_public_key(tkey);\n\n\t\t\tif ((srvr_group == NULL) || (srvr_ecpoint == NULL))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,\n\t\t\t\t ERR_R_INTERNAL_ERROR);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\tif ((clnt_ecdh=EC_KEY_new()) == NULL) \n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\tif (!EC_KEY_set_group(clnt_ecdh, srvr_group))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tif (ecdh_clnt_cert) \n\t\t\t\t{ \n\t\t\t\t/* Reuse key info from our certificate\n\t\t\t\t * We only need our private key to perform\n\t\t\t\t * the ECDH computation.\n\t\t\t\t */\n\t\t\t\tconst BIGNUM *priv_key;\n\t\t\t\ttkey = s->cert->key->privatekey->pkey.ec;\n\t\t\t\tpriv_key = EC_KEY_get0_private_key(tkey);\n\t\t\t\tif (priv_key == NULL)\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\t\t\t\tif (!EC_KEY_set_private_key(clnt_ecdh, priv_key))\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\telse \n\t\t\t\t{\n\t\t\t\t/* Generate a new ECDH key pair */\n\t\t\t\tif (!(EC_KEY_generate_key(clnt_ecdh)))\n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t/* use the 'p' output buffer for the ECDH key, but\n\t\t\t * make sure to clear it out afterwards\n\t\t\t */\n\n\t\t\tfield_size = EC_GROUP_get_degree(srvr_group);\n\t\t\tif (field_size <= 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, \n\t\t\t\t ERR_R_ECDH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tn=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);\n\t\t\tif (n <= 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, \n\t\t\t\t ERR_R_ECDH_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\n\t\t\t/* generate master key from the result */\n\t\t\ts->session->master_key_length = s->method->ssl3_enc \\\n\t\t\t -> generate_master_secret(s, \n\t\t\t\ts->session->master_key,\n\t\t\t\tp, n);\n\n\t\t\tmemset(p, 0, n); /* clean up */\n\n\t\t\tif (ecdh_clnt_cert) \n\t\t\t\t{\n\t\t\t\t/* Send empty client key exch message */\n\t\t\t\tn = 0;\n\t\t\t\t}\n\t\t\telse \n\t\t\t\t{\n\t\t\t\t/* First check the size of encoding and\n\t\t\t\t * allocate memory accordingly.\n\t\t\t\t */\n\t\t\t\tencoded_pt_len = \n\t\t\t\t EC_POINT_point2oct(srvr_group, \n\t\t\t\t\tEC_KEY_get0_public_key(clnt_ecdh), \n\t\t\t\t\tPOINT_CONVERSION_UNCOMPRESSED, \n\t\t\t\t\tNULL, 0, NULL);\n\n\t\t\t\tencodedPoint = (unsigned char *) \n\t\t\t\t OPENSSL_malloc(encoded_pt_len * \n\t\t\t\t\tsizeof(unsigned char)); \n\t\t\t\tbn_ctx = BN_CTX_new();\n\t\t\t\tif ((encodedPoint == NULL) || \n\t\t\t\t (bn_ctx == NULL)) \n\t\t\t\t\t{\n\t\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);\n\t\t\t\t\tgoto err;\n\t\t\t\t\t}\n\n\t\t\t\t/* Encode the public key */\n\t\t\t\tn = EC_POINT_point2oct(srvr_group, \n\t\t\t\t EC_KEY_get0_public_key(clnt_ecdh), \n\t\t\t\t POINT_CONVERSION_UNCOMPRESSED, \n\t\t\t\t encodedPoint, encoded_pt_len, bn_ctx);\n\n\t\t\t\t*p = n; /* length of encoded point */\n\t\t\t\t/* Encoded point will be copied here */\n\t\t\t\tp += 1; \n\t\t\t\t/* copy the point */\n\t\t\t\tmemcpy((unsigned char *)p, encodedPoint, n);\n\t\t\t\t/* increment n to account for length field */\n\t\t\t\tn += 1; \n\t\t\t\t}\n\n\t\t\t/* Free allocated memory */\n\t\t\tBN_CTX_free(bn_ctx);\n\t\t\tif (encodedPoint != NULL) OPENSSL_free(encodedPoint);\n\t\t\tif (clnt_ecdh != NULL) \n\t\t\t\t EC_KEY_free(clnt_ecdh);\n\t\t\tEVP_PKEY_free(srvr_pub_pkey);\n\t\t\t}\n#endif /* !OPENSSL_NO_ECDH */\n\t\telse\n\t\t\t{\n\t\t\tssl3_send_alert(s, SSL3_AL_FATAL,\n\t\t\t SSL_AD_HANDSHAKE_FAILURE);\n\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,\n\t\t\t ERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t\t}\n\t\t\n\t\t*(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;\n\t\tl2n3(n,d);\n\n\t\ts->state=SSL3_ST_CW_KEY_EXCH_B;\n\t\t/* number of bytes to write */\n\t\ts->init_num=n+4;\n\t\ts->init_off=0;\n\t\t}\n\n\t/* SSL3_ST_CW_KEY_EXCH_B */\n\treturn(ssl3_do_write(s,SSL3_RT_HANDSHAKE));\nerr:\n#ifndef OPENSSL_NO_ECDH\n\tBN_CTX_free(bn_ctx);\n\tif (encodedPoint != NULL) OPENSSL_free(encodedPoint);\n\tif (clnt_ecdh != NULL) \n\t\tEC_KEY_free(clnt_ecdh);\n\tEVP_PKEY_free(srvr_pub_pkey);\n#endif\n\treturn(-1);\n\t}", "target": 0, "cwe": ["CWE-476"], "project": "openssl", "commit_id": "141a5482fdd1944804cc342c1c443362eed8501b", "hash": 226060406209456150787342782468227641903, "size": 509, "message": "Fix CVE-2014-3470\n\nCheck session_cert is not NULL before dereferencing it.", "dataset": "other", "idx": 501557}
  1063. {"func": "BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)\n{\n int i, j;\n BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;\n X509_ALGOR *xa;\n ASN1_OCTET_STRING *data_body = NULL;\n const EVP_MD *evp_md;\n const EVP_CIPHER *evp_cipher = NULL;\n EVP_CIPHER_CTX *evp_ctx = NULL;\n X509_ALGOR *enc_alg = NULL;\n STACK_OF(X509_ALGOR) *md_sk = NULL;\n STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;\n PKCS7_RECIP_INFO *ri = NULL;\n unsigned char *ek = NULL, *tkey = NULL;\n int eklen = 0, tkeylen = 0;\n\n if (p7 == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);\n return NULL;\n }\n\n if (p7->d.ptr == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);\n return NULL;\n }\n\n i = OBJ_obj2nid(p7->type);\n p7->state = PKCS7_S_HEADER;\n\n switch (i) {\n case NID_pkcs7_signed:\n data_body = PKCS7_get_octet_string(p7->d.sign->contents);\n if (!PKCS7_is_detached(p7) && data_body == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_INVALID_SIGNED_DATA_TYPE);\n goto err;\n }\n md_sk = p7->d.sign->md_algs;\n break;\n case NID_pkcs7_signedAndEnveloped:\n rsk = p7->d.signed_and_enveloped->recipientinfo;\n md_sk = p7->d.signed_and_enveloped->md_algs;\n data_body = p7->d.signed_and_enveloped->enc_data->enc_data;\n enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;\n evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);\n if (evp_cipher == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNSUPPORTED_CIPHER_TYPE);\n goto err;\n }\n break;\n case NID_pkcs7_enveloped:\n rsk = p7->d.enveloped->recipientinfo;\n enc_alg = p7->d.enveloped->enc_data->algorithm;\n data_body = p7->d.enveloped->enc_data->enc_data;\n evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);\n if (evp_cipher == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNSUPPORTED_CIPHER_TYPE);\n goto err;\n }\n break;\n default:\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);\n goto err;\n }\n\n /* We will be checking the signature */\n if (md_sk != NULL) {\n for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {\n xa = sk_X509_ALGOR_value(md_sk, i);\n if ((btmp = BIO_new(BIO_f_md())) == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);\n goto err;\n }\n\n j = OBJ_obj2nid(xa->algorithm);\n evp_md = EVP_get_digestbynid(j);\n if (evp_md == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNKNOWN_DIGEST_TYPE);\n goto err;\n }\n\n BIO_set_md(btmp, evp_md);\n if (out == NULL)\n out = btmp;\n else\n BIO_push(out, btmp);\n btmp = NULL;\n }\n }\n\n if (evp_cipher != NULL) {\n#if 0\n unsigned char key[EVP_MAX_KEY_LENGTH];\n unsigned char iv[EVP_MAX_IV_LENGTH];\n unsigned char *p;\n int keylen, ivlen;\n int max;\n X509_OBJECT ret;\n#endif\n\n if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);\n goto err;\n }\n\n /*\n * It was encrypted, we need to decrypt the secret key with the\n * private key\n */\n\n /*\n * Find the recipientInfo which matches the passed certificate (if\n * any)\n */\n\n if (pcert) {\n for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {\n ri = sk_PKCS7_RECIP_INFO_value(rsk, i);\n if (!pkcs7_cmp_ri(ri, pcert))\n break;\n ri = NULL;\n }\n if (ri == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);\n goto err;\n }\n }\n\n /* If we haven't got a certificate try each ri in turn */\n if (pcert == NULL) {\n /*\n * Always attempt to decrypt all rinfo even after sucess as a\n * defence against MMA timing attacks.\n */\n for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {\n ri = sk_PKCS7_RECIP_INFO_value(rsk, i);\n\n if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)\n goto err;\n ERR_clear_error();\n }\n } else {\n /* Only exit on fatal errors, not decrypt failure */\n if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)\n goto err;\n ERR_clear_error();\n }\n\n evp_ctx = NULL;\n BIO_get_cipher_ctx(etmp, &evp_ctx);\n if (EVP_CipherInit_ex(evp_ctx, evp_cipher, NULL, NULL, NULL, 0) <= 0)\n goto err;\n if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) < 0)\n goto err;\n /* Generate random key as MMA defence */\n tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);\n tkey = OPENSSL_malloc(tkeylen);\n if (!tkey)\n goto err;\n if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)\n goto err;\n if (ek == NULL) {\n ek = tkey;\n eklen = tkeylen;\n tkey = NULL;\n }\n\n if (eklen != EVP_CIPHER_CTX_key_length(evp_ctx)) {\n /*\n * Some S/MIME clients don't use the same key and effective key\n * length. The key length is determined by the size of the\n * decrypted RSA key.\n */\n if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen)) {\n /* Use random key as MMA defence */\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n ek = tkey;\n eklen = tkeylen;\n tkey = NULL;\n }\n }\n /* Clear errors so we don't leak information useful in MMA */\n ERR_clear_error();\n if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)\n goto err;\n\n if (ek) {\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n ek = NULL;\n }\n if (tkey) {\n OPENSSL_cleanse(tkey, tkeylen);\n OPENSSL_free(tkey);\n tkey = NULL;\n }\n\n if (out == NULL)\n out = etmp;\n else\n BIO_push(out, etmp);\n etmp = NULL;\n }\n#if 1\n if (PKCS7_is_detached(p7) || (in_bio != NULL)) {\n bio = in_bio;\n } else {\n# if 0\n bio = BIO_new(BIO_s_mem());\n /*\n * We need to set this so that when we have read all the data, the\n * encrypt BIO, if present, will read EOF and encode the last few\n * bytes\n */\n BIO_set_mem_eof_return(bio, 0);\n\n if (data_body->length > 0)\n BIO_write(bio, (char *)data_body->data, data_body->length);\n# else\n if (data_body->length > 0)\n bio = BIO_new_mem_buf(data_body->data, data_body->length);\n else {\n bio = BIO_new(BIO_s_mem());\n BIO_set_mem_eof_return(bio, 0);\n }\n if (bio == NULL)\n goto err;\n# endif\n }\n BIO_push(out, bio);\n bio = NULL;\n#endif\n if (0) {\n err:\n if (ek) {\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n }\n if (tkey) {\n OPENSSL_cleanse(tkey, tkeylen);\n OPENSSL_free(tkey);\n }\n if (out != NULL)\n BIO_free_all(out);\n if (btmp != NULL)\n BIO_free_all(btmp);\n if (etmp != NULL)\n BIO_free_all(etmp);\n if (bio != NULL)\n BIO_free_all(bio);\n out = NULL;\n }\n return (out);\n}", "target": 1, "cwe": [], "project": "openssl", "commit_id": "5fbc59cac60db4d7c3172152b8bdafe0c675fabd", "hash": 28643171687418372612575244617991130930, "size": 259, "message": "PKCS#7: Fix NULL dereference with missing EncryptedContent.\n\nCVE-2015-1790\n\nReviewed-by: Rich Salz <rsalz@openssl.org>", "dataset": "other", "idx": 216512}
  1064. {"func": "BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)\n{\n int i, j;\n BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;\n X509_ALGOR *xa;\n ASN1_OCTET_STRING *data_body = NULL;\n const EVP_MD *evp_md;\n const EVP_CIPHER *evp_cipher = NULL;\n EVP_CIPHER_CTX *evp_ctx = NULL;\n X509_ALGOR *enc_alg = NULL;\n STACK_OF(X509_ALGOR) *md_sk = NULL;\n STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;\n PKCS7_RECIP_INFO *ri = NULL;\n unsigned char *ek = NULL, *tkey = NULL;\n int eklen = 0, tkeylen = 0;\n\n if (p7 == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);\n return NULL;\n }\n\n if (p7->d.ptr == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);\n return NULL;\n }\n\n i = OBJ_obj2nid(p7->type);\n p7->state = PKCS7_S_HEADER;\n\n switch (i) {\n case NID_pkcs7_signed:\n /*\n * p7->d.sign->contents is a PKCS7 structure consisting of a contentType\n * field and optional content.\n * data_body is NULL if that structure has no (=detached) content\n * or if the contentType is wrong (i.e., not \"data\").\n */\n data_body = PKCS7_get_octet_string(p7->d.sign->contents);\n if (!PKCS7_is_detached(p7) && data_body == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_INVALID_SIGNED_DATA_TYPE);\n goto err;\n }\n md_sk = p7->d.sign->md_algs;\n break;\n case NID_pkcs7_signedAndEnveloped:\n rsk = p7->d.signed_and_enveloped->recipientinfo;\n md_sk = p7->d.signed_and_enveloped->md_algs;\n /* data_body is NULL if the optional EncryptedContent is missing. */\n data_body = p7->d.signed_and_enveloped->enc_data->enc_data;\n enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;\n evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);\n if (evp_cipher == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNSUPPORTED_CIPHER_TYPE);\n goto err;\n }\n break;\n case NID_pkcs7_enveloped:\n rsk = p7->d.enveloped->recipientinfo;\n enc_alg = p7->d.enveloped->enc_data->algorithm;\n /* data_body is NULL if the optional EncryptedContent is missing. */\n data_body = p7->d.enveloped->enc_data->enc_data;\n evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);\n if (evp_cipher == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNSUPPORTED_CIPHER_TYPE);\n goto err;\n }\n break;\n default:\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);\n goto err;\n }\n\n /* Detached content must be supplied via in_bio instead. */\n if (data_body == NULL && in_bio == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);\n goto err;\n }\n\n /* We will be checking the signature */\n if (md_sk != NULL) {\n for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {\n xa = sk_X509_ALGOR_value(md_sk, i);\n if ((btmp = BIO_new(BIO_f_md())) == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);\n goto err;\n }\n\n j = OBJ_obj2nid(xa->algorithm);\n evp_md = EVP_get_digestbynid(j);\n if (evp_md == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNKNOWN_DIGEST_TYPE);\n goto err;\n }\n\n BIO_set_md(btmp, evp_md);\n if (out == NULL)\n out = btmp;\n else\n BIO_push(out, btmp);\n btmp = NULL;\n }\n }\n\n if (evp_cipher != NULL) {\n#if 0\n unsigned char key[EVP_MAX_KEY_LENGTH];\n unsigned char iv[EVP_MAX_IV_LENGTH];\n unsigned char *p;\n int keylen, ivlen;\n int max;\n X509_OBJECT ret;\n#endif\n\n if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);\n goto err;\n }\n\n /*\n * It was encrypted, we need to decrypt the secret key with the\n * private key\n */\n\n /*\n * Find the recipientInfo which matches the passed certificate (if\n * any)\n */\n\n if (pcert) {\n for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {\n ri = sk_PKCS7_RECIP_INFO_value(rsk, i);\n if (!pkcs7_cmp_ri(ri, pcert))\n break;\n ri = NULL;\n }\n if (ri == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);\n goto err;\n }\n }\n\n /* If we haven't got a certificate try each ri in turn */\n if (pcert == NULL) {\n /*\n * Always attempt to decrypt all rinfo even after sucess as a\n * defence against MMA timing attacks.\n */\n for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {\n ri = sk_PKCS7_RECIP_INFO_value(rsk, i);\n\n if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)\n goto err;\n ERR_clear_error();\n }\n } else {\n /* Only exit on fatal errors, not decrypt failure */\n if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)\n goto err;\n ERR_clear_error();\n }\n\n evp_ctx = NULL;\n BIO_get_cipher_ctx(etmp, &evp_ctx);\n if (EVP_CipherInit_ex(evp_ctx, evp_cipher, NULL, NULL, NULL, 0) <= 0)\n goto err;\n if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) < 0)\n goto err;\n /* Generate random key as MMA defence */\n tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);\n tkey = OPENSSL_malloc(tkeylen);\n if (!tkey)\n goto err;\n if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)\n goto err;\n if (ek == NULL) {\n ek = tkey;\n eklen = tkeylen;\n tkey = NULL;\n }\n\n if (eklen != EVP_CIPHER_CTX_key_length(evp_ctx)) {\n /*\n * Some S/MIME clients don't use the same key and effective key\n * length. The key length is determined by the size of the\n * decrypted RSA key.\n */\n if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen)) {\n /* Use random key as MMA defence */\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n ek = tkey;\n eklen = tkeylen;\n tkey = NULL;\n }\n }\n /* Clear errors so we don't leak information useful in MMA */\n ERR_clear_error();\n if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)\n goto err;\n\n if (ek) {\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n ek = NULL;\n }\n if (tkey) {\n OPENSSL_cleanse(tkey, tkeylen);\n OPENSSL_free(tkey);\n tkey = NULL;\n }\n\n if (out == NULL)\n out = etmp;\n else\n BIO_push(out, etmp);\n etmp = NULL;\n }\n#if 1\n if (in_bio != NULL) {\n bio = in_bio;\n } else {\n# if 0\n bio = BIO_new(BIO_s_mem());\n /*\n * We need to set this so that when we have read all the data, the\n * encrypt BIO, if present, will read EOF and encode the last few\n * bytes\n */\n BIO_set_mem_eof_return(bio, 0);\n\n if (data_body->length > 0)\n BIO_write(bio, (char *)data_body->data, data_body->length);\n# else\n if (data_body->length > 0)\n bio = BIO_new_mem_buf(data_body->data, data_body->length);\n else {\n bio = BIO_new(BIO_s_mem());\n BIO_set_mem_eof_return(bio, 0);\n }\n if (bio == NULL)\n goto err;\n# endif\n }\n BIO_push(out, bio);\n bio = NULL;\n#endif\n if (0) {\n err:\n if (ek) {\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n }\n if (tkey) {\n OPENSSL_cleanse(tkey, tkeylen);\n OPENSSL_free(tkey);\n }\n if (out != NULL)\n BIO_free_all(out);\n if (btmp != NULL)\n BIO_free_all(btmp);\n if (etmp != NULL)\n BIO_free_all(etmp);\n if (bio != NULL)\n BIO_free_all(bio);\n out = NULL;\n }\n return (out);\n}", "target": 0, "cwe": [], "project": "openssl", "commit_id": "5fbc59cac60db4d7c3172152b8bdafe0c675fabd", "hash": 162832984232169353223754051711762414456, "size": 273, "message": "PKCS#7: Fix NULL dereference with missing EncryptedContent.\n\nCVE-2015-1790\n\nReviewed-by: Rich Salz <rsalz@openssl.org>", "dataset": "other", "idx": 502658}
  1065. {"func": "int X509_verify_cert(X509_STORE_CTX *ctx)\n{\n X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;\n int bad_chain = 0;\n X509_VERIFY_PARAM *param = ctx->param;\n int depth, i, ok = 0;\n int num, j, retry;\n int (*cb) (int xok, X509_STORE_CTX *xctx);\n STACK_OF(X509) *sktmp = NULL;\n if (ctx->cert == NULL) {\n X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);\n return -1;\n }\n if (ctx->chain != NULL) {\n /*\n * This X509_STORE_CTX has already been used to verify a cert. We\n * cannot do another one.\n */\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);\n return -1;\n }\n\n cb = ctx->verify_cb;\n\n /*\n * first we make sure the chain we are going to build is present and that\n * the first entry is in place\n */\n if (((ctx->chain = sk_X509_new_null()) == NULL) ||\n (!sk_X509_push(ctx->chain, ctx->cert))) {\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);\n goto end;\n }\n CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);\n ctx->last_untrusted = 1;\n\n /* We use a temporary STACK so we can chop and hack at it */\n if (ctx->untrusted != NULL\n && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);\n goto end;\n }\n\n num = sk_X509_num(ctx->chain);\n x = sk_X509_value(ctx->chain, num - 1);\n depth = param->depth;\n\n for (;;) {\n /* If we have enough, we break */\n if (depth < num)\n break; /* FIXME: If this happens, we should take\n * note of it and, if appropriate, use the\n * X509_V_ERR_CERT_CHAIN_TOO_LONG error code\n * later. */\n\n /* If we are self signed, we break */\n if (ctx->check_issued(ctx, x, x))\n break;\n\n /* If we were passed a cert chain, use it first */\n if (ctx->untrusted != NULL) {\n xtmp = find_issuer(ctx, sktmp, x);\n if (xtmp != NULL) {\n if (!sk_X509_push(ctx->chain, xtmp)) {\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);\n goto end;\n }\n CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);\n (void)sk_X509_delete_ptr(sktmp, xtmp);\n ctx->last_untrusted++;\n x = xtmp;\n num++;\n /*\n * reparse the full chain for the next one\n */\n continue;\n }\n }\n break;\n }\n\n /* Remember how many untrusted certs we have */\n j = num;\n /*\n * at this point, chain should contain a list of untrusted certificates.\n * We now need to add at least one trusted one, if possible, otherwise we\n * complain.\n */\n\n do {\n /*\n * Examine last certificate in chain and see if it is self signed.\n */\n i = sk_X509_num(ctx->chain);\n x = sk_X509_value(ctx->chain, i - 1);\n if (ctx->check_issued(ctx, x, x)) {\n /* we have a self signed certificate */\n if (sk_X509_num(ctx->chain) == 1) {\n /*\n * We have a single self signed certificate: see if we can\n * find it in the store. We must have an exact match to avoid\n * possible impersonation.\n */\n ok = ctx->get_issuer(&xtmp, ctx, x);\n if ((ok <= 0) || X509_cmp(x, xtmp)) {\n ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;\n ctx->current_cert = x;\n ctx->error_depth = i - 1;\n if (ok == 1)\n X509_free(xtmp);\n bad_chain = 1;\n ok = cb(0, ctx);\n if (!ok)\n goto end;\n } else {\n /*\n * We have a match: replace certificate with store\n * version so we get any trust settings.\n */\n X509_free(x);\n x = xtmp;\n (void)sk_X509_set(ctx->chain, i - 1, x);\n ctx->last_untrusted = 0;\n }\n } else {\n /*\n * extract and save self signed certificate for later use\n */\n chain_ss = sk_X509_pop(ctx->chain);\n ctx->last_untrusted--;\n num--;\n j--;\n x = sk_X509_value(ctx->chain, num - 1);\n }\n }\n /* We now lookup certs from the certificate store */\n for (;;) {\n /* If we have enough, we break */\n if (depth < num)\n break;\n /* If we are self signed, we break */\n if (ctx->check_issued(ctx, x, x))\n break;\n ok = ctx->get_issuer(&xtmp, ctx, x);\n if (ok < 0)\n return ok;\n if (ok == 0)\n break;\n x = xtmp;\n if (!sk_X509_push(ctx->chain, x)) {\n X509_free(xtmp);\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);\n return 0;\n }\n num++;\n }\n\n /*\n * If we haven't got a least one certificate from our store then check\n * if there is an alternative chain that could be used. We only do this\n * if the user hasn't switched off alternate chain checking\n */\n retry = 0;\n if (j == ctx->last_untrusted &&\n !(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {\n while (j-- > 1) {\n xtmp2 = sk_X509_value(ctx->chain, j - 1);\n ok = ctx->get_issuer(&xtmp, ctx, xtmp2);\n if (ok < 0)\n goto end;\n /* Check if we found an alternate chain */\n if (ok > 0) {\n /*\n * Free up the found cert we'll add it again later\n */\n X509_free(xtmp);\n\n /*\n * Dump all the certs above this point - we've found an\n * alternate chain\n */\n while (num > j) {\n xtmp = sk_X509_pop(ctx->chain);\n X509_free(xtmp);\n num--;\n }\n ctx->last_untrusted = sk_X509_num(ctx->chain);\n retry = 1;\n break;\n }\n }\n }\n } while (retry);\n\n /* Is last certificate looked up self signed? */\n if (!ctx->check_issued(ctx, x, x)) {\n if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {\n if (ctx->last_untrusted >= num)\n ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;\n else\n ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;\n ctx->current_cert = x;\n } else {\n\n sk_X509_push(ctx->chain, chain_ss);\n num++;\n ctx->last_untrusted = num;\n ctx->current_cert = chain_ss;\n ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;\n chain_ss = NULL;\n }\n\n ctx->error_depth = num - 1;\n bad_chain = 1;\n ok = cb(0, ctx);\n if (!ok)\n goto end;\n }\n\n /* We have the chain complete: now we need to check its purpose */\n ok = check_chain_extensions(ctx);\n\n if (!ok)\n goto end;\n\n /* Check name constraints */\n\n ok = check_name_constraints(ctx);\n\n if (!ok)\n goto end;\n\n /* The chain extensions are OK: check trust */\n\n if (param->trust > 0)\n ok = check_trust(ctx);\n\n if (!ok)\n goto end;\n\n /* We may as well copy down any DSA parameters that are required */\n X509_get_pubkey_parameters(NULL, ctx->chain);\n\n /*\n * Check revocation status: we do this after copying parameters because\n * they may be needed for CRL signature verification.\n */\n\n ok = ctx->check_revocation(ctx);\n if (!ok)\n goto end;\n\n /* At this point, we have a chain and need to verify it */\n if (ctx->verify != NULL)\n ok = ctx->verify(ctx);\n else\n ok = internal_verify(ctx);\n if (!ok)\n goto end;\n\n#ifndef OPENSSL_NO_RFC3779\n /* RFC 3779 path validation, now that CRL check has been done */\n ok = v3_asid_validate_path(ctx);\n if (!ok)\n goto end;\n ok = v3_addr_validate_path(ctx);\n if (!ok)\n goto end;\n#endif\n\n /* If we get this far evaluate policies */\n if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))\n ok = ctx->check_policy(ctx);\n if (!ok)\n goto end;\n if (0) {\n end:\n X509_get_pubkey_parameters(NULL, ctx->chain);\n }\n if (sktmp != NULL)\n sk_X509_free(sktmp);\n if (chain_ss != NULL)\n X509_free(chain_ss);\n return ok;\n}", "target": 1, "cwe": ["CWE-254"], "project": "openssl", "commit_id": "cb22d2ae5a5b6069dbf66dbcce07223ac15a16de", "hash": 157510682266880135227270063780618680419, "size": 285, "message": "Fix alt chains bug\n\nThis is a follow up to the alternate chains certificate forgery issue\n(CVE-2015-1793). That issue is exacerbated in 1.0.1 by a related bug which\nmeans that we *always* check for an alternative chain, even if we have\nalready found a chain. The code is supposed to stop as soon as it has found\none (and does do in master and 1.0.2).\n\nReviewed-by: Stephen Henson <steve@openssl.org>", "dataset": "other", "idx": 216521}
  1066. {"func": "int X509_verify_cert(X509_STORE_CTX *ctx)\n{\n X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;\n int bad_chain = 0;\n X509_VERIFY_PARAM *param = ctx->param;\n int depth, i, ok = 0;\n int num, j, retry;\n int (*cb) (int xok, X509_STORE_CTX *xctx);\n STACK_OF(X509) *sktmp = NULL;\n if (ctx->cert == NULL) {\n X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);\n return -1;\n }\n if (ctx->chain != NULL) {\n /*\n * This X509_STORE_CTX has already been used to verify a cert. We\n * cannot do another one.\n */\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);\n return -1;\n }\n\n cb = ctx->verify_cb;\n\n /*\n * first we make sure the chain we are going to build is present and that\n * the first entry is in place\n */\n if (((ctx->chain = sk_X509_new_null()) == NULL) ||\n (!sk_X509_push(ctx->chain, ctx->cert))) {\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);\n goto end;\n }\n CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);\n ctx->last_untrusted = 1;\n\n /* We use a temporary STACK so we can chop and hack at it */\n if (ctx->untrusted != NULL\n && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);\n goto end;\n }\n\n num = sk_X509_num(ctx->chain);\n x = sk_X509_value(ctx->chain, num - 1);\n depth = param->depth;\n\n for (;;) {\n /* If we have enough, we break */\n if (depth < num)\n break; /* FIXME: If this happens, we should take\n * note of it and, if appropriate, use the\n * X509_V_ERR_CERT_CHAIN_TOO_LONG error code\n * later. */\n\n /* If we are self signed, we break */\n if (ctx->check_issued(ctx, x, x))\n break;\n\n /* If we were passed a cert chain, use it first */\n if (ctx->untrusted != NULL) {\n xtmp = find_issuer(ctx, sktmp, x);\n if (xtmp != NULL) {\n if (!sk_X509_push(ctx->chain, xtmp)) {\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);\n goto end;\n }\n CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);\n (void)sk_X509_delete_ptr(sktmp, xtmp);\n ctx->last_untrusted++;\n x = xtmp;\n num++;\n /*\n * reparse the full chain for the next one\n */\n continue;\n }\n }\n break;\n }\n\n /* Remember how many untrusted certs we have */\n j = num;\n /*\n * at this point, chain should contain a list of untrusted certificates.\n * We now need to add at least one trusted one, if possible, otherwise we\n * complain.\n */\n\n do {\n /*\n * Examine last certificate in chain and see if it is self signed.\n */\n i = sk_X509_num(ctx->chain);\n x = sk_X509_value(ctx->chain, i - 1);\n if (ctx->check_issued(ctx, x, x)) {\n /* we have a self signed certificate */\n if (sk_X509_num(ctx->chain) == 1) {\n /*\n * We have a single self signed certificate: see if we can\n * find it in the store. We must have an exact match to avoid\n * possible impersonation.\n */\n ok = ctx->get_issuer(&xtmp, ctx, x);\n if ((ok <= 0) || X509_cmp(x, xtmp)) {\n ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;\n ctx->current_cert = x;\n ctx->error_depth = i - 1;\n if (ok == 1)\n X509_free(xtmp);\n bad_chain = 1;\n ok = cb(0, ctx);\n if (!ok)\n goto end;\n } else {\n /*\n * We have a match: replace certificate with store\n * version so we get any trust settings.\n */\n X509_free(x);\n x = xtmp;\n (void)sk_X509_set(ctx->chain, i - 1, x);\n ctx->last_untrusted = 0;\n }\n } else {\n /*\n * extract and save self signed certificate for later use\n */\n chain_ss = sk_X509_pop(ctx->chain);\n ctx->last_untrusted--;\n num--;\n j--;\n x = sk_X509_value(ctx->chain, num - 1);\n }\n }\n /* We now lookup certs from the certificate store */\n for (;;) {\n /* If we have enough, we break */\n if (depth < num)\n break;\n /* If we are self signed, we break */\n if (ctx->check_issued(ctx, x, x))\n break;\n ok = ctx->get_issuer(&xtmp, ctx, x);\n if (ok < 0)\n return ok;\n if (ok == 0)\n break;\n x = xtmp;\n if (!sk_X509_push(ctx->chain, x)) {\n X509_free(xtmp);\n X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);\n return 0;\n }\n num++;\n }\n\n /*\n * If we haven't got a least one certificate from our store then check\n * if there is an alternative chain that could be used. We only do this\n * if the user hasn't switched off alternate chain checking\n */\n retry = 0;\n if (num == ctx->last_untrusted &&\n !(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {\n while (j-- > 1) {\n xtmp2 = sk_X509_value(ctx->chain, j - 1);\n ok = ctx->get_issuer(&xtmp, ctx, xtmp2);\n if (ok < 0)\n goto end;\n /* Check if we found an alternate chain */\n if (ok > 0) {\n /*\n * Free up the found cert we'll add it again later\n */\n X509_free(xtmp);\n\n /*\n * Dump all the certs above this point - we've found an\n * alternate chain\n */\n while (num > j) {\n xtmp = sk_X509_pop(ctx->chain);\n X509_free(xtmp);\n num--;\n }\n ctx->last_untrusted = sk_X509_num(ctx->chain);\n retry = 1;\n break;\n }\n }\n }\n } while (retry);\n\n /* Is last certificate looked up self signed? */\n if (!ctx->check_issued(ctx, x, x)) {\n if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {\n if (ctx->last_untrusted >= num)\n ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;\n else\n ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;\n ctx->current_cert = x;\n } else {\n\n sk_X509_push(ctx->chain, chain_ss);\n num++;\n ctx->last_untrusted = num;\n ctx->current_cert = chain_ss;\n ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;\n chain_ss = NULL;\n }\n\n ctx->error_depth = num - 1;\n bad_chain = 1;\n ok = cb(0, ctx);\n if (!ok)\n goto end;\n }\n\n /* We have the chain complete: now we need to check its purpose */\n ok = check_chain_extensions(ctx);\n\n if (!ok)\n goto end;\n\n /* Check name constraints */\n\n ok = check_name_constraints(ctx);\n\n if (!ok)\n goto end;\n\n /* The chain extensions are OK: check trust */\n\n if (param->trust > 0)\n ok = check_trust(ctx);\n\n if (!ok)\n goto end;\n\n /* We may as well copy down any DSA parameters that are required */\n X509_get_pubkey_parameters(NULL, ctx->chain);\n\n /*\n * Check revocation status: we do this after copying parameters because\n * they may be needed for CRL signature verification.\n */\n\n ok = ctx->check_revocation(ctx);\n if (!ok)\n goto end;\n\n /* At this point, we have a chain and need to verify it */\n if (ctx->verify != NULL)\n ok = ctx->verify(ctx);\n else\n ok = internal_verify(ctx);\n if (!ok)\n goto end;\n\n#ifndef OPENSSL_NO_RFC3779\n /* RFC 3779 path validation, now that CRL check has been done */\n ok = v3_asid_validate_path(ctx);\n if (!ok)\n goto end;\n ok = v3_addr_validate_path(ctx);\n if (!ok)\n goto end;\n#endif\n\n /* If we get this far evaluate policies */\n if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))\n ok = ctx->check_policy(ctx);\n if (!ok)\n goto end;\n if (0) {\n end:\n X509_get_pubkey_parameters(NULL, ctx->chain);\n }\n if (sktmp != NULL)\n sk_X509_free(sktmp);\n if (chain_ss != NULL)\n X509_free(chain_ss);\n return ok;\n}", "target": 0, "cwe": ["CWE-254"], "project": "openssl", "commit_id": "cb22d2ae5a5b6069dbf66dbcce07223ac15a16de", "hash": 142820662815600028556509579005056804595, "size": 285, "message": "Fix alt chains bug\n\nThis is a follow up to the alternate chains certificate forgery issue\n(CVE-2015-1793). That issue is exacerbated in 1.0.1 by a related bug which\nmeans that we *always* check for an alternative chain, even if we have\nalready found a chain. The code is supposed to stop as soon as it has found\none (and does do in master and 1.0.2).\n\nReviewed-by: Stephen Henson <steve@openssl.org>", "dataset": "other", "idx": 502765}
  1067. {"func": "int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,\n int len, int peek)\n{\n int al, i, j, ret;\n unsigned int n, curr_rec, num_recs, read_bytes;\n SSL3_RECORD *rr;\n SSL3_BUFFER *rbuf;\n void (*cb) (const SSL *ssl, int type2, int val) = NULL;\n\n rbuf = &s->rlayer.rbuf;\n\n if (!SSL3_BUFFER_is_initialised(rbuf)) {\n /* Not initialized yet */\n if (!ssl3_setup_read_buffer(s))\n return (-1);\n }\n\n if ((type && (type != SSL3_RT_APPLICATION_DATA)\n && (type != SSL3_RT_HANDSHAKE)) || (peek\n && (type !=\n SSL3_RT_APPLICATION_DATA))) {\n SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n return -1;\n }\n\n if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))\n /* (partially) satisfy request from storage */\n {\n unsigned char *src = s->rlayer.handshake_fragment;\n unsigned char *dst = buf;\n unsigned int k;\n\n /* peek == 0 */\n n = 0;\n while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {\n *dst++ = *src++;\n len--;\n s->rlayer.handshake_fragment_len--;\n n++;\n }\n /* move any remaining fragment bytes: */\n for (k = 0; k < s->rlayer.handshake_fragment_len; k++)\n s->rlayer.handshake_fragment[k] = *src++;\n\n if (recvd_type != NULL)\n *recvd_type = SSL3_RT_HANDSHAKE;\n\n return n;\n }\n\n /*\n * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.\n */\n\n if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {\n /* type == SSL3_RT_APPLICATION_DATA */\n i = s->handshake_func(s);\n if (i < 0)\n return (i);\n if (i == 0) {\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);\n return (-1);\n }\n }\n start:\n s->rwstate = SSL_NOTHING;\n\n /*-\n * For each record 'i' up to |num_recs]\n * rr[i].type - is the type of record\n * rr[i].data, - data\n * rr[i].off, - offset into 'data' for next read\n * rr[i].length, - number of bytes.\n */\n rr = s->rlayer.rrec;\n num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);\n\n do {\n /* get new records if necessary */\n if (num_recs == 0) {\n ret = ssl3_get_record(s);\n if (ret <= 0)\n return (ret);\n num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);\n if (num_recs == 0) {\n /* Shouldn't happen */\n al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n goto f_err;\n }\n }\n /* Skip over any records we have already read */\n for (curr_rec = 0;\n curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);\n curr_rec++) ;\n if (curr_rec == num_recs) {\n RECORD_LAYER_set_numrpipes(&s->rlayer, 0);\n num_recs = 0;\n curr_rec = 0;\n }\n } while (num_recs == 0);\n rr = &rr[curr_rec];\n\n /*\n * Reset the count of consecutive warning alerts if we've got a non-empty\n * record that isn't an alert.\n */\n if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT\n && SSL3_RECORD_get_length(rr) != 0)\n s->rlayer.alert_count = 0;\n\n /* we now have a packet which can be read and processed */\n\n if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,\n * reset by ssl3_get_finished */\n && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);\n goto f_err;\n }\n\n /*\n * If the other end has shut down, throw anything we read away (even in\n * 'peek' mode)\n */\n if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {\n SSL3_RECORD_set_length(rr, 0);\n s->rwstate = SSL_NOTHING;\n return (0);\n }\n\n if (type == SSL3_RECORD_get_type(rr)\n || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC\n && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {\n /*\n * SSL3_RT_APPLICATION_DATA or\n * SSL3_RT_HANDSHAKE or\n * SSL3_RT_CHANGE_CIPHER_SPEC\n */\n /*\n * make sure that we are not getting application data when we are\n * doing a handshake for the first time\n */\n if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&\n (s->enc_read_ctx == NULL)) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);\n goto f_err;\n }\n\n if (type == SSL3_RT_HANDSHAKE\n && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC\n && s->rlayer.handshake_fragment_len > 0) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);\n goto f_err;\n }\n\n if (recvd_type != NULL)\n *recvd_type = SSL3_RECORD_get_type(rr);\n\n if (len <= 0)\n return (len);\n\n read_bytes = 0;\n do {\n if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))\n n = SSL3_RECORD_get_length(rr);\n else\n n = (unsigned int)len - read_bytes;\n\n memcpy(buf, &(rr->data[rr->off]), n);\n buf += n;\n if (!peek) {\n SSL3_RECORD_sub_length(rr, n);\n SSL3_RECORD_add_off(rr, n);\n if (SSL3_RECORD_get_length(rr) == 0) {\n s->rlayer.rstate = SSL_ST_READ_HEADER;\n SSL3_RECORD_set_off(rr, 0);\n SSL3_RECORD_set_read(rr);\n }\n }\n if (SSL3_RECORD_get_length(rr) == 0\n || (peek && n == SSL3_RECORD_get_length(rr))) {\n curr_rec++;\n rr++;\n }\n read_bytes += n;\n } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs\n && read_bytes < (unsigned int)len);\n if (read_bytes == 0) {\n /* We must have read empty records. Get more data */\n goto start;\n }\n if (!peek && curr_rec == num_recs\n && (s->mode & SSL_MODE_RELEASE_BUFFERS)\n && SSL3_BUFFER_get_left(rbuf) == 0)\n ssl3_release_read_buffer(s);\n return read_bytes;\n }\n\n /*\n * If we get here, then type != rr->type; if we have a handshake message,\n * then it was unexpected (Hello Request or Client Hello) or invalid (we\n * were actually expecting a CCS).\n */\n\n /*\n * Lets just double check that we've not got an SSLv2 record\n */\n if (rr->rec_version == SSL2_VERSION) {\n /*\n * Should never happen. ssl3_get_record() should only give us an SSLv2\n * record back if this is the first packet and we are looking for an\n * initial ClientHello. Therefore |type| should always be equal to\n * |rr->type|. If not then something has gone horribly wrong\n */\n al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n goto f_err;\n }\n\n if (s->method->version == TLS_ANY_VERSION\n && (s->server || rr->type != SSL3_RT_ALERT)) {\n /*\n * If we've got this far and still haven't decided on what version\n * we're using then this must be a client side alert we're dealing with\n * (we don't allow heartbeats yet). We shouldn't be receiving anything\n * other than a ClientHello if we are a server.\n */\n s->version = rr->rec_version;\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);\n goto f_err;\n }\n\n /*\n * In case of record types for which we have 'fragment' storage, fill\n * that so that we can process the data at a fixed place.\n */\n {\n unsigned int dest_maxlen = 0;\n unsigned char *dest = NULL;\n unsigned int *dest_len = NULL;\n\n if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {\n dest_maxlen = sizeof s->rlayer.handshake_fragment;\n dest = s->rlayer.handshake_fragment;\n dest_len = &s->rlayer.handshake_fragment_len;\n } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {\n dest_maxlen = sizeof s->rlayer.alert_fragment;\n dest = s->rlayer.alert_fragment;\n dest_len = &s->rlayer.alert_fragment_len;\n }\n\n if (dest_maxlen > 0) {\n n = dest_maxlen - *dest_len; /* available space in 'dest' */\n if (SSL3_RECORD_get_length(rr) < n)\n n = SSL3_RECORD_get_length(rr); /* available bytes */\n\n /* now move 'n' bytes: */\n while (n-- > 0) {\n dest[(*dest_len)++] =\n SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];\n SSL3_RECORD_add_off(rr, 1);\n SSL3_RECORD_add_length(rr, -1);\n }\n\n if (*dest_len < dest_maxlen) {\n SSL3_RECORD_set_read(rr);\n goto start; /* fragment was too small */\n }\n }\n }\n\n /*-\n * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;\n * s->rlayer.alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.\n * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)\n */\n\n /* If we are a client, check for an incoming 'Hello Request': */\n if ((!s->server) &&\n (s->rlayer.handshake_fragment_len >= 4) &&\n (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&\n (s->session != NULL) && (s->session->cipher != NULL)) {\n s->rlayer.handshake_fragment_len = 0;\n\n if ((s->rlayer.handshake_fragment[1] != 0) ||\n (s->rlayer.handshake_fragment[2] != 0) ||\n (s->rlayer.handshake_fragment[3] != 0)) {\n al = SSL_AD_DECODE_ERROR;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);\n goto f_err;\n }\n\n if (s->msg_callback)\n s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,\n s->rlayer.handshake_fragment, 4, s,\n s->msg_callback_arg);\n\n if (SSL_is_init_finished(s) &&\n !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&\n !s->s3->renegotiate) {\n ssl3_renegotiate(s);\n if (ssl3_renegotiate_check(s)) {\n i = s->handshake_func(s);\n if (i < 0)\n return (i);\n if (i == 0) {\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);\n return (-1);\n }\n\n if (!(s->mode & SSL_MODE_AUTO_RETRY)) {\n if (SSL3_BUFFER_get_left(rbuf) == 0) {\n /* no read-ahead left? */\n BIO *bio;\n /*\n * In the case where we try to read application data,\n * but we trigger an SSL handshake, we return -1 with\n * the retry option set. Otherwise renegotiation may\n * cause nasty problems in the blocking world\n */\n s->rwstate = SSL_READING;\n bio = SSL_get_rbio(s);\n BIO_clear_retry_flags(bio);\n BIO_set_retry_read(bio);\n return (-1);\n }\n }\n }\n }\n /*\n * we either finished a handshake or ignored the request, now try\n * again to obtain the (application) data we were asked for\n */\n goto start;\n }\n /*\n * If we are a server and get a client hello when renegotiation isn't\n * allowed send back a no renegotiation alert and carry on. WARNING:\n * experimental code, needs reviewing (steve)\n */\n if (s->server &&\n SSL_is_init_finished(s) &&\n !s->s3->send_connection_binding &&\n (s->version > SSL3_VERSION) &&\n (s->rlayer.handshake_fragment_len >= 4) &&\n (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&\n (s->session != NULL) && (s->session->cipher != NULL) &&\n !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {\n SSL3_RECORD_set_length(rr, 0);\n SSL3_RECORD_set_read(rr);\n ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);\n goto start;\n }\n if (s->rlayer.alert_fragment_len >= 2) {\n int alert_level = s->rlayer.alert_fragment[0];\n int alert_descr = s->rlayer.alert_fragment[1];\n\n s->rlayer.alert_fragment_len = 0;\n\n if (s->msg_callback)\n s->msg_callback(0, s->version, SSL3_RT_ALERT,\n s->rlayer.alert_fragment, 2, s,\n s->msg_callback_arg);\n\n if (s->info_callback != NULL)\n cb = s->info_callback;\n else if (s->ctx->info_callback != NULL)\n cb = s->ctx->info_callback;\n\n if (cb != NULL) {\n j = (alert_level << 8) | alert_descr;\n cb(s, SSL_CB_READ_ALERT, j);\n }\n\n if (alert_level == SSL3_AL_WARNING) {\n s->s3->warn_alert = alert_descr;\n SSL3_RECORD_set_read(rr);\n\n s->rlayer.alert_count++;\n if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);\n goto f_err;\n }\n\n if (alert_descr == SSL_AD_CLOSE_NOTIFY) {\n s->shutdown |= SSL_RECEIVED_SHUTDOWN;\n return (0);\n }\n /*\n * This is a warning but we receive it if we requested\n * renegotiation and the peer denied it. Terminate with a fatal\n * alert because if application tried to renegotiate it\n * presumably had a good reason and expects it to succeed. In\n * future we might have a renegotiation where we don't care if\n * the peer refused it where we carry on.\n */\n else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {\n al = SSL_AD_HANDSHAKE_FAILURE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);\n goto f_err;\n }\n#ifdef SSL_AD_MISSING_SRP_USERNAME\n else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)\n return (0);\n#endif\n } else if (alert_level == SSL3_AL_FATAL) {\n char tmp[16];\n\n s->rwstate = SSL_NOTHING;\n s->s3->fatal_alert = alert_descr;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);\n BIO_snprintf(tmp, sizeof tmp, \"%d\", alert_descr);\n ERR_add_error_data(2, \"SSL alert number \", tmp);\n s->shutdown |= SSL_RECEIVED_SHUTDOWN;\n SSL3_RECORD_set_read(rr);\n SSL_CTX_remove_session(s->session_ctx, s->session);\n return (0);\n } else {\n al = SSL_AD_ILLEGAL_PARAMETER;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);\n goto f_err;\n }\n\n goto start;\n }\n\n if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a\n * shutdown */\n s->rwstate = SSL_NOTHING;\n SSL3_RECORD_set_length(rr, 0);\n SSL3_RECORD_set_read(rr);\n return (0);\n }\n\n if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);\n goto f_err;\n }\n\n /*\n * Unexpected handshake message (Client Hello, or protocol violation)\n */\n if ((s->rlayer.handshake_fragment_len >= 4)\n && !ossl_statem_get_in_handshake(s)) {\n if (SSL_is_init_finished(s) &&\n !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {\n ossl_statem_set_in_init(s, 1);\n s->renegotiate = 1;\n s->new_session = 1;\n }\n i = s->handshake_func(s);\n if (i < 0)\n return (i);\n if (i == 0) {\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);\n return (-1);\n }\n\n if (!(s->mode & SSL_MODE_AUTO_RETRY)) {\n if (SSL3_BUFFER_get_left(rbuf) == 0) {\n /* no read-ahead left? */\n BIO *bio;\n /*\n * In the case where we try to read application data, but we\n * trigger an SSL handshake, we return -1 with the retry\n * option set. Otherwise renegotiation may cause nasty\n * problems in the blocking world\n */\n s->rwstate = SSL_READING;\n bio = SSL_get_rbio(s);\n BIO_clear_retry_flags(bio);\n BIO_set_retry_read(bio);\n return (-1);\n }\n }\n goto start;\n }\n\n switch (SSL3_RECORD_get_type(rr)) {\n default:\n /*\n * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give\n * an unexpected message alert.\n */\n if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {\n SSL3_RECORD_set_length(rr, 0);\n SSL3_RECORD_set_read(rr);\n goto start;\n }\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);\n goto f_err;\n case SSL3_RT_CHANGE_CIPHER_SPEC:\n case SSL3_RT_ALERT:\n case SSL3_RT_HANDSHAKE:\n /*\n * we already handled all of these, with the possible exception of\n * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but\n * that should not happen when type != rr->type\n */\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n goto f_err;\n case SSL3_RT_APPLICATION_DATA:\n /*\n * At this point, we were expecting handshake data, but have\n * application data. If the library was running inside ssl3_read()\n * (i.e. in_read_app_data is set) and it makes sense to read\n * application data at this point (session renegotiation not yet\n * started), we will indulge it.\n */\n if (ossl_statem_app_data_allowed(s)) {\n s->s3->in_read_app_data = 2;\n return (-1);\n } else {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);\n goto f_err;\n }\n }\n /* not reached */\n\n f_err:\n ssl3_send_alert(s, SSL3_AL_FATAL, al);\n return (-1);\n}", "target": 1, "cwe": ["CWE-20"], "project": "openssl", "commit_id": "63658103d4441924f8dbfc517b99bb54758a98b9", "hash": 229842592254180110350134928519396587226, "size": 532, "message": "Fix a hang with SSL_peek()\n\nIf while calling SSL_peek() we read an empty record then we go into an\ninfinite loop, continually trying to read data from the empty record and\nnever making any progress. This could be exploited by a malicious peer in\na Denial Of Service attack.\n\nCVE-2016-6305\n\nGitHub Issue #1563\n\nReviewed-by: Rich Salz <rsalz@openssl.org>", "dataset": "other", "idx": 216634}
  1068. {"func": "int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,\n int len, int peek)\n{\n int al, i, j, ret;\n unsigned int n, curr_rec, num_recs, read_bytes;\n SSL3_RECORD *rr;\n SSL3_BUFFER *rbuf;\n void (*cb) (const SSL *ssl, int type2, int val) = NULL;\n\n rbuf = &s->rlayer.rbuf;\n\n if (!SSL3_BUFFER_is_initialised(rbuf)) {\n /* Not initialized yet */\n if (!ssl3_setup_read_buffer(s))\n return (-1);\n }\n\n if ((type && (type != SSL3_RT_APPLICATION_DATA)\n && (type != SSL3_RT_HANDSHAKE)) || (peek\n && (type !=\n SSL3_RT_APPLICATION_DATA))) {\n SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n return -1;\n }\n\n if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))\n /* (partially) satisfy request from storage */\n {\n unsigned char *src = s->rlayer.handshake_fragment;\n unsigned char *dst = buf;\n unsigned int k;\n\n /* peek == 0 */\n n = 0;\n while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {\n *dst++ = *src++;\n len--;\n s->rlayer.handshake_fragment_len--;\n n++;\n }\n /* move any remaining fragment bytes: */\n for (k = 0; k < s->rlayer.handshake_fragment_len; k++)\n s->rlayer.handshake_fragment[k] = *src++;\n\n if (recvd_type != NULL)\n *recvd_type = SSL3_RT_HANDSHAKE;\n\n return n;\n }\n\n /*\n * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.\n */\n\n if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {\n /* type == SSL3_RT_APPLICATION_DATA */\n i = s->handshake_func(s);\n if (i < 0)\n return (i);\n if (i == 0) {\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);\n return (-1);\n }\n }\n start:\n s->rwstate = SSL_NOTHING;\n\n /*-\n * For each record 'i' up to |num_recs]\n * rr[i].type - is the type of record\n * rr[i].data, - data\n * rr[i].off, - offset into 'data' for next read\n * rr[i].length, - number of bytes.\n */\n rr = s->rlayer.rrec;\n num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);\n\n do {\n /* get new records if necessary */\n if (num_recs == 0) {\n ret = ssl3_get_record(s);\n if (ret <= 0)\n return (ret);\n num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);\n if (num_recs == 0) {\n /* Shouldn't happen */\n al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n goto f_err;\n }\n }\n /* Skip over any records we have already read */\n for (curr_rec = 0;\n curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);\n curr_rec++) ;\n if (curr_rec == num_recs) {\n RECORD_LAYER_set_numrpipes(&s->rlayer, 0);\n num_recs = 0;\n curr_rec = 0;\n }\n } while (num_recs == 0);\n rr = &rr[curr_rec];\n\n /*\n * Reset the count of consecutive warning alerts if we've got a non-empty\n * record that isn't an alert.\n */\n if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT\n && SSL3_RECORD_get_length(rr) != 0)\n s->rlayer.alert_count = 0;\n\n /* we now have a packet which can be read and processed */\n\n if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,\n * reset by ssl3_get_finished */\n && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);\n goto f_err;\n }\n\n /*\n * If the other end has shut down, throw anything we read away (even in\n * 'peek' mode)\n */\n if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {\n SSL3_RECORD_set_length(rr, 0);\n s->rwstate = SSL_NOTHING;\n return (0);\n }\n\n if (type == SSL3_RECORD_get_type(rr)\n || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC\n && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {\n /*\n * SSL3_RT_APPLICATION_DATA or\n * SSL3_RT_HANDSHAKE or\n * SSL3_RT_CHANGE_CIPHER_SPEC\n */\n /*\n * make sure that we are not getting application data when we are\n * doing a handshake for the first time\n */\n if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&\n (s->enc_read_ctx == NULL)) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);\n goto f_err;\n }\n\n if (type == SSL3_RT_HANDSHAKE\n && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC\n && s->rlayer.handshake_fragment_len > 0) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);\n goto f_err;\n }\n\n if (recvd_type != NULL)\n *recvd_type = SSL3_RECORD_get_type(rr);\n\n if (len <= 0)\n return (len);\n\n read_bytes = 0;\n do {\n if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))\n n = SSL3_RECORD_get_length(rr);\n else\n n = (unsigned int)len - read_bytes;\n\n memcpy(buf, &(rr->data[rr->off]), n);\n buf += n;\n if (peek) {\n /* Mark any zero length record as consumed CVE-2016-6305 */\n if (SSL3_RECORD_get_length(rr) == 0)\n SSL3_RECORD_set_read(rr);\n } else {\n SSL3_RECORD_sub_length(rr, n);\n SSL3_RECORD_add_off(rr, n);\n if (SSL3_RECORD_get_length(rr) == 0) {\n s->rlayer.rstate = SSL_ST_READ_HEADER;\n SSL3_RECORD_set_off(rr, 0);\n SSL3_RECORD_set_read(rr);\n }\n }\n if (SSL3_RECORD_get_length(rr) == 0\n || (peek && n == SSL3_RECORD_get_length(rr))) {\n curr_rec++;\n rr++;\n }\n read_bytes += n;\n } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs\n && read_bytes < (unsigned int)len);\n if (read_bytes == 0) {\n /* We must have read empty records. Get more data */\n goto start;\n }\n if (!peek && curr_rec == num_recs\n && (s->mode & SSL_MODE_RELEASE_BUFFERS)\n && SSL3_BUFFER_get_left(rbuf) == 0)\n ssl3_release_read_buffer(s);\n return read_bytes;\n }\n\n /*\n * If we get here, then type != rr->type; if we have a handshake message,\n * then it was unexpected (Hello Request or Client Hello) or invalid (we\n * were actually expecting a CCS).\n */\n\n /*\n * Lets just double check that we've not got an SSLv2 record\n */\n if (rr->rec_version == SSL2_VERSION) {\n /*\n * Should never happen. ssl3_get_record() should only give us an SSLv2\n * record back if this is the first packet and we are looking for an\n * initial ClientHello. Therefore |type| should always be equal to\n * |rr->type|. If not then something has gone horribly wrong\n */\n al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n goto f_err;\n }\n\n if (s->method->version == TLS_ANY_VERSION\n && (s->server || rr->type != SSL3_RT_ALERT)) {\n /*\n * If we've got this far and still haven't decided on what version\n * we're using then this must be a client side alert we're dealing with\n * (we don't allow heartbeats yet). We shouldn't be receiving anything\n * other than a ClientHello if we are a server.\n */\n s->version = rr->rec_version;\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);\n goto f_err;\n }\n\n /*\n * In case of record types for which we have 'fragment' storage, fill\n * that so that we can process the data at a fixed place.\n */\n {\n unsigned int dest_maxlen = 0;\n unsigned char *dest = NULL;\n unsigned int *dest_len = NULL;\n\n if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {\n dest_maxlen = sizeof s->rlayer.handshake_fragment;\n dest = s->rlayer.handshake_fragment;\n dest_len = &s->rlayer.handshake_fragment_len;\n } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {\n dest_maxlen = sizeof s->rlayer.alert_fragment;\n dest = s->rlayer.alert_fragment;\n dest_len = &s->rlayer.alert_fragment_len;\n }\n\n if (dest_maxlen > 0) {\n n = dest_maxlen - *dest_len; /* available space in 'dest' */\n if (SSL3_RECORD_get_length(rr) < n)\n n = SSL3_RECORD_get_length(rr); /* available bytes */\n\n /* now move 'n' bytes: */\n while (n-- > 0) {\n dest[(*dest_len)++] =\n SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];\n SSL3_RECORD_add_off(rr, 1);\n SSL3_RECORD_add_length(rr, -1);\n }\n\n if (*dest_len < dest_maxlen) {\n SSL3_RECORD_set_read(rr);\n goto start; /* fragment was too small */\n }\n }\n }\n\n /*-\n * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;\n * s->rlayer.alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.\n * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)\n */\n\n /* If we are a client, check for an incoming 'Hello Request': */\n if ((!s->server) &&\n (s->rlayer.handshake_fragment_len >= 4) &&\n (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&\n (s->session != NULL) && (s->session->cipher != NULL)) {\n s->rlayer.handshake_fragment_len = 0;\n\n if ((s->rlayer.handshake_fragment[1] != 0) ||\n (s->rlayer.handshake_fragment[2] != 0) ||\n (s->rlayer.handshake_fragment[3] != 0)) {\n al = SSL_AD_DECODE_ERROR;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);\n goto f_err;\n }\n\n if (s->msg_callback)\n s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,\n s->rlayer.handshake_fragment, 4, s,\n s->msg_callback_arg);\n\n if (SSL_is_init_finished(s) &&\n !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&\n !s->s3->renegotiate) {\n ssl3_renegotiate(s);\n if (ssl3_renegotiate_check(s)) {\n i = s->handshake_func(s);\n if (i < 0)\n return (i);\n if (i == 0) {\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);\n return (-1);\n }\n\n if (!(s->mode & SSL_MODE_AUTO_RETRY)) {\n if (SSL3_BUFFER_get_left(rbuf) == 0) {\n /* no read-ahead left? */\n BIO *bio;\n /*\n * In the case where we try to read application data,\n * but we trigger an SSL handshake, we return -1 with\n * the retry option set. Otherwise renegotiation may\n * cause nasty problems in the blocking world\n */\n s->rwstate = SSL_READING;\n bio = SSL_get_rbio(s);\n BIO_clear_retry_flags(bio);\n BIO_set_retry_read(bio);\n return (-1);\n }\n }\n }\n }\n /*\n * we either finished a handshake or ignored the request, now try\n * again to obtain the (application) data we were asked for\n */\n goto start;\n }\n /*\n * If we are a server and get a client hello when renegotiation isn't\n * allowed send back a no renegotiation alert and carry on. WARNING:\n * experimental code, needs reviewing (steve)\n */\n if (s->server &&\n SSL_is_init_finished(s) &&\n !s->s3->send_connection_binding &&\n (s->version > SSL3_VERSION) &&\n (s->rlayer.handshake_fragment_len >= 4) &&\n (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&\n (s->session != NULL) && (s->session->cipher != NULL) &&\n !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {\n SSL3_RECORD_set_length(rr, 0);\n SSL3_RECORD_set_read(rr);\n ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);\n goto start;\n }\n if (s->rlayer.alert_fragment_len >= 2) {\n int alert_level = s->rlayer.alert_fragment[0];\n int alert_descr = s->rlayer.alert_fragment[1];\n\n s->rlayer.alert_fragment_len = 0;\n\n if (s->msg_callback)\n s->msg_callback(0, s->version, SSL3_RT_ALERT,\n s->rlayer.alert_fragment, 2, s,\n s->msg_callback_arg);\n\n if (s->info_callback != NULL)\n cb = s->info_callback;\n else if (s->ctx->info_callback != NULL)\n cb = s->ctx->info_callback;\n\n if (cb != NULL) {\n j = (alert_level << 8) | alert_descr;\n cb(s, SSL_CB_READ_ALERT, j);\n }\n\n if (alert_level == SSL3_AL_WARNING) {\n s->s3->warn_alert = alert_descr;\n SSL3_RECORD_set_read(rr);\n\n s->rlayer.alert_count++;\n if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);\n goto f_err;\n }\n\n if (alert_descr == SSL_AD_CLOSE_NOTIFY) {\n s->shutdown |= SSL_RECEIVED_SHUTDOWN;\n return (0);\n }\n /*\n * This is a warning but we receive it if we requested\n * renegotiation and the peer denied it. Terminate with a fatal\n * alert because if application tried to renegotiate it\n * presumably had a good reason and expects it to succeed. In\n * future we might have a renegotiation where we don't care if\n * the peer refused it where we carry on.\n */\n else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {\n al = SSL_AD_HANDSHAKE_FAILURE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);\n goto f_err;\n }\n#ifdef SSL_AD_MISSING_SRP_USERNAME\n else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)\n return (0);\n#endif\n } else if (alert_level == SSL3_AL_FATAL) {\n char tmp[16];\n\n s->rwstate = SSL_NOTHING;\n s->s3->fatal_alert = alert_descr;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);\n BIO_snprintf(tmp, sizeof tmp, \"%d\", alert_descr);\n ERR_add_error_data(2, \"SSL alert number \", tmp);\n s->shutdown |= SSL_RECEIVED_SHUTDOWN;\n SSL3_RECORD_set_read(rr);\n SSL_CTX_remove_session(s->session_ctx, s->session);\n return (0);\n } else {\n al = SSL_AD_ILLEGAL_PARAMETER;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);\n goto f_err;\n }\n\n goto start;\n }\n\n if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a\n * shutdown */\n s->rwstate = SSL_NOTHING;\n SSL3_RECORD_set_length(rr, 0);\n SSL3_RECORD_set_read(rr);\n return (0);\n }\n\n if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);\n goto f_err;\n }\n\n /*\n * Unexpected handshake message (Client Hello, or protocol violation)\n */\n if ((s->rlayer.handshake_fragment_len >= 4)\n && !ossl_statem_get_in_handshake(s)) {\n if (SSL_is_init_finished(s) &&\n !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {\n ossl_statem_set_in_init(s, 1);\n s->renegotiate = 1;\n s->new_session = 1;\n }\n i = s->handshake_func(s);\n if (i < 0)\n return (i);\n if (i == 0) {\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);\n return (-1);\n }\n\n if (!(s->mode & SSL_MODE_AUTO_RETRY)) {\n if (SSL3_BUFFER_get_left(rbuf) == 0) {\n /* no read-ahead left? */\n BIO *bio;\n /*\n * In the case where we try to read application data, but we\n * trigger an SSL handshake, we return -1 with the retry\n * option set. Otherwise renegotiation may cause nasty\n * problems in the blocking world\n */\n s->rwstate = SSL_READING;\n bio = SSL_get_rbio(s);\n BIO_clear_retry_flags(bio);\n BIO_set_retry_read(bio);\n return (-1);\n }\n }\n goto start;\n }\n\n switch (SSL3_RECORD_get_type(rr)) {\n default:\n /*\n * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give\n * an unexpected message alert.\n */\n if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {\n SSL3_RECORD_set_length(rr, 0);\n SSL3_RECORD_set_read(rr);\n goto start;\n }\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);\n goto f_err;\n case SSL3_RT_CHANGE_CIPHER_SPEC:\n case SSL3_RT_ALERT:\n case SSL3_RT_HANDSHAKE:\n /*\n * we already handled all of these, with the possible exception of\n * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but\n * that should not happen when type != rr->type\n */\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);\n goto f_err;\n case SSL3_RT_APPLICATION_DATA:\n /*\n * At this point, we were expecting handshake data, but have\n * application data. If the library was running inside ssl3_read()\n * (i.e. in_read_app_data is set) and it makes sense to read\n * application data at this point (session renegotiation not yet\n * started), we will indulge it.\n */\n if (ossl_statem_app_data_allowed(s)) {\n s->s3->in_read_app_data = 2;\n return (-1);\n } else {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);\n goto f_err;\n }\n }\n /* not reached */\n\n f_err:\n ssl3_send_alert(s, SSL3_AL_FATAL, al);\n return (-1);\n}", "target": 0, "cwe": ["CWE-20"], "project": "openssl", "commit_id": "63658103d4441924f8dbfc517b99bb54758a98b9", "hash": 282966599163418320840049525998042662202, "size": 536, "message": "Fix a hang with SSL_peek()\n\nIf while calling SSL_peek() we read an empty record then we go into an\ninfinite loop, continually trying to read data from the empty record and\nnever making any progress. This could be exploited by a malicious peer in\na Denial Of Service attack.\n\nCVE-2016-6305\n\nGitHub Issue #1563\n\nReviewed-by: Rich Salz <rsalz@openssl.org>", "dataset": "other", "idx": 503768}
  1069. {"func": "void auth_client_request_abort(struct auth_client_request **_request)\n{\n\tstruct auth_client_request *request = *_request;\n\n\t*_request = NULL;\n\n\tauth_client_send_cancel(request->conn->client, request->id);\n\tcall_callback(request, AUTH_REQUEST_STATUS_ABORT, NULL, NULL);\n\tpool_unref(&request->pool);\n}", "target": 1, "cwe": [], "project": "core", "commit_id": "a9b135760aea6d1790d447d351c56b78889dac22", "hash": 314867317538556373212284150622992900603, "size": 10, "message": "lib-auth: Remove request after abort\n\nOtherwise the request will still stay in hash table\nand get dereferenced when all requests are aborted\ncausing an attempt to access free'd memory.\n\nFound by Apollon Oikonomopoulos <apoikos@debian.org>\n\nBroken in 1a29ed2f96da1be22fa5a4d96c7583aa81b8b060", "dataset": "other", "idx": 216710}
  1070. {"func": "void auth_client_request_abort(struct auth_client_request **_request)\n{\n\tstruct auth_client_request *request = *_request;\n\n\t*_request = NULL;\n\n\tauth_client_send_cancel(request->conn->client, request->id);\n\tcall_callback(request, AUTH_REQUEST_STATUS_ABORT, NULL, NULL);\n\t/* remove the request */\n\tauth_server_connection_remove_request(request->conn, request->id);\n\tpool_unref(&request->pool);\n}", "target": 0, "cwe": [], "project": "core", "commit_id": "a9b135760aea6d1790d447d351c56b78889dac22", "hash": 93121729489284854446543863404294639172, "size": 12, "message": "lib-auth: Remove request after abort\n\nOtherwise the request will still stay in hash table\nand get dereferenced when all requests are aborted\ncausing an attempt to access free'd memory.\n\nFound by Apollon Oikonomopoulos <apoikos@debian.org>\n\nBroken in 1a29ed2f96da1be22fa5a4d96c7583aa81b8b060", "dataset": "other", "idx": 505209}
  1071. {"func": "ECDSA_SIG *ossl_ecdsa_sign_sig(const unsigned char *dgst, int dgst_len,\n const BIGNUM *in_kinv, const BIGNUM *in_r,\n EC_KEY *eckey)\n{\n int ok = 0, i;\n BIGNUM *kinv = NULL, *s, *m = NULL, *tmp = NULL;\n const BIGNUM *order, *ckinv;\n BN_CTX *ctx = NULL;\n const EC_GROUP *group;\n ECDSA_SIG *ret;\n const BIGNUM *priv_key;\n\n group = EC_KEY_get0_group(eckey);\n priv_key = EC_KEY_get0_private_key(eckey);\n\n if (group == NULL || priv_key == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_PASSED_NULL_PARAMETER);\n return NULL;\n }\n\n if (!EC_KEY_can_sign(eckey)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING);\n return NULL;\n }\n\n ret = ECDSA_SIG_new();\n if (ret == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n return NULL;\n }\n ret->r = BN_new();\n ret->s = BN_new();\n if (ret->r == NULL || ret->s == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n s = ret->s;\n\n if ((ctx = BN_CTX_new()) == NULL ||\n (tmp = BN_new()) == NULL || (m = BN_new()) == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n order = EC_GROUP_get0_order(group);\n if (order == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_EC_LIB);\n goto err;\n }\n i = BN_num_bits(order);\n /*\n * Need to truncate digest if it is too long: first truncate whole bytes.\n */\n if (8 * dgst_len > i)\n dgst_len = (i + 7) / 8;\n if (!BN_bin2bn(dgst, dgst_len, m)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n /* If still too long truncate remaining bits with a shift */\n if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n do {\n if (in_kinv == NULL || in_r == NULL) {\n if (!ecdsa_sign_setup(eckey, ctx, &kinv, &ret->r, dgst, dgst_len)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_ECDSA_LIB);\n goto err;\n }\n ckinv = kinv;\n } else {\n ckinv = in_kinv;\n if (BN_copy(ret->r, in_r) == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n }\n\n if (!BN_mod_mul(tmp, priv_key, ret->r, order, ctx)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n if (!BN_mod_add_quick(s, tmp, m, order)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n if (!BN_mod_mul(s, s, ckinv, order, ctx)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n if (BN_is_zero(s)) {\n /*\n * if kinv and r have been supplied by the caller don't to\n * generate new kinv and r values\n */\n if (in_kinv != NULL && in_r != NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, EC_R_NEED_NEW_SETUP_VALUES);\n goto err;\n }\n } else\n /* s != 0 => we have a valid signature */\n break;\n }\n while (1);\n\n ok = 1;\n err:\n if (!ok) {\n ECDSA_SIG_free(ret);\n ret = NULL;\n }\n BN_CTX_free(ctx);\n BN_clear_free(m);\n BN_clear_free(tmp);\n BN_clear_free(kinv);\n return ret;\n}", "target": 1, "cwe": ["CWE-203"], "project": "openssl", "commit_id": "0c27d793745c7837b13646302b6890a556b7017a", "hash": 151477642914054661196425866678434310834, "size": 118, "message": "Add blinding to an ECDSA signature\n\nKeegan Ryan (NCC Group) has demonstrated a side channel attack on an\nECDSA signature operation. During signing the signer calculates:\n\ns:= k^-1 * (m + r * priv_key) mod order\n\nThe addition operation above provides a sufficient signal for a\nflush+reload attack to derive the private key given sufficient signature\noperations.\n\nAs a mitigation (based on a suggestion from Keegan) we add blinding to\nthe operation so that:\n\ns := k^-1 * blind^-1 (blind * m + blind * r * priv_key) mod order\n\nSince this attack is a localhost side channel only no CVE is assigned.\n\nReviewed-by: Rich Salz <rsalz@openssl.org>", "dataset": "other", "idx": 216718}
  1072. {"func": "ECDSA_SIG *ossl_ecdsa_sign_sig(const unsigned char *dgst, int dgst_len,\n const BIGNUM *in_kinv, const BIGNUM *in_r,\n EC_KEY *eckey)\n{\n int ok = 0, i;\n BIGNUM *kinv = NULL, *s, *m = NULL, *tmp = NULL, *blind = NULL;\n BIGNUM *blindm = NULL;\n const BIGNUM *order, *ckinv;\n BN_CTX *ctx = NULL;\n const EC_GROUP *group;\n ECDSA_SIG *ret;\n const BIGNUM *priv_key;\n\n group = EC_KEY_get0_group(eckey);\n priv_key = EC_KEY_get0_private_key(eckey);\n\n if (group == NULL || priv_key == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_PASSED_NULL_PARAMETER);\n return NULL;\n }\n\n if (!EC_KEY_can_sign(eckey)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING);\n return NULL;\n }\n\n ret = ECDSA_SIG_new();\n if (ret == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n return NULL;\n }\n ret->r = BN_new();\n ret->s = BN_new();\n if (ret->r == NULL || ret->s == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n s = ret->s;\n\n ctx = BN_CTX_secure_new();\n if (ctx == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n BN_CTX_start(ctx);\n tmp = BN_CTX_get(ctx);\n m = BN_CTX_get(ctx);\n blind = BN_CTX_get(ctx);\n blindm = BN_CTX_get(ctx);\n if (blindm == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n order = EC_GROUP_get0_order(group);\n if (order == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_EC_LIB);\n goto err;\n }\n i = BN_num_bits(order);\n /*\n * Need to truncate digest if it is too long: first truncate whole bytes.\n */\n if (8 * dgst_len > i)\n dgst_len = (i + 7) / 8;\n if (!BN_bin2bn(dgst, dgst_len, m)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n /* If still too long truncate remaining bits with a shift */\n if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n do {\n if (in_kinv == NULL || in_r == NULL) {\n if (!ecdsa_sign_setup(eckey, ctx, &kinv, &ret->r, dgst, dgst_len)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_ECDSA_LIB);\n goto err;\n }\n ckinv = kinv;\n } else {\n ckinv = in_kinv;\n if (BN_copy(ret->r, in_r) == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n }\n\n /*\n * The normal signature calculation is:\n *\n * s := k^-1 * (m + r * priv_key) mod order\n *\n * We will blind this to protect against side channel attacks\n *\n * s := k^-1 * blind^-1 * (blind * m + blind * r * priv_key) mod order\n */\n\n /* Generate a blinding value */\n do {\n if (!BN_rand(blind, BN_num_bits(order) - 1, BN_RAND_TOP_ANY,\n BN_RAND_BOTTOM_ANY))\n goto err;\n } while (BN_is_zero(blind));\n BN_set_flags(blind, BN_FLG_CONSTTIME);\n BN_set_flags(blindm, BN_FLG_CONSTTIME);\n BN_set_flags(tmp, BN_FLG_CONSTTIME);\n\n /* tmp := blind * priv_key * r mod order */\n if (!BN_mod_mul(tmp, blind, priv_key, order, ctx)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n if (!BN_mod_mul(tmp, tmp, ret->r, order, ctx)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n\n /* blindm := blind * m mod order */\n if (!BN_mod_mul(blindm, blind, m, order, ctx)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n\n /* s : = (blind * priv_key * r) + (blind * m) mod order */\n if (!BN_mod_add_quick(s, tmp, blindm, order)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n\n /* s:= s * blind^-1 mod order */\n if (BN_mod_inverse(blind, blind, order, ctx) == NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n if (!BN_mod_mul(s, s, blind, order, ctx)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n\n /* s := s * k^-1 mod order */\n if (!BN_mod_mul(s, s, ckinv, order, ctx)) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB);\n goto err;\n }\n\n if (BN_is_zero(s)) {\n /*\n * if kinv and r have been supplied by the caller don't to\n * generate new kinv and r values\n */\n if (in_kinv != NULL && in_r != NULL) {\n ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, EC_R_NEED_NEW_SETUP_VALUES);\n goto err;\n }\n } else\n /* s != 0 => we have a valid signature */\n break;\n }\n while (1);\n\n ok = 1;\n err:\n if (!ok) {\n ECDSA_SIG_free(ret);\n ret = NULL;\n }\n BN_CTX_end(ctx);\n BN_CTX_free(ctx);\n BN_clear_free(kinv);\n return ret;\n}", "target": 0, "cwe": ["CWE-203"], "project": "openssl", "commit_id": "0c27d793745c7837b13646302b6890a556b7017a", "hash": 100110287515814318888302066096494027558, "size": 174, "message": "Add blinding to an ECDSA signature\n\nKeegan Ryan (NCC Group) has demonstrated a side channel attack on an\nECDSA signature operation. During signing the signer calculates:\n\ns:= k^-1 * (m + r * priv_key) mod order\n\nThe addition operation above provides a sufficient signal for a\nflush+reload attack to derive the private key given sufficient signature\noperations.\n\nAs a mitigation (based on a suggestion from Keegan) we add blinding to\nthe operation so that:\n\ns := k^-1 * blind^-1 (blind * m + blind * r * priv_key) mod order\n\nSince this attack is a localhost side channel only no CVE is assigned.\n\nReviewed-by: Rich Salz <rsalz@openssl.org>", "dataset": "other", "idx": 505371}
  1073. {"func": "struct cgit_cmd *cgit_get_cmd(struct cgit_context *ctx)\n{\n\tstatic struct cgit_cmd cmds[] = {\n\t\tdef_cmd(about, 0, 1),\n\t\tdef_cmd(blob, 1, 0),\n\t\tdef_cmd(commit, 1, 1),\n\t\tdef_cmd(diff, 1, 1),\n\t\tdef_cmd(log, 1, 1),\n\t\tdef_cmd(ls_cache, 0, 0),\n\t\tdef_cmd(patch, 1, 0),\n\t\tdef_cmd(refs, 1, 1),\n\t\tdef_cmd(repolist, 0, 0),\n\t\tdef_cmd(snapshot, 1, 0),\n\t\tdef_cmd(summary, 1, 1),\n\t\tdef_cmd(tag, 1, 1),\n\t\tdef_cmd(tree, 1, 1),\n\t};\n\tint i;\n\n\tif (ctx->qry.page == NULL) {\n\t\tif (ctx->repo)\n\t\t\tctx->qry.page = \"summary\";\n\t\telse\n\t\t\tctx->qry.page = \"repolist\";\n\t}\n\n\tfor(i = 0; i < sizeof(cmds)/sizeof(*cmds); i++)\n\t\tif (!strcmp(ctx->qry.page, cmds[i].name))\n\t\t\treturn &cmds[i];\n\treturn NULL;\n}", "target": 1, "cwe": [], "project": "cgit", "commit_id": "02a545e63454530c1639014d3239c14ced2022c6", "hash": 93798479963557747596875102576095851163, "size": 31, "message": "Add support for cloning over http\n\nThis patch implements basic support for cloning over http, based on the\nwork on git-http-backend by Shawn O. Pearce.\n\nSigned-off-by: Lars Hjemli <hjemli@gmail.com>", "dataset": "other", "idx": 216720}
  1074. {"func": "struct cgit_cmd *cgit_get_cmd(struct cgit_context *ctx)\n{\n\tstatic struct cgit_cmd cmds[] = {\n\t\tdef_cmd(HEAD, 1, 0),\n\t\tdef_cmd(about, 0, 1),\n\t\tdef_cmd(blob, 1, 0),\n\t\tdef_cmd(commit, 1, 1),\n\t\tdef_cmd(diff, 1, 1),\n\t\tdef_cmd(info, 1, 0),\n\t\tdef_cmd(log, 1, 1),\n\t\tdef_cmd(ls_cache, 0, 0),\n\t\tdef_cmd(objects, 1, 0),\n\t\tdef_cmd(patch, 1, 0),\n\t\tdef_cmd(refs, 1, 1),\n\t\tdef_cmd(repolist, 0, 0),\n\t\tdef_cmd(snapshot, 1, 0),\n\t\tdef_cmd(summary, 1, 1),\n\t\tdef_cmd(tag, 1, 1),\n\t\tdef_cmd(tree, 1, 1),\n\t};\n\tint i;\n\n\tif (ctx->qry.page == NULL) {\n\t\tif (ctx->repo)\n\t\t\tctx->qry.page = \"summary\";\n\t\telse\n\t\t\tctx->qry.page = \"repolist\";\n\t}\n\n\tfor(i = 0; i < sizeof(cmds)/sizeof(*cmds); i++)\n\t\tif (!strcmp(ctx->qry.page, cmds[i].name))\n\t\t\treturn &cmds[i];\n\treturn NULL;\n}", "target": 0, "cwe": [], "project": "cgit", "commit_id": "02a545e63454530c1639014d3239c14ced2022c6", "hash": 156010204768308273094220846969433284739, "size": 34, "message": "Add support for cloning over http\n\nThis patch implements basic support for cloning over http, based on the\nwork on git-http-backend by Shawn O. Pearce.\n\nSigned-off-by: Lars Hjemli <hjemli@gmail.com>", "dataset": "other", "idx": 505388}
  1075. {"func": "Agraph_t *agroot(void* obj)\n{\n switch (AGTYPE(obj)) {\n case AGINEDGE:\n case AGOUTEDGE:\n\treturn ((Agedge_t *) obj)->node->root;\n case AGNODE:\n\treturn ((Agnode_t *) obj)->root;\n case AGRAPH:\n\treturn ((Agraph_t *) obj)->root;\n default:\t\t\t/* actually can't occur if only 2 bit tags */\n\tagerr(AGERR, \"agroot of a bad object\");\n\treturn NILgraph;\n }\n}", "target": 1, "cwe": ["CWE-476"], "project": "graphviz", "commit_id": "839085f8026afd6f6920a0c31ad2a9d880d97932", "hash": 285926376776107496641309642772781622865, "size": 15, "message": "attempted fix for null pointer deference on malformed input", "dataset": "other", "idx": 216728}
  1076. {"func": "Agraph_t *agraphof(void *obj)\n{\n switch (AGTYPE(obj)) {\n case AGINEDGE:\n case AGOUTEDGE:\n\treturn ((Agedge_t *) obj)->node->root;\n case AGNODE:\n\treturn ((Agnode_t *) obj)->root;\n case AGRAPH:\n\treturn (Agraph_t *) obj;\n default:\t\t\t/* actually can't occur if only 2 bit tags */\n\tagerr(AGERR, \"agraphof a bad object\");\n\treturn NILgraph;\n }\n}", "target": 0, "cwe": ["CWE-476"], "project": "graphviz", "commit_id": "839085f8026afd6f6920a0c31ad2a9d880d97932", "hash": 248563598394800902846024511939663049757, "size": 15, "message": "attempted fix for null pointer deference on malformed input", "dataset": "other", "idx": 505492}
  1077. {"func": "static bool ntlmssp_check_buffer(const struct ntlmssp_buffer *buffer,\n\t\t\t\t size_t data_size, const char **error)\n{\n\tuint32_t offset = read_le32(&buffer->offset);\n\tuint16_t length = read_le16(&buffer->length);\n\tuint16_t space = read_le16(&buffer->space);\n\n\t/* Empty buffer is ok */\n\tif (length == 0 && space == 0)\n\t\treturn TRUE;\n\n\tif (offset >= data_size) {\n\t\t*error = \"buffer offset out of bounds\";\n\t\treturn FALSE;\n\t}\n\n\tif (offset + space > data_size) {\n\t\t*error = \"buffer end out of bounds\";\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "target": 1, "cwe": ["CWE-125"], "project": "core", "commit_id": "fb246611e62ad8c5a95b0ca180a63f17aa34b0d8", "hash": 44503422073269898902321827906643231697, "size": 23, "message": "lib-ntlm: Check buffer length on responses\n\nAdd missing check for buffer length.\n\nIf this is not checked, it is possible to send message which\ncauses read past buffer bug.\n\nBroken in c7480644202e5451fbed448508ea29a25cffc99c", "dataset": "other", "idx": 216799}
  1078. {"func": "static bool ntlmssp_check_buffer(const struct ntlmssp_buffer *buffer,\n\t\t\t\t size_t data_size, const char **error)\n{\n\tuint32_t offset = read_le32(&buffer->offset);\n\tuint16_t length = read_le16(&buffer->length);\n\tuint16_t space = read_le16(&buffer->space);\n\n\t/* Empty buffer is ok */\n\tif (length == 0 && space == 0)\n\t\treturn TRUE;\n\n\tif (length > data_size) {\n\t\t*error = \"buffer length out of bounds\";\n\t\treturn FALSE;\n\t}\n\n\tif (offset >= data_size) {\n\t\t*error = \"buffer offset out of bounds\";\n\t\treturn FALSE;\n\t}\n\n\tif (offset + space > data_size) {\n\t\t*error = \"buffer end out of bounds\";\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "target": 0, "cwe": ["CWE-125"], "project": "core", "commit_id": "fb246611e62ad8c5a95b0ca180a63f17aa34b0d8", "hash": 207567383368999279475384375671028455850, "size": 28, "message": "lib-ntlm: Check buffer length on responses\n\nAdd missing check for buffer length.\n\nIf this is not checked, it is possible to send message which\ncauses read past buffer bug.\n\nBroken in c7480644202e5451fbed448508ea29a25cffc99c", "dataset": "other", "idx": 506421}
  1079. {"func": "print_set_output(char *name, TBOOLEAN datablock, TBOOLEAN append_p)\n{\n if (print_out && print_out != stderr && print_out != stdout) {\n#ifdef PIPES\n\tif (print_out_name[0] == '|') {\n\t if (0 > pclose(print_out))\n\t\tperror(print_out_name);\n\t} else\n#endif\n\t if (0 > fclose(print_out))\n\t\tperror(print_out_name);\n }\n\n free(print_out_name);\n print_out_name = NULL;\n print_out_var = NULL;\n\n if (! name) {\n\tprint_out = stderr;\n\treturn;\n }\n\n if (strcmp(name, \"-\") == 0) {\n\tprint_out = stdout;\n\treturn;\n }\n\n#ifdef PIPES\n if (name[0] == '|') {\n\trestrict_popen();\n\tprint_out = popen(name + 1, \"w\");\n\tif (!print_out)\n\t perror(name);\n\telse\n\t print_out_name = name;\n\treturn;\n }\n#endif\n\n if (!datablock) {\n\tprint_out = fopen(name, append_p ? \"a\" : \"w\");\n\tif (!print_out) {\n\t perror(name);\n\t return;\n\t}\n } else {\n\tprint_out_var = add_udv_by_name(name);\n\tif (!append_p)\n\t gpfree_datablock(&print_out_var->udv_value);\n\t/* If this is not an existing datablock to be appended */\n\t/* then make it a new empty datablock */\n\tif (print_out_var->udv_value.type != DATABLOCK) {\n\t free_value(&print_out_var->udv_value);\n\t print_out_var->udv_value.type = DATABLOCK;\n\t print_out_var->udv_value.v.data_array = NULL;\n\t}\n }\n\n print_out_name = name;\n}", "target": 1, "cwe": ["CWE-415"], "project": "gnuplot", "commit_id": "052cbd17c3cbbc602ee080b2617d32a8417d7563", "hash": 335395554038302725624523074852189909378, "size": 60, "message": "successive failures of \"set print <foo>\" could cause double-free\nBug #2312", "dataset": "other", "idx": 216803}
  1080. {"func": "print_set_output(char *name, TBOOLEAN datablock, TBOOLEAN append_p)\n{\n if (print_out && print_out != stderr && print_out != stdout) {\n#ifdef PIPES\n\tif (print_out_name[0] == '|') {\n\t if (0 > pclose(print_out))\n\t\tperror(print_out_name);\n\t} else\n#endif\n\t if (0 > fclose(print_out))\n\t\tperror(print_out_name);\n\tprint_out = stderr;\n }\n\n free(print_out_name);\n print_out_name = NULL;\n print_out_var = NULL;\n\n if (! name) {\n\tprint_out = stderr;\n\treturn;\n }\n\n if (strcmp(name, \"-\") == 0) {\n\tprint_out = stdout;\n\treturn;\n }\n\n#ifdef PIPES\n if (name[0] == '|') {\n\trestrict_popen();\n\tprint_out = popen(name + 1, \"w\");\n\tif (!print_out)\n\t perror(name);\n\telse\n\t print_out_name = name;\n\treturn;\n }\n#endif\n\n if (!datablock) {\n\tprint_out = fopen(name, append_p ? \"a\" : \"w\");\n\tif (!print_out) {\n\t perror(name);\n\t return;\n\t}\n } else {\n\tprint_out_var = add_udv_by_name(name);\n\tif (!append_p)\n\t gpfree_datablock(&print_out_var->udv_value);\n\t/* If this is not an existing datablock to be appended */\n\t/* then make it a new empty datablock */\n\tif (print_out_var->udv_value.type != DATABLOCK) {\n\t free_value(&print_out_var->udv_value);\n\t print_out_var->udv_value.type = DATABLOCK;\n\t print_out_var->udv_value.v.data_array = NULL;\n\t}\n }\n\n print_out_name = name;\n}", "target": 0, "cwe": ["CWE-415"], "project": "gnuplot", "commit_id": "052cbd17c3cbbc602ee080b2617d32a8417d7563", "hash": 335994289631102428001579590913177625446, "size": 61, "message": "successive failures of \"set print <foo>\" could cause double-free\nBug #2312", "dataset": "other", "idx": 506550}
  1081. {"func": "enhanced_recursion(\n const char *p,\n TBOOLEAN brace,\n char *fontname,\n double fontsize,\n double base,\n TBOOLEAN widthflag,\n TBOOLEAN showflag,\n int overprint)\n{\n TBOOLEAN wasitalic, wasbold;\n\n /* Keep track of the style of the font passed in at this recursion level */\n wasitalic = (strstr(fontname, \":Italic\") != NULL);\n wasbold = (strstr(fontname, \":Bold\") != NULL);\n\n FPRINTF((stderr, \"RECURSE WITH \\\"%s\\\", %d %s %.1f %.1f %d %d %d\",\n\t\tp, brace, fontname, fontsize, base, widthflag, showflag, overprint));\n\n /* Start each recursion with a clean string */\n (term->enhanced_flush)();\n\n if (base + fontsize > enhanced_max_height) {\n\tenhanced_max_height = base + fontsize;\n\tENH_DEBUG((\"Setting max height to %.1f\\n\", enhanced_max_height));\n }\n\n if (base < enhanced_min_height) {\n\tenhanced_min_height = base;\n\tENH_DEBUG((\"Setting min height to %.1f\\n\", enhanced_min_height));\n }\n\n while (*p) {\n\tdouble shift;\n\n\t/*\n\t * EAM Jun 2009 - treating bytes one at a time does not work for multibyte\n\t * encodings, including utf-8. If we hit a byte with the high bit set, test\n\t * whether it starts a legal UTF-8 sequence and if so copy the whole thing.\n\t * Other multibyte encodings are still a problem.\n\t * Gnuplot's other defined encodings are all single-byte; for those we\n\t * really do want to treat one byte at a time.\n\t */\n\tif ((*p & 0x80) && (encoding == S_ENC_DEFAULT || encoding == S_ENC_UTF8)) {\n\t unsigned long utf8char;\n\t const char *nextchar = p;\n\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t if (utf8toulong(&utf8char, &nextchar)) {\t/* Legal UTF8 sequence */\n\t\twhile (p < nextchar)\n\t\t (term->enhanced_writec)(*p++);\n\t\tp--;\n\t } else {\t\t\t\t\t/* Some other multibyte encoding? */\n\t\t(term->enhanced_writec)(*p);\n\t }\n/* shige : for Shift_JIS */\n\t} else if ((*p & 0x80) && (encoding == S_ENC_SJIS)) {\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t (term->enhanced_writec)(*(p++));\n\t (term->enhanced_writec)(*p);\n\t} else\n\n\tswitch (*p) {\n\tcase '}' :\n\t /*{{{ deal with it*/\n\t if (brace)\n\t\treturn (p);\n\n\t int_warn(NO_CARET, \"enhanced text parser - spurious }\");\n\t break;\n\t /*}}}*/\n\n\tcase '_' :\n\tcase '^' :\n\t /*{{{ deal with super/sub script*/\n\t shift = (*p == '^') ? 0.5 : -0.3;\n\t (term->enhanced_flush)();\n\t p = enhanced_recursion(p + 1, FALSE, fontname, fontsize * 0.8,\n\t\t\t base + shift * fontsize, widthflag,\n\t\t\t showflag, overprint);\n\t break;\n\t /*}}}*/\n\tcase '{' :\n\t {\n\t\tTBOOLEAN isitalic = FALSE, isbold = FALSE, isnormal = FALSE;\n\t\tconst char *start_of_fontname = NULL;\n\t\tconst char *end_of_fontname = NULL;\n\t\tchar *localfontname = NULL;\n\t\tchar ch;\n\t\tdouble f = fontsize, ovp;\n\n\t\t/* Mar 2014 - this will hold \"fontfamily{:Italic}{:Bold}\" */\n\t\tchar *styledfontname = NULL;\n\n\t\t/*{{{ recurse (possibly with a new font) */\n\n\t\tENH_DEBUG((\"Dealing with {\\n\"));\n\n\t\t/* 30 Sep 2016: Remove incorrect whitespace-eating loop going */\n\t\t/* waaay back to 31-May-2000 */ /* while (*++p == ' '); */\n\t\t++p;\n\t\t/* get vertical offset (if present) for overprinted text */\n\t\tif (overprint == 2) {\n\t\t char *end;\n\t\t ovp = strtod(p,&end);\n\t\t p = end;\n\t\t if (term->flags & TERM_IS_POSTSCRIPT)\n\t\t\tbase = ovp*f;\n\t\t else\n\t\t\tbase += ovp*f;\n\t\t}\n\t\t--p;\n\n\t\tif (*++p == '/') {\n\t\t /* then parse a fontname, optional fontsize */\n\t\t while (*++p == ' ')\n\t\t\t; /* do nothing */\n\t\t if (*p=='-') {\n\t\t\twhile (*++p == ' ')\n\t\t\t ; /* do nothing */\n\t\t }\n\t\t start_of_fontname = p;\n\n\t\t /* Allow font name to be in quotes.\n\t\t * This makes it possible to handle font names containing spaces.\n\t\t */\n\t\t if (*p == '\\'' || *p == '\"') {\n\t\t\t++p;\n\t\t\twhile (*p != '\\0' && *p != '}' && *p != *start_of_fontname)\n\t\t\t ++p;\n\t\t\tif (*p != *start_of_fontname) {\n\t\t\t int_warn(NO_CARET, \"cannot interpret font name %s\", start_of_fontname);\n\t\t\t p = start_of_fontname;\n\t\t\t}\n\t\t\tstart_of_fontname++;\n\t\t\tend_of_fontname = p++;\n\t\t\tch = *p;\n\t\t } else {\n\n\t\t /* Normal unquoted font name */\n\t\t\twhile ((ch = *p) > ' ' && ch != '=' && ch != '*' && ch != '}' && ch != ':')\n\t\t\t ++p;\n\t\t\tend_of_fontname = p;\n\t\t }\n\n\t\t do {\n\t\t\tif (ch == '=') {\n\t\t\t /* get optional font size */\n\t\t\t char *end;\n\t\t\t p++;\n\t\t\t ENH_DEBUG((\"Calling strtod(\\\"%s\\\") ...\", p));\n\t\t\t f = strtod(p, &end);\n\t\t\t p = end;\n\t\t\t ENH_DEBUG((\"Returned %.1f and \\\"%s\\\"\\n\", f, p));\n\n\t\t\t if (f == 0)\n\t\t\t\tf = fontsize;\n\t\t\t else\n\t\t\t\tf *= enhanced_fontscale; /* remember the scaling */\n\n\t\t\t ENH_DEBUG((\"Font size %.1f\\n\", f));\n\t\t\t} else if (ch == '*') {\n\t\t\t /* get optional font size scale factor */\n\t\t\t char *end;\n\t\t\t p++;\n\t\t\t ENH_DEBUG((\"Calling strtod(\\\"%s\\\") ...\", p));\n\t\t\t f = strtod(p, &end);\n\t\t\t p = end;\n\t\t\t ENH_DEBUG((\"Returned %.1f and \\\"%s\\\"\\n\", f, p));\n\n\t\t\t if (f)\n\t\t\t\tf *= fontsize; /* apply the scale factor */\n\t\t\t else\n\t\t\t\tf = fontsize;\n\n\t\t\t ENH_DEBUG((\"Font size %.1f\\n\", f));\n\t\t\t} else if (ch == ':') {\n\t\t\t /* get optional style markup attributes */\n\t\t\t p++;\n\t\t\t if (!strncmp(p,\"Bold\",4))\n\t\t\t\tisbold = TRUE;\n\t\t\t if (!strncmp(p,\"Italic\",6))\n\t\t\t\tisitalic = TRUE;\n\t\t\t if (!strncmp(p,\"Normal\",6))\n\t\t\t\tisnormal = TRUE;\n\t\t\t while (isalpha((unsigned char)*p)) {p++;}\n\t\t\t}\n\t\t } while (((ch = *p) == '=') || (ch == ':') || (ch == '*'));\n\n\t\t if (ch == '}')\n\t\t\tint_warn(NO_CARET,\"bad syntax in enhanced text string\");\n\n\t\t if (*p == ' ')\t/* Eat up a single space following a font spec */\n\t\t\t++p;\n\t\t if (!start_of_fontname || (start_of_fontname == end_of_fontname)) {\n\t\t\t/* Use the font name passed in to us */\n\t\t\tlocalfontname = gp_strdup(fontname);\n\t\t } else {\n\t\t\t/* We found a new font name {/Font ...} */\n\t\t\tint len = end_of_fontname - start_of_fontname;\n\t\t\tlocalfontname = gp_alloc(len+1,\"localfontname\");\n\t\t\tstrncpy(localfontname, start_of_fontname, len);\n\t\t\tlocalfontname[len] = '\\0';\n\t\t }\n\t\t}\n\t\t/*}}}*/\n\n\t\t/* Collect cumulative style markup before passing it in the font name */\n\t\tisitalic = (wasitalic || isitalic) && !isnormal;\n\t\tisbold = (wasbold || isbold) && !isnormal;\n\n\t\tstyledfontname = stylefont(localfontname ? localfontname : fontname,\n\t\t\t\t\t isbold, isitalic);\n\n\t\tp = enhanced_recursion(p, TRUE, styledfontname, f, base,\n\t\t\t\t widthflag, showflag, overprint);\n\n\t\t(term->enhanced_flush)();\n\n\t\tfree(styledfontname);\n\t\tfree(localfontname);\n\n\t\tbreak;\n\t } /* case '{' */\n\tcase '@' :\n\t /*{{{ phantom box - prints next 'char', then restores currentpoint */\n\t (term->enhanced_flush)();\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 3);\n\t p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t widthflag, showflag, overprint);\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 4);\n\t break;\n\t /*}}}*/\n\n\tcase '&' :\n\t /*{{{ character skip - skips space equal to length of character(s) */\n\t (term->enhanced_flush)();\n\n\t p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t widthflag, FALSE, overprint);\n\t break;\n\t /*}}}*/\n\n\tcase '~' :\n\t /*{{{ overprinted text */\n\t /* the second string is overwritten on the first, centered\n\t * horizontally on the first and (optionally) vertically\n\t * shifted by an amount specified (as a fraction of the\n\t * current fontsize) at the beginning of the second string\n\n\t * Note that in this implementation neither the under- nor\n\t * overprinted string can contain syntax that would result\n\t * in additional recursions -- no subscripts,\n\t * superscripts, or anything else, with the exception of a\n\t * font definition at the beginning of the text */\n\n\t (term->enhanced_flush)();\n\t p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t widthflag, showflag, 1);\n\t (term->enhanced_flush)();\n\t if (!*p)\n\t break;\n\t p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t FALSE, showflag, 2);\n\n\t overprint = 0; /* may not be necessary, but just in case . . . */\n\t break;\n\t /*}}}*/\n\n\tcase '(' :\n\tcase ')' :\n\t /*{{{ an escape and print it */\n\t /* special cases */\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t if (term->flags & TERM_IS_POSTSCRIPT)\n\t\t(term->enhanced_writec)('\\\\');\n\t (term->enhanced_writec)(*p);\n\t break;\n\t /*}}}*/\n\n\tcase '\\\\' :\n\t /*{{{ various types of escape sequences, some context-dependent */\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\n\t /* Unicode represented as \\U+hhhhh where hhhhh is hexadecimal code point.\n\t * For UTF-8 encoding we translate hhhhh to a UTF-8 byte sequence and\n\t * output the bytes one by one.\n\t */\n\t if (p[1] == 'U' && p[2] == '+') {\n\t\tif (encoding == S_ENC_UTF8) {\n\t\t uint32_t codepoint;\n\t\t unsigned char utf8char[8];\n\t\t int i, length;\n\n\t\t sscanf(&(p[3]), \"%5x\", &codepoint);\n\t\t length = ucs4toutf8(codepoint, utf8char);\n\t\t p += (codepoint > 0xFFFF) ? 7 : 6;\n\t\t for (i=0; i<length; i++)\n\t\t\t(term->enhanced_writec)(utf8char[i]);\n\t\t break;\n\t\t}\n\n\t /* FIXME: non-utf8 environments not yet supported.\n\t * Note that some terminals may have an alternative way to handle unicode\n\t * escape sequences that is not dependent on encoding.\n\t * E.g. svg and html output could convert to xml sequences &#xhhhh;\n\t * For these cases we must retain the leading backslash so that the\n\t * unicode escape sequence can be recognized by the terminal driver.\n\t */\n\t\t(term->enhanced_writec)(p[0]);\n\t\tbreak;\n\t }\n\n\t /* Enhanced mode always uses \\xyz as an octal character representation\n\t * but each terminal type must give us the actual output format wanted.\n\t * pdf.trm wants the raw character code, which is why we use strtol();\n\t * most other terminal types want some variant of \"\\\\%o\".\n\t */\n\t if (p[1] >= '0' && p[1] <= '7') {\n\t\tchar *e, escape[16], octal[4] = {'\\0','\\0','\\0','\\0'};\n\n\t\toctal[0] = *(++p);\n\t\tif (p[1] >= '0' && p[1] <= '7') {\n\t\t octal[1] = *(++p);\n\t\t if (p[1] >= '0' && p[1] <= '7')\n\t\t\toctal[2] = *(++p);\n\t\t}\n\t\tsprintf(escape, enhanced_escape_format, strtol(octal,NULL,8));\n\t\tfor (e=escape; *e; e++) {\n\t\t (term->enhanced_writec)(*e);\n\t\t}\n\t\tbreak;\n\t }\n\n\t /* This was the original (prior to version 4) enhanced text code specific\n\t * to the reserved characters of PostScript.\n\t */\n\t if (term->flags & TERM_IS_POSTSCRIPT) {\n\t\tif (p[1]=='\\\\' || p[1]=='(' || p[1]==')') {\n\t\t (term->enhanced_writec)('\\\\');\n\t\t} else if (strchr(\"^_@&~{}\",p[1]) == NULL) {\n\t\t (term->enhanced_writec)('\\\\');\n\t\t (term->enhanced_writec)('\\\\');\n\t\t break;\n\t\t}\n\t }\n\n\t /* Step past the backslash character in the input stream */\n\t ++p;\n\n\t /* HBB: Avoid broken output if there's a \\ exactly at the end of the line */\n\t if (*p == '\\0') {\n\t\tint_warn(NO_CARET, \"enhanced text parser -- spurious backslash\");\n\t\tbreak;\n\t }\n\n\t /* SVG requires an escaped '&' to be passed as something else */\n\t /* FIXME: terminal-dependent code does not belong here */\n\t if (*p == '&' && encoding == S_ENC_DEFAULT && !strcmp(term->name, \"svg\")) {\n\t\t(term->enhanced_writec)('\\376');\n\t\tbreak;\n\t }\n\n\t /* print the character following the backslash */\n\t (term->enhanced_writec)(*p);\n\t break;\n\t /*}}}*/\n\n\tdefault:\n\t /*{{{ print it */\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t (term->enhanced_writec)(*p);\n\t /*}}}*/\n\t} /* switch (*p) */\n\n\t/* like TeX, we only do one character in a recursion, unless it's\n\t * in braces\n\t */\n\n\tif (!brace) {\n\t (term->enhanced_flush)();\n\t return(p); /* the ++p in the outer copy will increment us */\n\t}\n\n\tif (*p) /* only not true if { not terminated, I think */\n\t ++p;\n } /* while (*p) */\n\n (term->enhanced_flush)();\n return p;\n}", "target": 1, "cwe": ["CWE-787"], "project": "gnuplot", "commit_id": "963c7df3e0c5266efff260d0dff757dfe03d3632", "hash": 274740808820572089301785844084339721669, "size": 391, "message": "Better error handling for faulty font syntax\n\nA missing close-quote in an enhanced text font specification could\ncause a segfault.\nBug #2303", "dataset": "other", "idx": 216804}
  1082. {"func": "enhanced_recursion(\n const char *p,\n TBOOLEAN brace,\n char *fontname,\n double fontsize,\n double base,\n TBOOLEAN widthflag,\n TBOOLEAN showflag,\n int overprint)\n{\n TBOOLEAN wasitalic, wasbold;\n\n /* Keep track of the style of the font passed in at this recursion level */\n wasitalic = (strstr(fontname, \":Italic\") != NULL);\n wasbold = (strstr(fontname, \":Bold\") != NULL);\n\n FPRINTF((stderr, \"RECURSE WITH \\\"%s\\\", %d %s %.1f %.1f %d %d %d\",\n\t\tp, brace, fontname, fontsize, base, widthflag, showflag, overprint));\n\n /* Start each recursion with a clean string */\n (term->enhanced_flush)();\n\n if (base + fontsize > enhanced_max_height) {\n\tenhanced_max_height = base + fontsize;\n\tENH_DEBUG((\"Setting max height to %.1f\\n\", enhanced_max_height));\n }\n\n if (base < enhanced_min_height) {\n\tenhanced_min_height = base;\n\tENH_DEBUG((\"Setting min height to %.1f\\n\", enhanced_min_height));\n }\n\n while (*p) {\n\tdouble shift;\n\n\t/*\n\t * EAM Jun 2009 - treating bytes one at a time does not work for multibyte\n\t * encodings, including utf-8. If we hit a byte with the high bit set, test\n\t * whether it starts a legal UTF-8 sequence and if so copy the whole thing.\n\t * Other multibyte encodings are still a problem.\n\t * Gnuplot's other defined encodings are all single-byte; for those we\n\t * really do want to treat one byte at a time.\n\t */\n\tif ((*p & 0x80) && (encoding == S_ENC_DEFAULT || encoding == S_ENC_UTF8)) {\n\t unsigned long utf8char;\n\t const char *nextchar = p;\n\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t if (utf8toulong(&utf8char, &nextchar)) {\t/* Legal UTF8 sequence */\n\t\twhile (p < nextchar)\n\t\t (term->enhanced_writec)(*p++);\n\t\tp--;\n\t } else {\t\t\t\t\t/* Some other multibyte encoding? */\n\t\t(term->enhanced_writec)(*p);\n\t }\n/* shige : for Shift_JIS */\n\t} else if ((*p & 0x80) && (encoding == S_ENC_SJIS)) {\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t (term->enhanced_writec)(*(p++));\n\t (term->enhanced_writec)(*p);\n\t} else\n\n\tswitch (*p) {\n\tcase '}' :\n\t /*{{{ deal with it*/\n\t if (brace)\n\t\treturn (p);\n\n\t int_warn(NO_CARET, \"enhanced text parser - spurious }\");\n\t break;\n\t /*}}}*/\n\n\tcase '_' :\n\tcase '^' :\n\t /*{{{ deal with super/sub script*/\n\t shift = (*p == '^') ? 0.5 : -0.3;\n\t (term->enhanced_flush)();\n\t p = enhanced_recursion(p + 1, FALSE, fontname, fontsize * 0.8,\n\t\t\t base + shift * fontsize, widthflag,\n\t\t\t showflag, overprint);\n\t break;\n\t /*}}}*/\n\tcase '{' :\n\t {\n\t\tTBOOLEAN isitalic = FALSE, isbold = FALSE, isnormal = FALSE;\n\t\tconst char *start_of_fontname = NULL;\n\t\tconst char *end_of_fontname = NULL;\n\t\tchar *localfontname = NULL;\n\t\tchar ch;\n\t\tdouble f = fontsize, ovp;\n\n\t\t/* Mar 2014 - this will hold \"fontfamily{:Italic}{:Bold}\" */\n\t\tchar *styledfontname = NULL;\n\n\t\t/*{{{ recurse (possibly with a new font) */\n\n\t\tENH_DEBUG((\"Dealing with {\\n\"));\n\n\t\t/* 30 Sep 2016: Remove incorrect whitespace-eating loop going */\n\t\t/* waaay back to 31-May-2000 */ /* while (*++p == ' '); */\n\t\t++p;\n\t\t/* get vertical offset (if present) for overprinted text */\n\t\tif (overprint == 2) {\n\t\t char *end;\n\t\t ovp = strtod(p,&end);\n\t\t p = end;\n\t\t if (term->flags & TERM_IS_POSTSCRIPT)\n\t\t\tbase = ovp*f;\n\t\t else\n\t\t\tbase += ovp*f;\n\t\t}\n\t\t--p;\n\n\t\tif (*++p == '/') {\n\t\t /* then parse a fontname, optional fontsize */\n\t\t while (*++p == ' ')\n\t\t\t; /* do nothing */\n\t\t if (*p=='-') {\n\t\t\twhile (*++p == ' ')\n\t\t\t ; /* do nothing */\n\t\t }\n\t\t start_of_fontname = p;\n\n\t\t /* Allow font name to be in quotes.\n\t\t * This makes it possible to handle font names containing spaces.\n\t\t */\n\t\t if (*p == '\\'' || *p == '\"') {\n\t\t\t++p;\n\t\t\twhile (*p != '\\0' && *p != '}' && *p != *start_of_fontname)\n\t\t\t ++p;\n\t\t\tif (*p != *start_of_fontname) {\n\t\t\t int_warn(NO_CARET, \"cannot interpret font name %s\", start_of_fontname);\n\t\t\t p = start_of_fontname + 1;\n\t\t\t}\n\t\t\tstart_of_fontname++;\n\t\t\tend_of_fontname = p++;\n\t\t\tch = *p;\n\t\t } else {\n\n\t\t /* Normal unquoted font name */\n\t\t\twhile ((ch = *p) > ' ' && ch != '=' && ch != '*' && ch != '}' && ch != ':')\n\t\t\t ++p;\n\t\t\tend_of_fontname = p;\n\t\t }\n\n\t\t do {\n\t\t\tif (ch == '=') {\n\t\t\t /* get optional font size */\n\t\t\t char *end;\n\t\t\t p++;\n\t\t\t ENH_DEBUG((\"Calling strtod(\\\"%s\\\") ...\", p));\n\t\t\t f = strtod(p, &end);\n\t\t\t p = end;\n\t\t\t ENH_DEBUG((\"Returned %.1f and \\\"%s\\\"\\n\", f, p));\n\n\t\t\t if (f == 0)\n\t\t\t\tf = fontsize;\n\t\t\t else\n\t\t\t\tf *= enhanced_fontscale; /* remember the scaling */\n\n\t\t\t ENH_DEBUG((\"Font size %.1f\\n\", f));\n\t\t\t} else if (ch == '*') {\n\t\t\t /* get optional font size scale factor */\n\t\t\t char *end;\n\t\t\t p++;\n\t\t\t ENH_DEBUG((\"Calling strtod(\\\"%s\\\") ...\", p));\n\t\t\t f = strtod(p, &end);\n\t\t\t p = end;\n\t\t\t ENH_DEBUG((\"Returned %.1f and \\\"%s\\\"\\n\", f, p));\n\n\t\t\t if (f)\n\t\t\t\tf *= fontsize; /* apply the scale factor */\n\t\t\t else\n\t\t\t\tf = fontsize;\n\n\t\t\t ENH_DEBUG((\"Font size %.1f\\n\", f));\n\t\t\t} else if (ch == ':') {\n\t\t\t /* get optional style markup attributes */\n\t\t\t p++;\n\t\t\t if (!strncmp(p,\"Bold\",4))\n\t\t\t\tisbold = TRUE;\n\t\t\t if (!strncmp(p,\"Italic\",6))\n\t\t\t\tisitalic = TRUE;\n\t\t\t if (!strncmp(p,\"Normal\",6))\n\t\t\t\tisnormal = TRUE;\n\t\t\t while (isalpha((unsigned char)*p)) {p++;}\n\t\t\t}\n\t\t } while (((ch = *p) == '=') || (ch == ':') || (ch == '*'));\n\n\t\t if (ch == '}')\n\t\t\tint_warn(NO_CARET,\"bad syntax in enhanced text string\");\n\n\t\t if (*p == ' ')\t/* Eat up a single space following a font spec */\n\t\t\t++p;\n\t\t if (!start_of_fontname || (start_of_fontname == end_of_fontname)) {\n\t\t\t/* Use the font name passed in to us */\n\t\t\tlocalfontname = gp_strdup(fontname);\n\t\t } else {\n\t\t\t/* We found a new font name {/Font ...} */\n\t\t\tint len = end_of_fontname - start_of_fontname;\n\t\t\tlocalfontname = gp_alloc(len+1,\"localfontname\");\n\t\t\tstrncpy(localfontname, start_of_fontname, len);\n\t\t\tlocalfontname[len] = '\\0';\n\t\t }\n\t\t}\n\t\t/*}}}*/\n\n\t\t/* Collect cumulative style markup before passing it in the font name */\n\t\tisitalic = (wasitalic || isitalic) && !isnormal;\n\t\tisbold = (wasbold || isbold) && !isnormal;\n\n\t\tstyledfontname = stylefont(localfontname ? localfontname : fontname,\n\t\t\t\t\t isbold, isitalic);\n\n\t\tp = enhanced_recursion(p, TRUE, styledfontname, f, base,\n\t\t\t\t widthflag, showflag, overprint);\n\n\t\t(term->enhanced_flush)();\n\n\t\tfree(styledfontname);\n\t\tfree(localfontname);\n\n\t\tbreak;\n\t } /* case '{' */\n\tcase '@' :\n\t /*{{{ phantom box - prints next 'char', then restores currentpoint */\n\t (term->enhanced_flush)();\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 3);\n\t p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t widthflag, showflag, overprint);\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 4);\n\t break;\n\t /*}}}*/\n\n\tcase '&' :\n\t /*{{{ character skip - skips space equal to length of character(s) */\n\t (term->enhanced_flush)();\n\n\t p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t widthflag, FALSE, overprint);\n\t break;\n\t /*}}}*/\n\n\tcase '~' :\n\t /*{{{ overprinted text */\n\t /* the second string is overwritten on the first, centered\n\t * horizontally on the first and (optionally) vertically\n\t * shifted by an amount specified (as a fraction of the\n\t * current fontsize) at the beginning of the second string\n\n\t * Note that in this implementation neither the under- nor\n\t * overprinted string can contain syntax that would result\n\t * in additional recursions -- no subscripts,\n\t * superscripts, or anything else, with the exception of a\n\t * font definition at the beginning of the text */\n\n\t (term->enhanced_flush)();\n\t p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t widthflag, showflag, 1);\n\t (term->enhanced_flush)();\n\t if (!*p)\n\t break;\n\t p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,\n\t\t\t FALSE, showflag, 2);\n\n\t overprint = 0; /* may not be necessary, but just in case . . . */\n\t break;\n\t /*}}}*/\n\n\tcase '(' :\n\tcase ')' :\n\t /*{{{ an escape and print it */\n\t /* special cases */\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t if (term->flags & TERM_IS_POSTSCRIPT)\n\t\t(term->enhanced_writec)('\\\\');\n\t (term->enhanced_writec)(*p);\n\t break;\n\t /*}}}*/\n\n\tcase '\\\\' :\n\t /*{{{ various types of escape sequences, some context-dependent */\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\n\t /* Unicode represented as \\U+hhhhh where hhhhh is hexadecimal code point.\n\t * For UTF-8 encoding we translate hhhhh to a UTF-8 byte sequence and\n\t * output the bytes one by one.\n\t */\n\t if (p[1] == 'U' && p[2] == '+') {\n\t\tif (encoding == S_ENC_UTF8) {\n\t\t uint32_t codepoint;\n\t\t unsigned char utf8char[8];\n\t\t int i, length;\n\n\t\t sscanf(&(p[3]), \"%5x\", &codepoint);\n\t\t length = ucs4toutf8(codepoint, utf8char);\n\t\t p += (codepoint > 0xFFFF) ? 7 : 6;\n\t\t for (i=0; i<length; i++)\n\t\t\t(term->enhanced_writec)(utf8char[i]);\n\t\t break;\n\t\t}\n\n\t /* FIXME: non-utf8 environments not yet supported.\n\t * Note that some terminals may have an alternative way to handle unicode\n\t * escape sequences that is not dependent on encoding.\n\t * E.g. svg and html output could convert to xml sequences &#xhhhh;\n\t * For these cases we must retain the leading backslash so that the\n\t * unicode escape sequence can be recognized by the terminal driver.\n\t */\n\t\t(term->enhanced_writec)(p[0]);\n\t\tbreak;\n\t }\n\n\t /* Enhanced mode always uses \\xyz as an octal character representation\n\t * but each terminal type must give us the actual output format wanted.\n\t * pdf.trm wants the raw character code, which is why we use strtol();\n\t * most other terminal types want some variant of \"\\\\%o\".\n\t */\n\t if (p[1] >= '0' && p[1] <= '7') {\n\t\tchar *e, escape[16], octal[4] = {'\\0','\\0','\\0','\\0'};\n\n\t\toctal[0] = *(++p);\n\t\tif (p[1] >= '0' && p[1] <= '7') {\n\t\t octal[1] = *(++p);\n\t\t if (p[1] >= '0' && p[1] <= '7')\n\t\t\toctal[2] = *(++p);\n\t\t}\n\t\tsprintf(escape, enhanced_escape_format, strtol(octal,NULL,8));\n\t\tfor (e=escape; *e; e++) {\n\t\t (term->enhanced_writec)(*e);\n\t\t}\n\t\tbreak;\n\t }\n\n\t /* This was the original (prior to version 4) enhanced text code specific\n\t * to the reserved characters of PostScript.\n\t */\n\t if (term->flags & TERM_IS_POSTSCRIPT) {\n\t\tif (p[1]=='\\\\' || p[1]=='(' || p[1]==')') {\n\t\t (term->enhanced_writec)('\\\\');\n\t\t} else if (strchr(\"^_@&~{}\",p[1]) == NULL) {\n\t\t (term->enhanced_writec)('\\\\');\n\t\t (term->enhanced_writec)('\\\\');\n\t\t break;\n\t\t}\n\t }\n\n\t /* Step past the backslash character in the input stream */\n\t ++p;\n\n\t /* HBB: Avoid broken output if there's a \\ exactly at the end of the line */\n\t if (*p == '\\0') {\n\t\tint_warn(NO_CARET, \"enhanced text parser -- spurious backslash\");\n\t\tbreak;\n\t }\n\n\t /* SVG requires an escaped '&' to be passed as something else */\n\t /* FIXME: terminal-dependent code does not belong here */\n\t if (*p == '&' && encoding == S_ENC_DEFAULT && !strcmp(term->name, \"svg\")) {\n\t\t(term->enhanced_writec)('\\376');\n\t\tbreak;\n\t }\n\n\t /* print the character following the backslash */\n\t (term->enhanced_writec)(*p);\n\t break;\n\t /*}}}*/\n\n\tdefault:\n\t /*{{{ print it */\n\t (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);\n\t (term->enhanced_writec)(*p);\n\t /*}}}*/\n\t} /* switch (*p) */\n\n\t/* like TeX, we only do one character in a recursion, unless it's\n\t * in braces\n\t */\n\n\tif (!brace) {\n\t (term->enhanced_flush)();\n\t return(p); /* the ++p in the outer copy will increment us */\n\t}\n\n\tif (*p) /* only not true if { not terminated, I think */\n\t ++p;\n } /* while (*p) */\n\n (term->enhanced_flush)();\n return p;\n}", "target": 0, "cwe": ["CWE-787"], "project": "gnuplot", "commit_id": "963c7df3e0c5266efff260d0dff757dfe03d3632", "hash": 149342336659596954781928859318497749578, "size": 391, "message": "Better error handling for faulty font syntax\n\nA missing close-quote in an enhanced text font specification could\ncause a segfault.\nBug #2303", "dataset": "other", "idx": 506600}
  1083. {"func": "mysql_select(THD *thd,\n\t TABLE_LIST *tables, uint wild_num, List<Item> &fields,\n\t COND *conds, uint og_num, ORDER *order, ORDER *group,\n\t Item *having, ORDER *proc_param, ulonglong select_options,\n\t select_result *result, SELECT_LEX_UNIT *unit,\n\t SELECT_LEX *select_lex)\n{\n int err= 0;\n bool free_join= 1;\n DBUG_ENTER(\"mysql_select\");\n\n select_lex->context.resolve_in_select_list= TRUE;\n JOIN *join;\n if (select_lex->join != 0)\n {\n join= select_lex->join;\n /*\n is it single SELECT in derived table, called in derived table\n creation\n */\n if (select_lex->linkage != DERIVED_TABLE_TYPE ||\n\t(select_options & SELECT_DESCRIBE))\n {\n if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)\n {\n /*\n Original join tabs might be overwritten at first\n subselect execution. So we need to restore them.\n */\n Item_subselect *subselect= select_lex->master_unit()->item;\n if (subselect && subselect->is_uncacheable() && join->reinit())\n DBUG_RETURN(TRUE);\n }\n else\n {\n if ((err= join->prepare( tables, wild_num,\n conds, og_num, order, false, group, having,\n proc_param, select_lex, unit)))\n\t{\n\t goto err;\n\t}\n }\n }\n free_join= 0;\n join->select_options= select_options;\n }\n else\n {\n if (thd->lex->describe)\n select_options|= SELECT_DESCRIBE;\n\n /*\n When in EXPLAIN, delay deleting the joins so that they are still\n available when we're producing EXPLAIN EXTENDED warning text.\n */\n if (select_options & SELECT_DESCRIBE)\n free_join= 0;\n\n if (!(join= new (thd->mem_root) JOIN(thd, fields, select_options, result)))\n\tDBUG_RETURN(TRUE);\n THD_STAGE_INFO(thd, stage_init);\n thd->lex->used_tables=0;\n if ((err= join->prepare(tables, wild_num,\n conds, og_num, order, false, group, having, proc_param,\n select_lex, unit)))\n {\n goto err;\n }\n }\n\n if ((err= join->optimize()))\n {\n goto err;\t\t\t\t\t// 1\n }\n\n if (thd->lex->describe & DESCRIBE_EXTENDED)\n {\n join->conds_history= join->conds;\n join->having_history= (join->having?join->having:join->tmp_having);\n }\n\n if (unlikely(thd->is_error()))\n goto err;\n\n join->exec();\n\n if (thd->lex->describe & DESCRIBE_EXTENDED)\n {\n select_lex->where= join->conds_history;\n select_lex->having= join->having_history;\n }\n\nerr:\n if (free_join)\n {\n THD_STAGE_INFO(thd, stage_end);\n err|= (int)(select_lex->cleanup());\n DBUG_RETURN(err || thd->is_error());\n }\n DBUG_RETURN(join->error ? join->error: err);\n}", "target": 1, "cwe": [], "project": "server", "commit_id": "ff77a09bda884fe6bf3917eb29b9d3a2f53f919b", "hash": 228957657691958004226213087331589913552, "size": 101, "message": "MDEV-22464 Server crash on UPDATE with nested subquery\n\nUninitialized ref_pointer_array[] because setup_fields() got empty\nfields list. mysql_multi_update() for some reason does that by\nsubstituting the fields list with empty total_list for the\nmysql_select() call (looks like wrong merge since total_list is not\nused anywhere else and is always empty). The fix would be to return\nback the original fields list. But this fails update_use_source.test\ncase:\n\n --error ER_BAD_FIELD_ERROR\n update v1 set t1c1=2 order by 1;\n\nActually not failing the above seems to be ok.\n\nThe other fix would be to keep resolve_in_select_list false (and that\nkeeps outer context from being resolved in\nItem_ref::fix_fields()). This fix is more consistent with how SELECT\nbehaves:\n\n --error ER_SUBQUERY_NO_1_ROW\n select a from t1 where a= (select 2 from t1 having (a = 3));\n\nSo this patch implements this fix.", "dataset": "other", "idx": 216900}
  1084. {"func": "mysql_select(THD *thd,\n\t TABLE_LIST *tables, uint wild_num, List<Item> &fields,\n\t COND *conds, uint og_num, ORDER *order, ORDER *group,\n\t Item *having, ORDER *proc_param, ulonglong select_options,\n\t select_result *result, SELECT_LEX_UNIT *unit,\n\t SELECT_LEX *select_lex)\n{\n int err= 0;\n bool free_join= 1;\n DBUG_ENTER(\"mysql_select\");\n\n if (!fields.is_empty())\n select_lex->context.resolve_in_select_list= true;\n JOIN *join;\n if (select_lex->join != 0)\n {\n join= select_lex->join;\n /*\n is it single SELECT in derived table, called in derived table\n creation\n */\n if (select_lex->linkage != DERIVED_TABLE_TYPE ||\n\t(select_options & SELECT_DESCRIBE))\n {\n if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)\n {\n /*\n Original join tabs might be overwritten at first\n subselect execution. So we need to restore them.\n */\n Item_subselect *subselect= select_lex->master_unit()->item;\n if (subselect && subselect->is_uncacheable() && join->reinit())\n DBUG_RETURN(TRUE);\n }\n else\n {\n if ((err= join->prepare( tables, wild_num,\n conds, og_num, order, false, group, having,\n proc_param, select_lex, unit)))\n\t{\n\t goto err;\n\t}\n }\n }\n free_join= 0;\n join->select_options= select_options;\n }\n else\n {\n if (thd->lex->describe)\n select_options|= SELECT_DESCRIBE;\n\n /*\n When in EXPLAIN, delay deleting the joins so that they are still\n available when we're producing EXPLAIN EXTENDED warning text.\n */\n if (select_options & SELECT_DESCRIBE)\n free_join= 0;\n\n if (!(join= new (thd->mem_root) JOIN(thd, fields, select_options, result)))\n\tDBUG_RETURN(TRUE);\n THD_STAGE_INFO(thd, stage_init);\n thd->lex->used_tables=0;\n if ((err= join->prepare(tables, wild_num,\n conds, og_num, order, false, group, having, proc_param,\n select_lex, unit)))\n {\n goto err;\n }\n }\n\n if ((err= join->optimize()))\n {\n goto err;\t\t\t\t\t// 1\n }\n\n if (thd->lex->describe & DESCRIBE_EXTENDED)\n {\n join->conds_history= join->conds;\n join->having_history= (join->having?join->having:join->tmp_having);\n }\n\n if (unlikely(thd->is_error()))\n goto err;\n\n join->exec();\n\n if (thd->lex->describe & DESCRIBE_EXTENDED)\n {\n select_lex->where= join->conds_history;\n select_lex->having= join->having_history;\n }\n\nerr:\n if (free_join)\n {\n THD_STAGE_INFO(thd, stage_end);\n err|= (int)(select_lex->cleanup());\n DBUG_RETURN(err || thd->is_error());\n }\n DBUG_RETURN(join->error ? join->error: err);\n}", "target": 0, "cwe": [], "project": "server", "commit_id": "ff77a09bda884fe6bf3917eb29b9d3a2f53f919b", "hash": 220114340611820363716888880887583014373, "size": 102, "message": "MDEV-22464 Server crash on UPDATE with nested subquery\n\nUninitialized ref_pointer_array[] because setup_fields() got empty\nfields list. mysql_multi_update() for some reason does that by\nsubstituting the fields list with empty total_list for the\nmysql_select() call (looks like wrong merge since total_list is not\nused anywhere else and is always empty). The fix would be to return\nback the original fields list. But this fails update_use_source.test\ncase:\n\n --error ER_BAD_FIELD_ERROR\n update v1 set t1c1=2 order by 1;\n\nActually not failing the above seems to be ok.\n\nThe other fix would be to keep resolve_in_select_list false (and that\nkeeps outer context from being resolved in\nItem_ref::fix_fields()). This fix is more consistent with how SELECT\nbehaves:\n\n --error ER_SUBQUERY_NO_1_ROW\n select a from t1 where a= (select 2 from t1 having (a = 3));\n\nSo this patch implements this fix.", "dataset": "other", "idx": 508727}
  1085. {"func": " bool const_item() const { return used_tables() == 0; }", "target": 1, "cwe": ["CWE-617"], "project": "server", "commit_id": "2e7891080667c59ac80f788eef4d59d447595772", "hash": 176129634520084965565043652739444849021, "size": 1, "message": "MDEV-25635 Assertion failure when pushing from HAVING into WHERE of view\n\nThis bug could manifest itself after pushing a where condition over a\nmergeable derived table / view / CTE DT into a grouping view / derived\ntable / CTE V whose item list contained set functions with constant\narguments such as MIN(2), SUM(1) etc. In such cases the field references\nused in the condition pushed into the view V that correspond set functions\nare wrapped into Item_direct_view_ref wrappers. Due to a wrong implementation\nof the virtual method const_item() for the class Item_direct_view_ref the\nwrapped set functions with constant arguments could be erroneously taken\nfor constant items. This could lead to a wrong result set returned by the\nmain select query in 10.2. In 10.4 where a possibility of pushing condition\nfrom HAVING into WHERE had been added this could cause a crash.\n\nApproved by Sergey Petrunya <sergey.petrunya@mariadb.com>", "dataset": "other", "idx": 216904}
  1086. {"func": " bool const_item() const { return true; }", "target": 0, "cwe": ["CWE-617"], "project": "server", "commit_id": "2e7891080667c59ac80f788eef4d59d447595772", "hash": 159584463450720417609161999255773197240, "size": 1, "message": "MDEV-25635 Assertion failure when pushing from HAVING into WHERE of view\n\nThis bug could manifest itself after pushing a where condition over a\nmergeable derived table / view / CTE DT into a grouping view / derived\ntable / CTE V whose item list contained set functions with constant\narguments such as MIN(2), SUM(1) etc. In such cases the field references\nused in the condition pushed into the view V that correspond set functions\nare wrapped into Item_direct_view_ref wrappers. Due to a wrong implementation\nof the virtual method const_item() for the class Item_direct_view_ref the\nwrapped set functions with constant arguments could be erroneously taken\nfor constant items. This could lead to a wrong result set returned by the\nmain select query in 10.2. In 10.4 where a possibility of pushing condition\nfrom HAVING into WHERE had been added this could cause a crash.\n\nApproved by Sergey Petrunya <sergey.petrunya@mariadb.com>", "dataset": "other", "idx": 509429}
  1087. {"func": "int setup_conds(THD *thd, TABLE_LIST *tables, List<TABLE_LIST> &leaves,\n COND **conds)\n{\n SELECT_LEX *select_lex= thd->lex->current_select;\n TABLE_LIST *table= NULL;\t// For HP compilers\n /*\n it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX\n which belong to LEX, i.e. most up SELECT) will be updated by\n INSERT/UPDATE/LOAD\n NOTE: using this condition helps to prevent call of prepare_check_option()\n from subquery of VIEW, because tables of subquery belongs to VIEW\n (see condition before prepare_check_option() call)\n */\n bool it_is_update= (select_lex == thd->lex->first_select_lex()) &&\n thd->lex->which_check_option_applicable();\n bool save_is_item_list_lookup= select_lex->is_item_list_lookup;\n TABLE_LIST *derived= select_lex->master_unit()->derived;\n DBUG_ENTER(\"setup_conds\");\n\n select_lex->is_item_list_lookup= 0;\n\n thd->column_usage= MARK_COLUMNS_READ;\n DBUG_PRINT(\"info\", (\"thd->column_usage: %d\", thd->column_usage));\n select_lex->cond_count= 0;\n select_lex->between_count= 0;\n select_lex->max_equal_elems= 0;\n\n for (table= tables; table; table= table->next_local)\n {\n if (select_lex == thd->lex->first_select_lex() &&\n select_lex->first_cond_optimization &&\n table->merged_for_insert &&\n table->prepare_where(thd, conds, FALSE))\n goto err_no_arena;\n }\n\n if (*conds)\n {\n thd->where=\"where clause\";\n DBUG_EXECUTE(\"where\",\n print_where(*conds,\n \"WHERE in setup_conds\",\n QT_ORDINARY););\n /*\n Wrap alone field in WHERE clause in case it will be outer field of subquery\n which need persistent pointer on it, but conds could be changed by optimizer\n */\n if ((*conds)->type() == Item::FIELD_ITEM && !derived)\n wrap_ident(thd, conds);\n (*conds)->mark_as_condition_AND_part(NO_JOIN_NEST);\n if ((*conds)->fix_fields_if_needed_for_bool(thd, conds))\n goto err_no_arena;\n }\n\n /*\n Apply fix_fields() to all ON clauses at all levels of nesting,\n including the ones inside view definitions.\n */\n if (setup_on_expr(thd, tables, it_is_update))\n goto err_no_arena;\n\n if (!thd->stmt_arena->is_conventional())\n {\n /*\n We are in prepared statement preparation code => we should store\n WHERE clause changing for next executions.\n\n We do this ON -> WHERE transformation only once per PS/SP statement.\n */\n select_lex->where= *conds;\n }\n thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;\n DBUG_RETURN(thd->is_error());\n\nerr_no_arena:\n select_lex->is_item_list_lookup= save_is_item_list_lookup;\n DBUG_RETURN(1);\n}", "target": 1, "cwe": ["CWE-416"], "project": "server", "commit_id": "0beed9b5e933f0ff79b3bb346524f7a451d14e38", "hash": 262702369848133778206065023423367520417, "size": 78, "message": "MDEV-28097 use-after-free when WHERE has subquery with an outer reference in HAVING\n\nwhen resolving WHERE and ON clauses, do not look in\nSELECT list/aliases.", "dataset": "other", "idx": 216967}
  1088. {"func": "int setup_conds(THD *thd, TABLE_LIST *tables, List<TABLE_LIST> &leaves,\n COND **conds)\n{\n SELECT_LEX *select_lex= thd->lex->current_select;\n TABLE_LIST *table= NULL;\t// For HP compilers\n /*\n it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX\n which belong to LEX, i.e. most up SELECT) will be updated by\n INSERT/UPDATE/LOAD\n NOTE: using this condition helps to prevent call of prepare_check_option()\n from subquery of VIEW, because tables of subquery belongs to VIEW\n (see condition before prepare_check_option() call)\n */\n bool it_is_update= (select_lex == thd->lex->first_select_lex()) &&\n thd->lex->which_check_option_applicable();\n bool save_is_item_list_lookup= select_lex->is_item_list_lookup;\n TABLE_LIST *derived= select_lex->master_unit()->derived;\n bool save_resolve_in_select_list= select_lex->context.resolve_in_select_list;\n DBUG_ENTER(\"setup_conds\");\n\n select_lex->is_item_list_lookup= 0;\n select_lex->context.resolve_in_select_list= false;\n\n thd->column_usage= MARK_COLUMNS_READ;\n DBUG_PRINT(\"info\", (\"thd->column_usage: %d\", thd->column_usage));\n select_lex->cond_count= 0;\n select_lex->between_count= 0;\n select_lex->max_equal_elems= 0;\n\n for (table= tables; table; table= table->next_local)\n {\n if (select_lex == thd->lex->first_select_lex() &&\n select_lex->first_cond_optimization &&\n table->merged_for_insert &&\n table->prepare_where(thd, conds, FALSE))\n goto err_no_arena;\n }\n\n if (*conds)\n {\n thd->where=\"where clause\";\n DBUG_EXECUTE(\"where\",\n print_where(*conds,\n \"WHERE in setup_conds\",\n QT_ORDINARY););\n /*\n Wrap alone field in WHERE clause in case it will be outer field of subquery\n which need persistent pointer on it, but conds could be changed by optimizer\n */\n if ((*conds)->type() == Item::FIELD_ITEM && !derived)\n wrap_ident(thd, conds);\n (*conds)->mark_as_condition_AND_part(NO_JOIN_NEST);\n if ((*conds)->fix_fields_if_needed_for_bool(thd, conds))\n goto err_no_arena;\n }\n\n /*\n Apply fix_fields() to all ON clauses at all levels of nesting,\n including the ones inside view definitions.\n */\n if (setup_on_expr(thd, tables, it_is_update))\n goto err_no_arena;\n\n if (!thd->stmt_arena->is_conventional())\n {\n /*\n We are in prepared statement preparation code => we should store\n WHERE clause changing for next executions.\n\n We do this ON -> WHERE transformation only once per PS/SP statement.\n */\n select_lex->where= *conds;\n }\n thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;\n select_lex->context.resolve_in_select_list= save_resolve_in_select_list;\n DBUG_RETURN(thd->is_error());\n\nerr_no_arena:\n select_lex->is_item_list_lookup= save_is_item_list_lookup;\n DBUG_RETURN(1);\n}", "target": 0, "cwe": ["CWE-416"], "project": "server", "commit_id": "0beed9b5e933f0ff79b3bb346524f7a451d14e38", "hash": 194559671954579966469337004526733694851, "size": 81, "message": "MDEV-28097 use-after-free when WHERE has subquery with an outer reference in HAVING\n\nwhen resolving WHERE and ON clauses, do not look in\nSELECT list/aliases.", "dataset": "other", "idx": 514568}
  1089. {"func": "address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,\n hwaddr *xlat, hwaddr *plen,\n MemTxAttrs attrs, int *prot)\n{\n MemoryRegionSection *section;\n IOMMUMemoryRegion *iommu_mr;\n IOMMUMemoryRegionClass *imrc;\n IOMMUTLBEntry iotlb;\n int iommu_idx;\n AddressSpaceDispatch *d =\n qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);\n\n for (;;) {\n section = address_space_translate_internal(d, addr, &addr, plen, false);\n\n iommu_mr = memory_region_get_iommu(section->mr);\n if (!iommu_mr) {\n break;\n }\n\n imrc = memory_region_get_iommu_class_nocheck(iommu_mr);\n\n iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);\n tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);\n /* We need all the permissions, so pass IOMMU_NONE so the IOMMU\n * doesn't short-cut its translation table walk.\n */\n iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);\n addr = ((iotlb.translated_addr & ~iotlb.addr_mask)\n | (addr & iotlb.addr_mask));\n /* Update the caller's prot bits to remove permissions the IOMMU\n * is giving us a failure response for. If we get down to no\n * permissions left at all we can give up now.\n */\n if (!(iotlb.perm & IOMMU_RO)) {\n *prot &= ~(PAGE_READ | PAGE_EXEC);\n }\n if (!(iotlb.perm & IOMMU_WO)) {\n *prot &= ~PAGE_WRITE;\n }\n\n if (!*prot) {\n goto translate_fail;\n }\n\n d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));\n }\n\n assert(!memory_region_is_iommu(section->mr));\n *xlat = addr;\n return section;\n\ntranslate_fail:\n return &d->map.sections[PHYS_SECTION_UNASSIGNED];\n}", "target": 1, "cwe": ["CWE-908"], "project": "qemu", "commit_id": "418ade7849ce7641c0f7333718caf5091a02fd4c", "hash": 270213508919707612636527664610402006659, "size": 55, "message": "softmmu: Always initialize xlat in address_space_translate_for_iotlb\n\nThe bug is an uninitialized memory read, along the translate_fail\npath, which results in garbage being read from iotlb_to_section,\nwhich can lead to a crash in io_readx/io_writex.\n\nThe bug may be fixed by writing any value with zero\nin ~TARGET_PAGE_MASK, so that the call to iotlb_to_section using\nthe xlat'ed address returns io_mem_unassigned, as desired by the\ntranslate_fail path.\n\nIt is most useful to record the original physical page address,\nwhich will eventually be logged by memory_region_access_valid\nwhen the access is rejected by unassigned_mem_accepts.\n\nResolves: https://gitlab.com/qemu-project/qemu/-/issues/1065\nSigned-off-by: Richard Henderson <richard.henderson@linaro.org>\nReviewed-by: Peter Maydell <peter.maydell@linaro.org>\nMessage-Id: <20220621153829.366423-1-richard.henderson@linaro.org>", "dataset": "other", "idx": 216983}
  1090. {"func": "address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr orig_addr,\n hwaddr *xlat, hwaddr *plen,\n MemTxAttrs attrs, int *prot)\n{\n MemoryRegionSection *section;\n IOMMUMemoryRegion *iommu_mr;\n IOMMUMemoryRegionClass *imrc;\n IOMMUTLBEntry iotlb;\n int iommu_idx;\n hwaddr addr = orig_addr;\n AddressSpaceDispatch *d =\n qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);\n\n for (;;) {\n section = address_space_translate_internal(d, addr, &addr, plen, false);\n\n iommu_mr = memory_region_get_iommu(section->mr);\n if (!iommu_mr) {\n break;\n }\n\n imrc = memory_region_get_iommu_class_nocheck(iommu_mr);\n\n iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);\n tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);\n /* We need all the permissions, so pass IOMMU_NONE so the IOMMU\n * doesn't short-cut its translation table walk.\n */\n iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);\n addr = ((iotlb.translated_addr & ~iotlb.addr_mask)\n | (addr & iotlb.addr_mask));\n /* Update the caller's prot bits to remove permissions the IOMMU\n * is giving us a failure response for. If we get down to no\n * permissions left at all we can give up now.\n */\n if (!(iotlb.perm & IOMMU_RO)) {\n *prot &= ~(PAGE_READ | PAGE_EXEC);\n }\n if (!(iotlb.perm & IOMMU_WO)) {\n *prot &= ~PAGE_WRITE;\n }\n\n if (!*prot) {\n goto translate_fail;\n }\n\n d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));\n }\n\n assert(!memory_region_is_iommu(section->mr));\n *xlat = addr;\n return section;\n\ntranslate_fail:\n /*\n * We should be given a page-aligned address -- certainly\n * tlb_set_page_with_attrs() does so. The page offset of xlat\n * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.\n * The page portion of xlat will be logged by memory_region_access_valid()\n * when this memory access is rejected, so use the original untranslated\n * physical address.\n */\n assert((orig_addr & ~TARGET_PAGE_MASK) == 0);\n *xlat = orig_addr;\n return &d->map.sections[PHYS_SECTION_UNASSIGNED];\n}", "target": 0, "cwe": ["CWE-908"], "project": "qemu", "commit_id": "418ade7849ce7641c0f7333718caf5091a02fd4c", "hash": 321441136289267261236517804510082881725, "size": 66, "message": "softmmu: Always initialize xlat in address_space_translate_for_iotlb\n\nThe bug is an uninitialized memory read, along the translate_fail\npath, which results in garbage being read from iotlb_to_section,\nwhich can lead to a crash in io_readx/io_writex.\n\nThe bug may be fixed by writing any value with zero\nin ~TARGET_PAGE_MASK, so that the call to iotlb_to_section using\nthe xlat'ed address returns io_mem_unassigned, as desired by the\ntranslate_fail path.\n\nIt is most useful to record the original physical page address,\nwhich will eventually be logged by memory_region_access_valid\nwhen the access is rejected by unassigned_mem_accepts.\n\nResolves: https://gitlab.com/qemu-project/qemu/-/issues/1065\nSigned-off-by: Richard Henderson <richard.henderson@linaro.org>\nReviewed-by: Peter Maydell <peter.maydell@linaro.org>\nMessage-Id: <20220621153829.366423-1-richard.henderson@linaro.org>", "dataset": "other", "idx": 514752}
  1091. {"project": "bootstrap-dht", "commit_id": "e809ea80e3527e32c40756eddd8b2ae44bc3af1a", "target": 1, "func": "\tint lazy_bdecode(char const* start, char const* end, lazy_entry& ret\n\t\t, error_code& ec, int* error_pos, int depth_limit, int item_limit)\n\t{\n\t\tchar const* const orig_start = start;\n\t\tret.clear();\n\t\tif (start == end) return 0;\n\n\t\tstd::vector<lazy_entry*> stack;\n\n\t\tstack.push_back(&ret);\n\t\twhile (start <= end)\n\t\t{\n\t\t\tif (stack.empty()) break; // done!\n\n\t\t\tlazy_entry* top = stack.back();\n\n\t\t\tif (int(stack.size()) > depth_limit) TORRENT_FAIL_BDECODE(bdecode_errors::depth_exceeded);\n\t\t\tif (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\tchar t = *start;\n\t\t\t++start;\n\t\t\tif (start >= end && t != 'e') TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\n\t\t\tswitch (top->type())\n\t\t\t{\n\t\t\t\tcase lazy_entry::dict_t:\n\t\t\t\t{\n\t\t\t\t\tif (t == 'e')\n\t\t\t\t\t{\n\t\t\t\t\t\ttop->set_end(start);\n\t\t\t\t\t\tstack.pop_back();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (!numeric(t)) TORRENT_FAIL_BDECODE(bdecode_errors::expected_string);\n\t\t\t\t\tboost::int64_t len = t - '0';\n\t\t\t\t\tbdecode_errors::error_code_enum e = bdecode_errors::no_error;\n\t\t\t\t\tstart = parse_int(start, end, ':', len, e);\n\t\t\t\t\tif (e)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(e);\n\n\t\t\t\t\tif (start + len + 1 > end)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\n\t\t\t\t\tif (len < 0)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::overflow);\n\n\t\t\t\t\t++start;\n\t\t\t\t\tif (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\tlazy_entry* ent = top->dict_append(start);\n\t\t\t\t\tif (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);\n\t\t\t\t\tstart += len;\n\t\t\t\t\tif (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\tstack.push_back(ent);\n\t\t\t\t\tt = *start;\n\t\t\t\t\t++start;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase lazy_entry::list_t:\n\t\t\t\t{\n\t\t\t\t\tif (t == 'e')\n\t\t\t\t\t{\n\t\t\t\t\t\ttop->set_end(start);\n\t\t\t\t\t\tstack.pop_back();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tlazy_entry* ent = top->list_append();\n\t\t\t\t\tif (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);\n\t\t\t\t\tstack.push_back(ent);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: break;\n\t\t\t}\n\n\t\t\t--item_limit;\n\t\t\tif (item_limit <= 0) TORRENT_FAIL_BDECODE(bdecode_errors::limit_exceeded);\n\n\t\t\ttop = stack.back();\n\t\t\tswitch (t)\n\t\t\t{\n\t\t\t\tcase 'd':\n\t\t\t\t\ttop->construct_dict(start - 1);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase 'l':\n\t\t\t\t\ttop->construct_list(start - 1);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase 'i':\n\t\t\t\t{\n\t\t\t\t\tchar const* int_start = start;\n\t\t\t\t\tstart = find_char(start, end, 'e');\n\t\t\t\t\ttop->construct_int(int_start, start - int_start);\n\t\t\t\t\tif (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\tTORRENT_ASSERT(*start == 'e');\n\t\t\t\t\t++start;\n\t\t\t\t\tstack.pop_back();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tif (!numeric(t))\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::expected_value);\n\n\t\t\t\t\tboost::int64_t len = t - '0';\n\t\t\t\t\tbdecode_errors::error_code_enum e = bdecode_errors::no_error;\n\t\t\t\t\tstart = parse_int(start, end, ':', len, e);\n\t\t\t\t\tif (e)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(e);\n\t\t\t\t\tif (start + len + 1 > end)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\tif (len < 0)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::overflow);\n\n\t\t\t\t\t++start;\n\t\t\t\t\ttop->construct_string(start, int(len));\n\t\t\t\t\tstack.pop_back();\n\t\t\t\t\tstart += len;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\treturn 0;\n\t}", "idx": 217129, "cwe": "CWE-20", "hash": 303897306844529998268848892134869917191, "dataset": "other"}
  1092. {"project": "bootstrap-dht", "commit_id": "e809ea80e3527e32c40756eddd8b2ae44bc3af1a", "target": 0, "func": "\tint lazy_bdecode(char const* start, char const* end, lazy_entry& ret\n\t\t, error_code& ec, int* error_pos, int depth_limit, int item_limit)\n\t{\n\t\tchar const* const orig_start = start;\n\t\tret.clear();\n\t\tif (start == end) return 0;\n\n\t\tstd::vector<lazy_entry*> stack;\n\n\t\tstack.push_back(&ret);\n\t\twhile (start <= end)\n\t\t{\n\t\t\tif (stack.empty()) break; // done!\n\n\t\t\tlazy_entry* top = stack.back();\n\n\t\t\tif (int(stack.size()) > depth_limit) TORRENT_FAIL_BDECODE(bdecode_errors::depth_exceeded);\n\t\t\tif (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\tchar t = *start;\n\t\t\t++start;\n\t\t\tif (start >= end && t != 'e') TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\n\t\t\tswitch (top->type())\n\t\t\t{\n\t\t\t\tcase lazy_entry::dict_t:\n\t\t\t\t{\n\t\t\t\t\tif (t == 'e')\n\t\t\t\t\t{\n\t\t\t\t\t\ttop->set_end(start);\n\t\t\t\t\t\tstack.pop_back();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (!numeric(t)) TORRENT_FAIL_BDECODE(bdecode_errors::expected_string);\n\t\t\t\t\tboost::int64_t len = t - '0';\n\t\t\t\t\tbdecode_errors::error_code_enum e = bdecode_errors::no_error;\n\t\t\t\t\tstart = parse_int(start, end, ':', len, e);\n\t\t\t\t\tif (e)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(e);\n\n\t\t\t\t\t// remaining buffer size excluding ':'\n\t\t\t\t\tconst ptrdiff_t buff_size = end - start - 1;\n\t\t\t\t\tif (len > buff_size)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\n\t\t\t\t\tif (len < 0)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::overflow);\n\n\t\t\t\t\t++start;\n\t\t\t\t\tif (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\tlazy_entry* ent = top->dict_append(start);\n\t\t\t\t\tif (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);\n\t\t\t\t\tstart += len;\n\t\t\t\t\tif (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\tstack.push_back(ent);\n\t\t\t\t\tt = *start;\n\t\t\t\t\t++start;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase lazy_entry::list_t:\n\t\t\t\t{\n\t\t\t\t\tif (t == 'e')\n\t\t\t\t\t{\n\t\t\t\t\t\ttop->set_end(start);\n\t\t\t\t\t\tstack.pop_back();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tlazy_entry* ent = top->list_append();\n\t\t\t\t\tif (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);\n\t\t\t\t\tstack.push_back(ent);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: break;\n\t\t\t}\n\n\t\t\t--item_limit;\n\t\t\tif (item_limit <= 0) TORRENT_FAIL_BDECODE(bdecode_errors::limit_exceeded);\n\n\t\t\ttop = stack.back();\n\t\t\tswitch (t)\n\t\t\t{\n\t\t\t\tcase 'd':\n\t\t\t\t\ttop->construct_dict(start - 1);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase 'l':\n\t\t\t\t\ttop->construct_list(start - 1);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase 'i':\n\t\t\t\t{\n\t\t\t\t\tchar const* int_start = start;\n\t\t\t\t\tstart = find_char(start, end, 'e');\n\t\t\t\t\ttop->construct_int(int_start, start - int_start);\n\t\t\t\t\tif (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\tTORRENT_ASSERT(*start == 'e');\n\t\t\t\t\t++start;\n\t\t\t\t\tstack.pop_back();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tif (!numeric(t))\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::expected_value);\n\n\t\t\t\t\tboost::int64_t len = t - '0';\n\t\t\t\t\tbdecode_errors::error_code_enum e = bdecode_errors::no_error;\n\t\t\t\t\tstart = parse_int(start, end, ':', len, e);\n\t\t\t\t\tif (e)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(e);\n\n\t\t\t\t\t// remaining buffer size excluding ':'\n\t\t\t\t\tconst ptrdiff_t buff_size = end - start - 1;\n\t\t\t\t\tif (len > buff_size)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\tif (len < 0)\n\t\t\t\t\t\tTORRENT_FAIL_BDECODE(bdecode_errors::overflow);\n\n\t\t\t\t\t++start;\n\t\t\t\t\tif (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);\n\t\t\t\t\ttop->construct_string(start, int(len));\n\t\t\t\t\tstack.pop_back();\n\t\t\t\t\tstart += len;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\treturn 0;\n\t}", "idx": 516864, "cwe": "CWE-20", "hash": 299748660269779445607709495916524481939, "dataset": "other"}
  1093. {"project": "gd-libgd", "commit_id": "47eb44b2e90ca88a08dca9f9a1aa9041e9587f43", "target": 1, "func": "GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP)\n{\n\tint i, j, ret;\n\tunsigned char count;\n\n\tif(flag) {\n\t\tscd->curbit = 0;\n\t\tscd->lastbit = 0;\n\t\tscd->last_byte = 0;\n\t\tscd->done = FALSE;\n\t\treturn 0;\n\t}\n\n\tif((scd->curbit + code_size) >= scd->lastbit) {\n\t\tif(scd->done) {\n\t\t\tif(scd->curbit >= scd->lastbit) {\n\t\t\t\t/* Oh well */\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\n\t\tscd->buf[0] = scd->buf[scd->last_byte - 2];\n\t\tscd->buf[1] = scd->buf[scd->last_byte - 1];\n\n\t\tif((count = GetDataBlock(fd, &scd->buf[2], ZeroDataBlockP)) <= 0) {\n\t\t\tscd->done = TRUE;\n\t\t}\n\n\t\tscd->last_byte = 2 + count;\n\t\tscd->curbit = (scd->curbit - scd->lastbit) + 16;\n\t\tscd->lastbit = (2 + count) * 8;\n\t}\n\n\tret = 0;\n\tfor (i = scd->curbit, j = 0; j < code_size; ++i, ++j) {\n\t\tret |= ((scd->buf[i / 8] & (1 << (i % 8))) != 0) << j;\n\t}\n\n\tscd->curbit += code_size;\n\n\treturn ret;\n}", "idx": 217131, "cwe": "CWE-119", "hash": 8231978434120641265466209385096992968, "dataset": "other"}
  1094. {"project": "gd-libgd", "commit_id": "47eb44b2e90ca88a08dca9f9a1aa9041e9587f43", "target": 0, "func": "GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP)\n{\n\tint i, j, ret;\n\tunsigned char count;\n\n\tif(flag) {\n\t\tscd->curbit = 0;\n\t\tscd->lastbit = 0;\n\t\tscd->last_byte = 0;\n\t\tscd->done = FALSE;\n\t\treturn 0;\n\t}\n\n\tif((scd->curbit + code_size) >= scd->lastbit) {\n\t\tif(scd->done) {\n\t\t\tif(scd->curbit >= scd->lastbit) {\n\t\t\t\t/* Oh well */\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\n\t\tscd->buf[0] = scd->buf[scd->last_byte - 2];\n\t\tscd->buf[1] = scd->buf[scd->last_byte - 1];\n\n\t\tif((count = GetDataBlock(fd, &scd->buf[2], ZeroDataBlockP)) <= 0) {\n\t\t\tscd->done = TRUE;\n\t\t}\n\n\t\tscd->last_byte = 2 + count;\n\t\tscd->curbit = (scd->curbit - scd->lastbit) + 16;\n\t\tscd->lastbit = (2 + count) * 8;\n\t}\n\n\tret = 0;\n\tfor (i = scd->curbit, j = 0; j < code_size; ++i, ++j) {\n\t\tif (i < CSD_BUF_SIZE * 8) {\n\t\t\tret |= ((scd->buf[i / 8] & (1 << (i % 8))) != 0) << j;\n\t\t} else {\n\t\t\tret = -1;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tscd->curbit += code_size;\n\n\treturn ret;\n}", "idx": 516911, "cwe": "CWE-119", "hash": 206733771084438888735004024525182153352, "dataset": "other"}
  1095. {"project": "opaque", "commit_id": "5ddda15d89f5ac82f4416208c5319ace4aecdc36", "target": 1, "func": "void ocall_malloc(size_t size, uint8_t **ret) {\n *ret = static_cast<uint8_t *>(malloc(size));\n}", "idx": 217231, "cwe": "CWE-787", "hash": 130259907659980781908050896256972879576, "dataset": "other"}
  1096. {"project": "opaque", "commit_id": "5ddda15d89f5ac82f4416208c5319ace4aecdc36", "target": 0, "func": "void unsafe_ocall_malloc(size_t size, uint8_t **ret) {\n *ret = static_cast<uint8_t *>(malloc(size));\n}", "idx": 519071, "cwe": "CWE-787", "hash": 130685230068749250584832344066735474045, "dataset": "other"}
  1097. {"project": "univention-corporate-server", "commit_id": "a28053045bd2e778c50ed1acaf4e52e1e34f6e34", "target": 1, "func": "int data_on_connection(int fd, callback_remove_handler remove)\n{\n\tint nread;\n\tchar *network_packet;\n\tchar network_line[8192];\n\tchar *p;\n\tunsigned long id;\n\n\tchar string[1024];\n\tunsigned long msg_id = UINT32_MAX;\n\tenum network_protocol version = network_client_get_version(fd);\n\n\tioctl(fd, FIONREAD, &nread);\n\n\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"new connection data = %d\\n\",nread);\n\n\tif(nread == 0)\n\t{\n\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, \"%d failed, got 0 close connection to listener \", fd);\n\t\tclose(fd);\n\t\tFD_CLR(fd, &readfds);\n\t\tremove(fd);\n\t\tnetwork_client_dump ();\n\t\treturn 0;\n\t}\n\n\n\tif ( nread >= 8192 ) {\n\n\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, \"%d failed, more than 8192 close connection to listener \", fd);\n\t\tclose(fd);\n\t\tFD_CLR(fd, &readfds);\n\t\tremove(fd);\n\n\t\treturn 0;\n\t}\n\n\t/* read the whole package */\n\tnetwork_packet=malloc((nread+1) * sizeof(char));\n\tread(fd, network_packet, nread);\n\tnetwork_packet[nread]='\\0';\n\n\tmemset(network_line, 0, 8192);\n\tp=network_packet;\n\tp_sem(sem_id);\n\n\twhile ( get_network_line(p, network_line) ) {\n\n\t\tif ( strlen(network_line) > 0 ) {\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"line = [%s]\",network_line);\n\t\t}\n\n\t\t\n\t\tif ( !strncmp(network_line, \"MSGID: \", strlen(\"MSGID: \")) ) {\n\t\t\t/* read message id */\n\n\t\t\tmsg_id=strtoul(&(network_line[strlen(\"MSGID: \")]), NULL, 10);\n\n\t\t\tp+=strlen(network_line);\n\n\n\t\t} else if ( !strncmp(network_line, \"Version: \", strlen(\"Version: \")) ) {\n\t\t\tchar *head = network_line, *end;\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: VERSION\");\n\n\t\t\tversion = strtoul(head + 9, &end, 10);\n\t\t\tif (!head[9] || *end)\n\t\t\t\tgoto failed;\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"VERSION=%d\", version);\n\n\t\t\tif (version < network_procotol_version) {\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, \"Forbidden VERSION=%d < %d, close connection to listener\", version, network_procotol_version);\n\t\t\t\tgoto close;\n\t\t\t} else if (version >= PROTOCOL_LAST) {\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, \"Future VERSION=%d\", version);\n\t\t\t\tversion = PROTOCOL_LAST - 1;\n\t\t\t}\n\t\t\tnetwork_client_set_version(fd, version);\n\t\t\t\n\t\t\t/* reset message id */\n\t\t\tmsg_id = UINT32_MAX;\n\n\t\t\tp+=strlen(network_line);\n\n\n\t\t} else if ( !strncmp(network_line, \"Capabilities: \", strlen(\"Capabilities: \")) ) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: Capabilities\");\n\n\t\t\tif ( version > PROTOCOL_UNKNOWN ) {\n\n\t\t\t\tmemset(string, 0, sizeof(string));\n\t\t\t\t\n\t\t\t\tsnprintf(string, sizeof(string), \"Version: %d\\nCapabilities: \\n\\n\", version);\n\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"SEND: %s\", string);\n\n\t\t\t\twrite(fd, string, strlen(string));\n\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"Capabilities recv, but no version line\");\n\t\t\t\t\n\t\t\t}\n\n\t\t\tp+=strlen(network_line);\n\n\n\t\t} else if ( !strncmp(network_line, \"GET_DN \", strlen(\"GET_DN \")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: GET_DN\");\n\n\t\t\tid=strtoul(&(network_line[strlen(\"GET_DN \")]), NULL, 10);\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"id: %ld\",id);\n\n\t\t\tif ( id <= notify_last_id.id) {\n\n\t\t\t\tchar *dn_string = NULL;\n\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"try to read %ld from cache\", id);\n\n\t\t\t\t/* try to read from cache */\n\t\t\t\tif ( (dn_string = notifier_cache_get(id)) == NULL ) {\n\n\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"%ld not found in cache\", id);\n\n\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"%ld get one dn\", id);\n\n\t\t\t\t\t/* read from transaction file, because not in cache */\n\t\t\t\t\tif( (dn_string=notify_transcation_get_one_dn ( id )) == NULL ) {\n\n\t\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"%ld failed \", id);\n\t\t\t\t\t\t/* TODO: maybe close connection? */\n\n\t\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, \"%d failed, close connection to listener \", fd);\n\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t\tFD_CLR(fd, &readfds);\n\t\t\t\t\t\tremove(fd);\n\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ( dn_string != NULL ) {\n\n\t\t\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\n%s\\n\\n\",msg_id,dn_string);\n\n\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"--> %d: [%s]\",fd, string);\n\n\t\t\t\t\twrite(fd, string, strlen(string));\n\n\t\t\t\t\tfree(dn_string);\n\n\t\t\t\t}\n\n\n\t\t\t} else {\n\t\t\t\t/* set wanted id */\n\n\t\t\t\tnetwork_client_set_next_id(fd, id);\n\t\t\t\tnetwork_client_set_msg_id(fd, msg_id);\n\n\t\t\t}\n\n\t\t\tp+=strlen(network_line)+1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\t\t} else if (!strncmp(p, \"WAIT_ID \", 8) && msg_id != UINT32_MAX && version >= PROTOCOL_3) {\n\t\t\tchar *head = network_line, *end;\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: WAIT_ID\");\n\t\t\tid = strtoul(head + 8, &end, 10);\n\t\t\tif (!head[8] || *end)\n\t\t\t\tgoto failed;\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"id: %ld\", id);\n\n\t\t\tif (id <= notify_last_id.id) {\n\t\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\n%ld\\n\\n\", msg_id, notify_last_id.id);\n\t\t\t\twrite(fd, string, strlen(string));\n\t\t\t} else {\n\t\t\t\t/* set wanted id */\n\t\t\t\tnetwork_client_set_next_id(fd, id);\n\t\t\t\tnetwork_client_set_msg_id(fd, msg_id);\n\t\t\t}\n\n\t\t\tp += strlen(network_line) + 1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\t\t} else if ( !strncmp(network_line, \"GET_ID\", strlen(\"GET_ID\")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: GET_ID\");\n\n\t\t\tmemset(string, 0, sizeof(string));\n\n\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\n%ld\\n\\n\",msg_id,notify_last_id.id);\n\n\t\t\twrite(fd, string, strlen(string));\n\n\t\t\tp+=strlen(network_line)+1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\n\t\t} else if ( !strncmp(network_line, \"GET_SCHEMA_ID\", strlen(\"GET_SCHEMA_ID\")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: GET_SCHEMA_ID\");\n\n\t\t\tmemset(string, 0, sizeof(string));\n\n\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\n%ld\\n\\n\",msg_id,SCHEMA_ID);\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"--> %d: [%s]\",fd, string);\n\n\t\t\twrite(fd, string, strlen(string));\n\n\t\t\tp+=strlen(network_line)+1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\n\t\t} else if ( !strncmp(network_line, \"ALIVE\", strlen(\"ALIVE\")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: ALIVE\");\n\n\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\nOKAY\\n\\n\",msg_id);\n\n\t\t\twrite(fd, string, strlen(string));\n\n\t\t\tp+=strlen(network_line)+1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\t\t} else {\n\n\t\t\tp+=strlen(network_line);\n\n\t\t\tif (strlen(network_line) == 0 ) {\n\t\t\t\tp+=1;\n \t\t\t} else {\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, \"Drop package [%s]\", network_line);\n\t\t\t}\n\n\t\t}\n\t}\n\tv_sem(sem_id);\n\n\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"END Package\");\n\t\n\n\tnetwork_client_dump ();\n\n\treturn 0;\n\nfailed:\n\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, \"Failed parsing [%s]\", p);\nclose:\n\tclose(fd);\n\tFD_CLR(fd, &readfds);\n\tremove(fd);\n\treturn 0;\n}", "idx": 217234, "cwe": "CWE-200", "hash": 188430389350604684179918044848604196033, "dataset": "other"}
  1098. {"project": "univention-corporate-server", "commit_id": "a28053045bd2e778c50ed1acaf4e52e1e34f6e34", "target": 0, "func": "int data_on_connection(int fd, callback_remove_handler remove)\n{\n\tint nread;\n\tchar *network_packet;\n\tchar network_line[8192];\n\tchar *p;\n\tunsigned long id;\n\n\tchar string[1024];\n\tunsigned long msg_id = UINT32_MAX;\n\tenum network_protocol version = network_client_get_version(fd);\n\n\tioctl(fd, FIONREAD, &nread);\n\n\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"new connection data = %d\\n\",nread);\n\n\tif(nread == 0)\n\t{\n\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, \"%d failed, got 0 close connection to listener \", fd);\n\t\tclose(fd);\n\t\tFD_CLR(fd, &readfds);\n\t\tremove(fd);\n\t\tnetwork_client_dump ();\n\t\treturn 0;\n\t}\n\n\n\tif ( nread >= 8192 ) {\n\n\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, \"%d failed, more than 8192 close connection to listener \", fd);\n\t\tclose(fd);\n\t\tFD_CLR(fd, &readfds);\n\t\tremove(fd);\n\n\t\treturn 0;\n\t}\n\n\t/* read the whole package */\n\tnetwork_packet=malloc((nread+1) * sizeof(char));\n\tread(fd, network_packet, nread);\n\tnetwork_packet[nread]='\\0';\n\n\tmemset(network_line, 0, 8192);\n\tp=network_packet;\n\tp_sem(sem_id);\n\n\twhile ( get_network_line(p, network_line) ) {\n\n\t\tif ( strlen(network_line) > 0 ) {\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"line = [%s]\",network_line);\n\t\t}\n\n\t\t\n\t\tif ( !strncmp(network_line, \"MSGID: \", strlen(\"MSGID: \")) ) {\n\t\t\t/* read message id */\n\n\t\t\tmsg_id=strtoul(&(network_line[strlen(\"MSGID: \")]), NULL, 10);\n\n\t\t\tp+=strlen(network_line);\n\n\n\t\t} else if ( !strncmp(network_line, \"Version: \", strlen(\"Version: \")) ) {\n\t\t\tchar *head = network_line, *end;\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: VERSION\");\n\n\t\t\tversion = strtoul(head + 9, &end, 10);\n\t\t\tif (!head[9] || *end)\n\t\t\t\tgoto failed;\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"VERSION=%d\", version);\n\n\t\t\tif (version < network_procotol_version) {\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, \"Forbidden VERSION=%d < %d, close connection to listener\", version, network_procotol_version);\n\t\t\t\tgoto close;\n\t\t\t} else if (version >= PROTOCOL_LAST) {\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, \"Future VERSION=%d\", version);\n\t\t\t\tversion = PROTOCOL_LAST - 1;\n\t\t\t}\n\t\t\tnetwork_client_set_version(fd, version);\n\t\t\t\n\t\t\t/* reset message id */\n\t\t\tmsg_id = UINT32_MAX;\n\n\t\t\tp+=strlen(network_line);\n\n\n\t\t} else if ( !strncmp(network_line, \"Capabilities: \", strlen(\"Capabilities: \")) ) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: Capabilities\");\n\n\t\t\tif ( version > PROTOCOL_UNKNOWN ) {\n\n\t\t\t\tmemset(string, 0, sizeof(string));\n\t\t\t\t\n\t\t\t\tsnprintf(string, sizeof(string), \"Version: %d\\nCapabilities: \\n\\n\", version);\n\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"SEND: %s\", string);\n\n\t\t\t\twrite(fd, string, strlen(string));\n\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"Capabilities recv, but no version line\");\n\t\t\t\t\n\t\t\t}\n\n\t\t\tp+=strlen(network_line);\n\n\n\t\t} else if ( !strncmp(network_line, \"GET_DN \", strlen(\"GET_DN \")) && msg_id != UINT32_MAX && version > PROTOCOL_UNKNOWN && version < PROTOCOL_3) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: GET_DN\");\n\n\t\t\tid=strtoul(&(network_line[strlen(\"GET_DN \")]), NULL, 10);\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"id: %ld\",id);\n\n\t\t\tif ( id <= notify_last_id.id) {\n\n\t\t\t\tchar *dn_string = NULL;\n\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"try to read %ld from cache\", id);\n\n\t\t\t\t/* try to read from cache */\n\t\t\t\tif ( (dn_string = notifier_cache_get(id)) == NULL ) {\n\n\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"%ld not found in cache\", id);\n\n\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"%ld get one dn\", id);\n\n\t\t\t\t\t/* read from transaction file, because not in cache */\n\t\t\t\t\tif( (dn_string=notify_transcation_get_one_dn ( id )) == NULL ) {\n\n\t\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"%ld failed \", id);\n\t\t\t\t\t\t/* TODO: maybe close connection? */\n\n\t\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, \"%d failed, close connection to listener \", fd);\n\t\t\t\t\t\tclose(fd);\n\t\t\t\t\t\tFD_CLR(fd, &readfds);\n\t\t\t\t\t\tremove(fd);\n\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ( dn_string != NULL ) {\n\n\t\t\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\n%s\\n\\n\",msg_id,dn_string);\n\n\t\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"--> %d: [%s]\",fd, string);\n\n\t\t\t\t\twrite(fd, string, strlen(string));\n\n\t\t\t\t\tfree(dn_string);\n\n\t\t\t\t}\n\n\n\t\t\t} else {\n\t\t\t\t/* set wanted id */\n\n\t\t\t\tnetwork_client_set_next_id(fd, id);\n\t\t\t\tnetwork_client_set_msg_id(fd, msg_id);\n\n\t\t\t}\n\n\t\t\tp+=strlen(network_line)+1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\t\t} else if (!strncmp(p, \"WAIT_ID \", 8) && msg_id != UINT32_MAX && version >= PROTOCOL_3) {\n\t\t\tchar *head = network_line, *end;\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: WAIT_ID\");\n\t\t\tid = strtoul(head + 8, &end, 10);\n\t\t\tif (!head[8] || *end)\n\t\t\t\tgoto failed;\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"id: %ld\", id);\n\n\t\t\tif (id <= notify_last_id.id) {\n\t\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\n%ld\\n\\n\", msg_id, notify_last_id.id);\n\t\t\t\twrite(fd, string, strlen(string));\n\t\t\t} else {\n\t\t\t\t/* set wanted id */\n\t\t\t\tnetwork_client_set_next_id(fd, id);\n\t\t\t\tnetwork_client_set_msg_id(fd, msg_id);\n\t\t\t}\n\n\t\t\tp += strlen(network_line) + 1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\t\t} else if ( !strncmp(network_line, \"GET_ID\", strlen(\"GET_ID\")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: GET_ID\");\n\n\t\t\tmemset(string, 0, sizeof(string));\n\n\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\n%ld\\n\\n\",msg_id,notify_last_id.id);\n\n\t\t\twrite(fd, string, strlen(string));\n\n\t\t\tp+=strlen(network_line)+1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\n\t\t} else if ( !strncmp(network_line, \"GET_SCHEMA_ID\", strlen(\"GET_SCHEMA_ID\")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: GET_SCHEMA_ID\");\n\n\t\t\tmemset(string, 0, sizeof(string));\n\n\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\n%ld\\n\\n\",msg_id,SCHEMA_ID);\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"--> %d: [%s]\",fd, string);\n\n\t\t\twrite(fd, string, strlen(string));\n\n\t\t\tp+=strlen(network_line)+1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\n\t\t} else if ( !strncmp(network_line, \"ALIVE\", strlen(\"ALIVE\")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {\n\n\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"RECV: ALIVE\");\n\n\t\t\tsnprintf(string, sizeof(string), \"MSGID: %ld\\nOKAY\\n\\n\",msg_id);\n\n\t\t\twrite(fd, string, strlen(string));\n\n\t\t\tp+=strlen(network_line)+1;\n\t\t\tmsg_id = UINT32_MAX;\n\n\t\t} else {\n\n\t\t\tp+=strlen(network_line);\n\n\t\t\tif (strlen(network_line) == 0 ) {\n\t\t\t\tp+=1;\n \t\t\t} else {\n\t\t\t\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, \"Drop package [%s]\", network_line);\n\t\t\t}\n\n\t\t}\n\t}\n\tv_sem(sem_id);\n\n\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, \"END Package\");\n\t\n\n\tnetwork_client_dump ();\n\n\treturn 0;\n\nfailed:\n\tunivention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, \"Failed parsing [%s]\", p);\nclose:\n\tclose(fd);\n\tFD_CLR(fd, &readfds);\n\tremove(fd);\n\treturn 0;\n}", "idx": 519112, "cwe": "CWE-200", "hash": 191505813336538609500405503383750297649, "dataset": "other"}
  1099. {"project": "serenity", "commit_id": "48fbf6a88d4822a1e5470cf08f29464511bd72c1", "target": 1, "func": "static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, 256>& tests)\n{\n // Written using Wikipedia:\n // https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Miller%E2%80%93Rabin_test\n ASSERT(!(n < 4));\n auto predecessor = n.minus({ 1 });\n auto d = predecessor;\n size_t r = 0;\n\n {\n auto div_result = d.divided_by(2);\n while (div_result.remainder == 0) {\n d = div_result.quotient;\n div_result = d.divided_by(2);\n ++r;\n }\n }\n if (r == 0) {\n // n - 1 is odd, so n was even. But there is only one even prime:\n return n == 2;\n }\n\n for (auto a : tests) {\n // Technically: ASSERT(2 <= a && a <= n - 2)\n ASSERT(a < n);\n auto x = ModularPower(a, d, n);\n if (x == 1 || x == predecessor)\n continue;\n bool skip_this_witness = false;\n // r \u2212 1 iterations.\n for (size_t i = 0; i < r - 1; ++i) {\n x = ModularPower(x, 2, n);\n if (x == predecessor) {\n skip_this_witness = true;\n break;\n }\n }\n if (skip_this_witness)\n continue;\n return false; // \"composite\"\n }\n\n return true; // \"probably prime\"\n}", "idx": 217238, "cwe": "CWE-120", "hash": 179391134827512981723637669244439395484, "dataset": "other"}
  1100. {"project": "serenity", "commit_id": "48fbf6a88d4822a1e5470cf08f29464511bd72c1", "target": 0, "func": "static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, 256>& tests)\n{\n // Written using Wikipedia:\n // https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Miller%E2%80%93Rabin_test\n ASSERT(!(n < 4));\n auto predecessor = n.minus({ 1 });\n auto d = predecessor;\n size_t r = 0;\n\n {\n auto div_result = d.divided_by(2);\n while (div_result.remainder == 0) {\n d = div_result.quotient;\n div_result = d.divided_by(2);\n ++r;\n }\n }\n if (r == 0) {\n // n - 1 is odd, so n was even. But there is only one even prime:\n return n == 2;\n }\n\n for (auto& a : tests) {\n // Technically: ASSERT(2 <= a && a <= n - 2)\n ASSERT(a < n);\n auto x = ModularPower(a, d, n);\n if (x == 1 || x == predecessor)\n continue;\n bool skip_this_witness = false;\n // r \u2212 1 iterations.\n for (size_t i = 0; i < r - 1; ++i) {\n x = ModularPower(x, 2, n);\n if (x == predecessor) {\n skip_this_witness = true;\n break;\n }\n }\n if (skip_this_witness)\n continue;\n return false; // \"composite\"\n }\n\n return true; // \"probably prime\"\n}", "idx": 519155, "cwe": "CWE-120", "hash": 295059986924029830016313633716285228943, "dataset": "other"}
  1101. {"project": "serenity", "commit_id": "c9f25bca048443e317f1994ba9b106f2386688c3", "target": 1, "func": "String UTF16BEDecoder::to_utf8(const StringView& input)\n{\n StringBuilder builder(input.length() / 2);\n for (size_t i = 0; i < input.length(); i += 2) {\n u16 code_point = (input[i] << 8) | input[i + 1];\n builder.append_code_point(code_point);\n }\n return builder.to_string();\n}", "idx": 217239, "cwe": "CWE-120", "hash": 267515062059261157996667906553021221826, "dataset": "other"}
  1102. {"project": "serenity", "commit_id": "c9f25bca048443e317f1994ba9b106f2386688c3", "target": 0, "func": "String UTF16BEDecoder::to_utf8(const StringView& input)\n{\n StringBuilder builder(input.length() / 2);\n size_t utf16_length = input.length() - (input.length() % 2);\n for (size_t i = 0; i < utf16_length; i += 2) {\n u16 code_point = (input[i] << 8) | input[i + 1];\n builder.append_code_point(code_point);\n }\n return builder.to_string();\n}", "idx": 519174, "cwe": "CWE-120", "hash": 241191260041407383507436626312122244727, "dataset": "other"}
  1103. {"project": "serenity", "commit_id": "4317db7498eaa5a37068052bb0310fbc6a5f78e4", "target": 1, "func": " bool read(ReadonlyBytes buffer)\n {\n auto fields_size = sizeof(CentralDirectoryRecord) - (sizeof(u8*) * 3);\n if (buffer.size() < fields_size)\n return false;\n if (memcmp(buffer.data(), central_directory_record_signature, sizeof(central_directory_record_signature)) != 0)\n return false;\n memcpy(reinterpret_cast<void*>(&made_by_version), buffer.data() + sizeof(central_directory_record_signature), fields_size);\n name = buffer.data() + sizeof(central_directory_record_signature) + fields_size;\n extra_data = name + name_length;\n comment = extra_data + extra_data_length;\n return true;\n }", "idx": 217240, "cwe": "CWE-120", "hash": 69369911002037312040550057926154543506, "dataset": "other"}
  1104. {"project": "serenity", "commit_id": "4317db7498eaa5a37068052bb0310fbc6a5f78e4", "target": 0, "func": " bool read(ReadonlyBytes buffer)\n {\n auto fields_size = sizeof(CentralDirectoryRecord) - (sizeof(u8*) * 3);\n if (buffer.size() < sizeof(central_directory_record_signature) + fields_size)\n return false;\n if (memcmp(buffer.data(), central_directory_record_signature, sizeof(central_directory_record_signature)) != 0)\n return false;\n memcpy(reinterpret_cast<void*>(&made_by_version), buffer.data() + sizeof(central_directory_record_signature), fields_size);\n if (buffer.size() < sizeof(end_of_central_directory_signature) + fields_size + comment_length + name_length + extra_data_length)\n return false;\n name = buffer.data() + sizeof(central_directory_record_signature) + fields_size;\n extra_data = name + name_length;\n comment = extra_data + extra_data_length;\n return true;\n }", "idx": 519180, "cwe": "CWE-120", "hash": 215987508473597737335837343307564688788, "dataset": "other"}
  1105. {"project": "serenity", "commit_id": "4317db7498eaa5a37068052bb0310fbc6a5f78e4", "target": 1, "func": " bool read(ReadonlyBytes buffer)\n {\n auto fields_size = sizeof(LocalFileHeader) - (sizeof(u8*) * 3);\n if (buffer.size() < fields_size)\n return false;\n if (memcmp(buffer.data(), local_file_header_signature, sizeof(local_file_header_signature)) != 0)\n return false;\n memcpy(reinterpret_cast<void*>(&minimum_version), buffer.data() + sizeof(local_file_header_signature), fields_size);\n name = buffer.data() + sizeof(local_file_header_signature) + fields_size;\n extra_data = name + name_length;\n compressed_data = extra_data + extra_data_length;\n return true;\n }", "idx": 217241, "cwe": "CWE-120", "hash": 319771508886292667317399837063760564198, "dataset": "other"}
  1106. {"project": "serenity", "commit_id": "4317db7498eaa5a37068052bb0310fbc6a5f78e4", "target": 0, "func": " bool read(ReadonlyBytes buffer)\n {\n auto fields_size = sizeof(LocalFileHeader) - (sizeof(u8*) * 3);\n if (buffer.size() < sizeof(local_file_header_signature) + fields_size)\n return false;\n if (memcmp(buffer.data(), local_file_header_signature, sizeof(local_file_header_signature)) != 0)\n return false;\n memcpy(reinterpret_cast<void*>(&minimum_version), buffer.data() + sizeof(local_file_header_signature), fields_size);\n if (buffer.size() < sizeof(end_of_central_directory_signature) + fields_size + name_length + extra_data_length + compressed_size)\n return false;\n name = buffer.data() + sizeof(local_file_header_signature) + fields_size;\n extra_data = name + name_length;\n compressed_data = extra_data + extra_data_length;\n return true;\n }", "idx": 519176, "cwe": "CWE-120", "hash": 170061068009080567685608343570245159652, "dataset": "other"}
  1107. {"project": "serenity", "commit_id": "4317db7498eaa5a37068052bb0310fbc6a5f78e4", "target": 1, "func": " bool read(ReadonlyBytes buffer)\n {\n auto fields_size = sizeof(EndOfCentralDirectory) - sizeof(u8*);\n if (buffer.size() < fields_size)\n return false;\n if (memcmp(buffer.data(), end_of_central_directory_signature, sizeof(end_of_central_directory_signature)) != 0)\n return false;\n memcpy(reinterpret_cast<void*>(&disk_number), buffer.data() + sizeof(end_of_central_directory_signature), fields_size);\n comment = buffer.data() + sizeof(end_of_central_directory_signature) + fields_size;\n return true;\n }", "idx": 217242, "cwe": "CWE-120", "hash": 192941992425069693221994624340355163369, "dataset": "other"}
  1108. {"project": "serenity", "commit_id": "4317db7498eaa5a37068052bb0310fbc6a5f78e4", "target": 0, "func": " bool read(ReadonlyBytes buffer)\n {\n auto fields_size = sizeof(EndOfCentralDirectory) - sizeof(u8*);\n if (buffer.size() < sizeof(end_of_central_directory_signature) + fields_size)\n return false;\n if (memcmp(buffer.data(), end_of_central_directory_signature, sizeof(end_of_central_directory_signature)) != 0)\n return false;\n memcpy(reinterpret_cast<void*>(&disk_number), buffer.data() + sizeof(end_of_central_directory_signature), fields_size);\n if (buffer.size() < sizeof(end_of_central_directory_signature) + fields_size + comment_length)\n return false;\n comment = buffer.data() + sizeof(end_of_central_directory_signature) + fields_size;\n return true;\n }", "idx": 519179, "cwe": "CWE-120", "hash": 113107175078160338642110725818946808617, "dataset": "other"}
  1109. {"project": "mbed-coap", "commit_id": "4647a68e364401e81dbd370728127d844f221d93", "target": 1, "func": "static int8_t sn_coap_parser_options_parse(struct coap_s *handle, uint8_t **packet_data_pptr, sn_coap_hdr_s *dst_coap_msg_ptr, uint8_t *packet_data_start_ptr, uint16_t packet_len)\n{\n uint8_t previous_option_number = 0;\n int8_t ret_status = 0;\n uint16_t message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n 0);\n\n /* Parse token, if exists */\n dst_coap_msg_ptr->token_len = *packet_data_start_ptr & COAP_HEADER_TOKEN_LENGTH_MASK;\n\n if (dst_coap_msg_ptr->token_len) {\n int8_t ptr_check_result;\n if ((dst_coap_msg_ptr->token_len > 8) || dst_coap_msg_ptr->token_ptr) {\n tr_error(\"sn_coap_parser_options_parse - token not valid!\");\n return -1;\n }\n\n ptr_check_result = sn_coap_parser_check_packet_ptr(*packet_data_pptr, packet_data_start_ptr, packet_len, dst_coap_msg_ptr->token_len);\n if (0 != ptr_check_result) {\n tr_error(\"sn_coap_parser_options_parse - **packet_data_pptr overflow !\");\n return -1;\n }\n\n dst_coap_msg_ptr->token_ptr = sn_coap_protocol_malloc_copy(handle, *packet_data_pptr, dst_coap_msg_ptr->token_len);\n\n if (dst_coap_msg_ptr->token_ptr == NULL) {\n tr_error(\"sn_coap_parser_options_parse - failed to allocate token!\");\n return -1;\n }\n\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n dst_coap_msg_ptr->token_len);\n }\n\n /* Loop all Options */\n while (message_left && (**packet_data_pptr != 0xff)) {\n /* Get option length WITHOUT extensions */\n uint16_t option_len = (**packet_data_pptr & 0x0F);\n /* Get option number WITHOUT extensions */\n uint16_t option_number = (**packet_data_pptr >> COAP_OPTIONS_OPTION_NUMBER_SHIFT);\n\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr, packet_data_start_ptr, packet_len, 1);\n\n int8_t option_parse_result;\n /* Add possible option delta extension */\n option_parse_result = parse_ext_option(&option_number,\n packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n &message_left);\n if (option_parse_result != 0) {\n return -1;\n }\n /* Add previous option to option delta and get option number */\n option_number += previous_option_number;\n\n /* Add possible option length extension to resolve full length of the option */\n option_parse_result = parse_ext_option(&option_len,\n packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n &message_left);\n if (option_parse_result != 0) {\n return -1;\n }\n\n /* * * Parse option itself * * */\n /* Some options are handled independently in own functions */\n previous_option_number = option_number;\n /* Allocate options_list_ptr if needed */\n switch (option_number) {\n case COAP_OPTION_MAX_AGE:\n case COAP_OPTION_PROXY_URI:\n case COAP_OPTION_ETAG:\n case COAP_OPTION_URI_HOST:\n case COAP_OPTION_LOCATION_PATH:\n case COAP_OPTION_URI_PORT:\n case COAP_OPTION_LOCATION_QUERY:\n case COAP_OPTION_OBSERVE:\n case COAP_OPTION_URI_QUERY:\n case COAP_OPTION_BLOCK2:\n case COAP_OPTION_BLOCK1:\n case COAP_OPTION_ACCEPT:\n case COAP_OPTION_SIZE1:\n case COAP_OPTION_SIZE2:\n if (sn_coap_parser_alloc_options(handle, dst_coap_msg_ptr) == NULL) {\n tr_error(\"sn_coap_parser_options_parse - failed to allocate options!\");\n return -1;\n }\n break;\n }\n\n if (message_left < option_len){\n /* packet_data_pptr would overflow! */\n tr_error(\"sn_coap_parser_options_parse - **packet_data_pptr would overflow when parsing options!\");\n return -1;\n }\n\n /* Parse option */\n switch (option_number) {\n case COAP_OPTION_CONTENT_FORMAT:\n if ((option_len > 2) || (dst_coap_msg_ptr->content_format != COAP_CT_NONE)) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_CONTENT_FORMAT not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->content_format = (sn_coap_content_format_e) sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_MAX_AGE:\n if (option_len > 4) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_MAX_AGE not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->max_age = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_PROXY_URI:\n if ((option_len > 1034) || (option_len < 1) || dst_coap_msg_ptr->options_list_ptr->proxy_uri_ptr) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_PROXY_URI not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->proxy_uri_len = option_len;\n dst_coap_msg_ptr->options_list_ptr->proxy_uri_ptr = sn_coap_protocol_malloc_copy(handle, *packet_data_pptr, option_len);\n\n if (dst_coap_msg_ptr->options_list_ptr->proxy_uri_ptr == NULL) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_PROXY_URI allocation failed!\");\n return -1;\n }\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr, packet_data_start_ptr, packet_len, option_len);\n break;\n\n case COAP_OPTION_ETAG:\n /* This is managed independently because User gives this option in one character table */\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr,\n message_left,\n &dst_coap_msg_ptr->options_list_ptr->etag_ptr,\n (uint16_t *)&dst_coap_msg_ptr->options_list_ptr->etag_len,\n COAP_OPTION_ETAG, option_len);\n if (ret_status < 0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_ETAG not valid!\");\n return -1;\n }\n break;\n\n case COAP_OPTION_URI_HOST:\n if ((option_len > 255) || (option_len < 1) || dst_coap_msg_ptr->options_list_ptr->uri_host_ptr) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_HOST not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->uri_host_len = option_len;\n dst_coap_msg_ptr->options_list_ptr->uri_host_ptr = sn_coap_protocol_malloc_copy(handle, *packet_data_pptr, option_len);\n\n if (dst_coap_msg_ptr->options_list_ptr->uri_host_ptr == NULL) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_HOST allocation failed!\");\n return -1;\n }\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr, packet_data_start_ptr, packet_len, option_len);\n break;\n\n case COAP_OPTION_LOCATION_PATH:\n if (dst_coap_msg_ptr->options_list_ptr->location_path_ptr) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_LOCATION_PATH exists!\");\n return -1;\n }\n /* This is managed independently because User gives this option in one character table */\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr, message_left,\n &dst_coap_msg_ptr->options_list_ptr->location_path_ptr, &dst_coap_msg_ptr->options_list_ptr->location_path_len,\n COAP_OPTION_LOCATION_PATH, option_len);\n if (ret_status <0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_LOCATION_PATH not valid!\");\n return -1;\n }\n break;\n\n case COAP_OPTION_URI_PORT:\n if ((option_len > 2) || dst_coap_msg_ptr->options_list_ptr->uri_port != COAP_OPTION_URI_PORT_NONE) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_PORT not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->uri_port = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_LOCATION_QUERY:\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr, message_left,\n &dst_coap_msg_ptr->options_list_ptr->location_query_ptr, &dst_coap_msg_ptr->options_list_ptr->location_query_len,\n COAP_OPTION_LOCATION_QUERY, option_len);\n if (ret_status < 0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_LOCATION_QUERY not valid!\");\n return -1;\n }\n\n break;\n\n case COAP_OPTION_URI_PATH:\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr, message_left,\n &dst_coap_msg_ptr->uri_path_ptr, &dst_coap_msg_ptr->uri_path_len,\n COAP_OPTION_URI_PATH, option_len);\n if (ret_status < 0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_PATH not valid!\");\n return -1;\n }\n break;\n\n case COAP_OPTION_OBSERVE:\n if ((option_len > 2) || dst_coap_msg_ptr->options_list_ptr->observe != COAP_OBSERVE_NONE) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_OBSERVE not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->observe = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_URI_QUERY:\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr, message_left,\n &dst_coap_msg_ptr->options_list_ptr->uri_query_ptr, &dst_coap_msg_ptr->options_list_ptr->uri_query_len,\n COAP_OPTION_URI_QUERY, option_len);\n if (ret_status < 0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_QUERY not valid!\");\n return -1;\n }\n break;\n\n case COAP_OPTION_BLOCK2:\n if ((option_len > 3) || dst_coap_msg_ptr->options_list_ptr->block2 != COAP_OPTION_BLOCK_NONE) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_BLOCK2 not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->block2 = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_BLOCK1:\n if ((option_len > 3) || dst_coap_msg_ptr->options_list_ptr->block1 != COAP_OPTION_BLOCK_NONE) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_BLOCK1 not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->block1 = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_ACCEPT:\n if ((option_len > 2) || (dst_coap_msg_ptr->options_list_ptr->accept != COAP_CT_NONE)) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_ACCEPT not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->accept = (sn_coap_content_format_e) sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_SIZE1:\n if ((option_len > 4) || dst_coap_msg_ptr->options_list_ptr->use_size1) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_SIZE1 not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->use_size1 = true;\n dst_coap_msg_ptr->options_list_ptr->size1 = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_SIZE2:\n if ((option_len > 4) || dst_coap_msg_ptr->options_list_ptr->use_size2) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_SIZE2 not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->use_size2 = true;\n dst_coap_msg_ptr->options_list_ptr->size2 = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n default:\n tr_error(\"sn_coap_parser_options_parse - unknown option!\");\n return -1;\n }\n\n /* Check for overflow */\n if ((*packet_data_pptr - packet_data_start_ptr) > packet_len) {\n return -1;\n }\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n 0);\n }\n return 0;\n}", "idx": 217244, "cwe": "CWE-401", "hash": 214117041663586615268817958198922051959, "dataset": "other"}
  1110. {"project": "mbed-coap", "commit_id": "4647a68e364401e81dbd370728127d844f221d93", "target": 0, "func": "static int8_t sn_coap_parser_options_parse(struct coap_s *handle, uint8_t **packet_data_pptr, sn_coap_hdr_s *dst_coap_msg_ptr, uint8_t *packet_data_start_ptr, uint16_t packet_len)\n{\n uint8_t previous_option_number = 0;\n int8_t ret_status = 0;\n uint16_t message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n 0);\n\n /* Parse token, if exists */\n dst_coap_msg_ptr->token_len = *packet_data_start_ptr & COAP_HEADER_TOKEN_LENGTH_MASK;\n\n if (dst_coap_msg_ptr->token_len) {\n int8_t ptr_check_result;\n if ((dst_coap_msg_ptr->token_len > 8) || dst_coap_msg_ptr->token_ptr) {\n tr_error(\"sn_coap_parser_options_parse - token not valid!\");\n return -1;\n }\n\n ptr_check_result = sn_coap_parser_check_packet_ptr(*packet_data_pptr, packet_data_start_ptr, packet_len, dst_coap_msg_ptr->token_len);\n if (0 != ptr_check_result) {\n tr_error(\"sn_coap_parser_options_parse - **packet_data_pptr overflow !\");\n return -1;\n }\n\n dst_coap_msg_ptr->token_ptr = sn_coap_protocol_malloc_copy(handle, *packet_data_pptr, dst_coap_msg_ptr->token_len);\n\n if (dst_coap_msg_ptr->token_ptr == NULL) {\n tr_error(\"sn_coap_parser_options_parse - failed to allocate token!\");\n return -1;\n }\n\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n dst_coap_msg_ptr->token_len);\n }\n\n /* Loop all Options */\n while (message_left && (**packet_data_pptr != 0xff)) {\n /* Get option length WITHOUT extensions */\n uint16_t option_len = (**packet_data_pptr & 0x0F);\n /* Get option number WITHOUT extensions */\n uint16_t option_number = (**packet_data_pptr >> COAP_OPTIONS_OPTION_NUMBER_SHIFT);\n\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr, packet_data_start_ptr, packet_len, 1);\n\n int8_t option_parse_result;\n /* Add possible option delta extension */\n option_parse_result = parse_ext_option(&option_number,\n packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n &message_left);\n if (option_parse_result != 0) {\n return -1;\n }\n /* Add previous option to option delta and get option number */\n if(sn_coap_parser_add_u16_limit(option_number, previous_option_number, &option_number) != 0)\n {\n return -1;\n }\n\n /* Add possible option length extension to resolve full length of the option */\n option_parse_result = parse_ext_option(&option_len,\n packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n &message_left);\n if (option_parse_result != 0) {\n return -1;\n }\n\n /* * * Parse option itself * * */\n /* Some options are handled independently in own functions */\n previous_option_number = option_number;\n /* Allocate options_list_ptr if needed */\n switch (option_number) {\n case COAP_OPTION_MAX_AGE:\n case COAP_OPTION_PROXY_URI:\n case COAP_OPTION_ETAG:\n case COAP_OPTION_URI_HOST:\n case COAP_OPTION_LOCATION_PATH:\n case COAP_OPTION_URI_PORT:\n case COAP_OPTION_LOCATION_QUERY:\n case COAP_OPTION_OBSERVE:\n case COAP_OPTION_URI_QUERY:\n case COAP_OPTION_BLOCK2:\n case COAP_OPTION_BLOCK1:\n case COAP_OPTION_ACCEPT:\n case COAP_OPTION_SIZE1:\n case COAP_OPTION_SIZE2:\n if (sn_coap_parser_alloc_options(handle, dst_coap_msg_ptr) == NULL) {\n tr_error(\"sn_coap_parser_options_parse - failed to allocate options!\");\n return -1;\n }\n break;\n }\n\n if (message_left < option_len){\n /* packet_data_pptr would overflow! */\n tr_error(\"sn_coap_parser_options_parse - **packet_data_pptr would overflow when parsing options!\");\n return -1;\n }\n\n /* Parse option */\n switch (option_number) {\n case COAP_OPTION_CONTENT_FORMAT:\n if ((option_len > 2) || (dst_coap_msg_ptr->content_format != COAP_CT_NONE)) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_CONTENT_FORMAT not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->content_format = (sn_coap_content_format_e) sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_MAX_AGE:\n if (option_len > 4) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_MAX_AGE not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->max_age = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_PROXY_URI:\n if ((option_len > 1034) || (option_len < 1) || dst_coap_msg_ptr->options_list_ptr->proxy_uri_ptr) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_PROXY_URI not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->proxy_uri_len = option_len;\n dst_coap_msg_ptr->options_list_ptr->proxy_uri_ptr = sn_coap_protocol_malloc_copy(handle, *packet_data_pptr, option_len);\n\n if (dst_coap_msg_ptr->options_list_ptr->proxy_uri_ptr == NULL) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_PROXY_URI allocation failed!\");\n return -1;\n }\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr, packet_data_start_ptr, packet_len, option_len);\n break;\n\n case COAP_OPTION_ETAG:\n if (dst_coap_msg_ptr->options_list_ptr->etag_ptr)\n {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_ETAG exists!\");\n return -1;\n }\n /* This is managed independently because User gives this option in one character table */\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr,\n message_left,\n &dst_coap_msg_ptr->options_list_ptr->etag_ptr,\n (uint16_t *)&dst_coap_msg_ptr->options_list_ptr->etag_len,\n COAP_OPTION_ETAG, option_len);\n if (ret_status < 0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_ETAG not valid!\");\n return -1;\n }\n break;\n\n case COAP_OPTION_URI_HOST:\n if ((option_len > 255) || (option_len < 1) || dst_coap_msg_ptr->options_list_ptr->uri_host_ptr) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_HOST not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->uri_host_len = option_len;\n dst_coap_msg_ptr->options_list_ptr->uri_host_ptr = sn_coap_protocol_malloc_copy(handle, *packet_data_pptr, option_len);\n\n if (dst_coap_msg_ptr->options_list_ptr->uri_host_ptr == NULL) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_HOST allocation failed!\");\n return -1;\n }\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr, packet_data_start_ptr, packet_len, option_len);\n break;\n\n case COAP_OPTION_LOCATION_PATH:\n if (dst_coap_msg_ptr->options_list_ptr->location_path_ptr) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_LOCATION_PATH exists!\");\n return -1;\n }\n /* This is managed independently because User gives this option in one character table */\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr, message_left,\n &dst_coap_msg_ptr->options_list_ptr->location_path_ptr, &dst_coap_msg_ptr->options_list_ptr->location_path_len,\n COAP_OPTION_LOCATION_PATH, option_len);\n if (ret_status <0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_LOCATION_PATH not valid!\");\n return -1;\n }\n break;\n\n case COAP_OPTION_URI_PORT:\n if ((option_len > 2) || dst_coap_msg_ptr->options_list_ptr->uri_port != COAP_OPTION_URI_PORT_NONE) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_PORT not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->uri_port = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_LOCATION_QUERY:\n if (dst_coap_msg_ptr->options_list_ptr->location_query_ptr)\n {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_LOCATION_QUERY exists!\");\n return -1;\n }\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr, message_left,\n &dst_coap_msg_ptr->options_list_ptr->location_query_ptr, &dst_coap_msg_ptr->options_list_ptr->location_query_len,\n COAP_OPTION_LOCATION_QUERY, option_len);\n if (ret_status < 0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_LOCATION_QUERY not valid!\");\n return -1;\n }\n\n break;\n\n case COAP_OPTION_URI_PATH:\n if (dst_coap_msg_ptr->uri_path_ptr)\n {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_PATH exists!\");\n return -1;\n }\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr, message_left,\n &dst_coap_msg_ptr->uri_path_ptr, &dst_coap_msg_ptr->uri_path_len,\n COAP_OPTION_URI_PATH, option_len);\n if (ret_status < 0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_PATH not valid!\");\n return -1;\n }\n break;\n\n case COAP_OPTION_OBSERVE:\n if ((option_len > 2) || dst_coap_msg_ptr->options_list_ptr->observe != COAP_OBSERVE_NONE) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_OBSERVE not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->observe = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_URI_QUERY:\n ret_status = sn_coap_parser_options_parse_multiple_options(handle, packet_data_pptr, message_left,\n &dst_coap_msg_ptr->options_list_ptr->uri_query_ptr, &dst_coap_msg_ptr->options_list_ptr->uri_query_len,\n COAP_OPTION_URI_QUERY, option_len);\n if (ret_status < 0) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_URI_QUERY not valid!\");\n return -1;\n }\n break;\n\n case COAP_OPTION_BLOCK2:\n if ((option_len > 3) || dst_coap_msg_ptr->options_list_ptr->block2 != COAP_OPTION_BLOCK_NONE) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_BLOCK2 not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->block2 = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_BLOCK1:\n if ((option_len > 3) || dst_coap_msg_ptr->options_list_ptr->block1 != COAP_OPTION_BLOCK_NONE) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_BLOCK1 not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->block1 = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_ACCEPT:\n if ((option_len > 2) || (dst_coap_msg_ptr->options_list_ptr->accept != COAP_CT_NONE)) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_ACCEPT not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->accept = (sn_coap_content_format_e) sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_SIZE1:\n if ((option_len > 4) || dst_coap_msg_ptr->options_list_ptr->use_size1) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_SIZE1 not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->use_size1 = true;\n dst_coap_msg_ptr->options_list_ptr->size1 = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n case COAP_OPTION_SIZE2:\n if ((option_len > 4) || dst_coap_msg_ptr->options_list_ptr->use_size2) {\n tr_error(\"sn_coap_parser_options_parse - COAP_OPTION_SIZE2 not valid!\");\n return -1;\n }\n dst_coap_msg_ptr->options_list_ptr->use_size2 = true;\n dst_coap_msg_ptr->options_list_ptr->size2 = sn_coap_parser_options_parse_uint(packet_data_pptr, option_len);\n break;\n\n default:\n tr_error(\"sn_coap_parser_options_parse - unknown option!\");\n return -1;\n }\n\n /* Check for overflow */\n if ((*packet_data_pptr - packet_data_start_ptr) > packet_len) {\n return -1;\n }\n message_left = sn_coap_parser_move_packet_ptr(packet_data_pptr,\n packet_data_start_ptr,\n packet_len,\n 0);\n }\n return 0;\n}", "idx": 519481, "cwe": "CWE-401", "hash": 204700212510397032757265218058647314504, "dataset": "other"}
  1111. {"project": "phosphor-host-ipmid", "commit_id": "b265455a2518ece7c004b43c144199ec980fc620", "target": 1, "func": "int PasswdMgr::updatePasswdSpecialFile(const std::string& userName,\n const std::string& newUserName)\n{\n phosphor::user::shadow::Lock lock();\n\n size_t bytesWritten = 0;\n size_t inBytesLen = 0;\n size_t isUsrFound = false;\n const EVP_CIPHER* cipher = EVP_aes_128_cbc();\n std::vector<uint8_t> dataBuf;\n\n // Read the encrypted file and get the file data\n // Check user existance and return if not exist.\n if (readPasswdFileData(dataBuf) != 0)\n {\n log<level::DEBUG>(\"Error in reading the encrypted pass file\");\n return -EIO;\n }\n\n if (dataBuf.size() != 0)\n {\n inBytesLen =\n dataBuf.size() + newUserName.size() + EVP_CIPHER_block_size(cipher);\n }\n\n std::vector<uint8_t> inBytes(inBytesLen);\n if (inBytesLen != 0)\n {\n char* outPtr = reinterpret_cast<char*>(dataBuf.data());\n char* nToken = NULL;\n char* linePtr = strtok_r(outPtr, \"\\n\", &nToken);\n while (linePtr != NULL)\n {\n size_t userEPos = 0;\n\n std::string lineStr(linePtr);\n if ((userEPos = lineStr.find(\":\")) != std::string::npos)\n {\n if (userName.compare(lineStr.substr(0, userEPos)) == 0)\n {\n isUsrFound = true;\n if (!newUserName.empty())\n {\n bytesWritten += std::snprintf(\n reinterpret_cast<char*>(&inBytes[0]) + bytesWritten,\n (inBytesLen - bytesWritten), \"%s%s\\n\",\n newUserName.c_str(),\n lineStr.substr(userEPos, lineStr.size()).data());\n }\n }\n else\n {\n bytesWritten += std::snprintf(\n reinterpret_cast<char*>(&inBytes[0]) + bytesWritten,\n (inBytesLen - bytesWritten), \"%s\\n\", lineStr.data());\n }\n }\n linePtr = strtok_r(NULL, \"\\n\", &nToken);\n }\n inBytesLen = bytesWritten;\n }\n if (!isUsrFound)\n {\n log<level::DEBUG>(\"User doesn't exist\");\n return 0;\n }\n\n // Read the key buff from key file\n std::array<uint8_t, maxKeySize> keyBuff;\n std::ifstream keyFile(encryptKeyFileName, std::ios::in | std::ios::binary);\n if (!keyFile.good())\n {\n log<level::DEBUG>(\"Error in opening encryption key file\");\n return -EIO;\n }\n keyFile.read(reinterpret_cast<char*>(keyBuff.data()), keyBuff.size());\n if (keyFile.fail())\n {\n log<level::DEBUG>(\"Error in reading encryption key file\");\n return -EIO;\n }\n keyFile.close();\n\n // Read the original passwd file mode\n struct stat st = {};\n if (stat(passwdFileName, &st) != 0)\n {\n log<level::DEBUG>(\"Error in getting password file fstat()\");\n return -EIO;\n }\n\n // Create temporary file for write\n std::string pwdFile(passwdFileName);\n std::vector<char> tempFileName(pwdFile.begin(), pwdFile.end());\n std::vector<char> fileTemplate = {'_', '_', 'X', 'X', 'X',\n 'X', 'X', 'X', '\\0'};\n tempFileName.insert(tempFileName.end(), fileTemplate.begin(),\n fileTemplate.end());\n int fd = mkstemp((char*)tempFileName.data());\n if (fd == -1)\n {\n log<level::DEBUG>(\"Error creating temp file\");\n return -EIO;\n }\n\n std::string strTempFileName(tempFileName.data());\n // Open the temp file for writing from provided fd\n // By \"true\", remove it at exit if still there.\n // This is needed to cleanup the temp file at exception\n phosphor::user::File temp(fd, strTempFileName, \"w\", true);\n if ((temp)() == NULL)\n {\n close(fd);\n log<level::DEBUG>(\"Error creating temp file\");\n return -EIO;\n }\n\n // Set the file mode as of actual ipmi-pass file.\n if (fchmod(fileno((temp)()), st.st_mode) < 0)\n {\n log<level::DEBUG>(\"Error setting fchmod for temp file\");\n return -EIO;\n }\n\n const EVP_MD* digest = EVP_sha256();\n size_t hashLen = EVP_MD_block_size(digest);\n std::vector<uint8_t> hash(hashLen);\n size_t ivLen = EVP_CIPHER_iv_length(cipher);\n std::vector<uint8_t> iv(ivLen);\n std::array<uint8_t, EVP_MAX_KEY_LENGTH> key;\n size_t keyLen = key.size();\n std::array<uint8_t, EVP_MAX_MD_SIZE> mac;\n size_t macLen = mac.size();\n\n // Create random hash and generate hash key which will be used for\n // encryption.\n if (RAND_bytes(hash.data(), hashLen) != 1)\n {\n log<level::DEBUG>(\"Hash genertion failed, bailing out\");\n return -EIO;\n }\n if (NULL == HMAC(digest, keyBuff.data(), keyBuff.size(), hash.data(),\n hashLen, key.data(),\n reinterpret_cast<unsigned int*>(&keyLen)))\n {\n log<level::DEBUG>(\"Failed to create MAC for authentication\");\n return -EIO;\n }\n\n // Generate IV values\n if (RAND_bytes(iv.data(), ivLen) != 1)\n {\n log<level::DEBUG>(\"UV genertion failed, bailing out\");\n return -EIO;\n }\n\n // Encrypt the input data\n std::vector<uint8_t> outBytes(inBytesLen + EVP_MAX_BLOCK_LENGTH);\n size_t outBytesLen = 0;\n if (inBytesLen != 0)\n {\n if (encryptDecryptData(true, EVP_aes_128_cbc(), key.data(), keyLen,\n iv.data(), ivLen, inBytes.data(), inBytesLen,\n mac.data(), &macLen, outBytes.data(),\n &outBytesLen) != 0)\n {\n log<level::DEBUG>(\"Error while encrypting the data\");\n return -EIO;\n }\n outBytes[outBytesLen] = 0;\n }\n OPENSSL_cleanse(key.data(), keyLen);\n\n // Update the meta password structure.\n MetaPassStruct metaData = {META_PASSWD_SIG, {0, 0}, 0, 0, 0, 0, 0};\n metaData.hashSize = hashLen;\n metaData.ivSize = ivLen;\n metaData.dataSize = bytesWritten;\n metaData.padSize = outBytesLen - bytesWritten;\n metaData.macSize = macLen;\n\n if (fwrite(&metaData, 1, sizeof(metaData), (temp)()) != sizeof(metaData))\n {\n log<level::DEBUG>(\"Error in writing meta data\");\n return -EIO;\n }\n\n if (fwrite(&hash[0], 1, hashLen, (temp)()) != hashLen)\n {\n log<level::DEBUG>(\"Error in writing hash data\");\n return -EIO;\n }\n\n if (fwrite(&iv[0], 1, ivLen, (temp)()) != ivLen)\n {\n log<level::DEBUG>(\"Error in writing IV data\");\n return -EIO;\n }\n\n if (fwrite(&outBytes[0], 1, outBytesLen, (temp)()) != outBytesLen)\n {\n log<level::DEBUG>(\"Error in writing encrypted data\");\n return -EIO;\n }\n\n if (fwrite(&mac[0], 1, macLen, (temp)()) != macLen)\n {\n log<level::DEBUG>(\"Error in writing MAC data\");\n return -EIO;\n }\n\n if (fflush((temp)()))\n {\n log<level::DEBUG>(\n \"File fflush error while writing entries to special file\");\n return -EIO;\n }\n\n OPENSSL_cleanse(iv.data(), ivLen);\n\n // Rename the tmp file to actual file\n if (std::rename(strTempFileName.data(), passwdFileName) != 0)\n {\n log<level::DEBUG>(\"Failed to rename tmp file to ipmi-pass\");\n return -EIO;\n }\n\n return 0;\n}", "idx": 217248, "cwe": "CWE-276", "hash": 221959307217368580668393288338011666999, "dataset": "other"}
  1112. {"project": "phosphor-host-ipmid", "commit_id": "b265455a2518ece7c004b43c144199ec980fc620", "target": 0, "func": "int PasswdMgr::updatePasswdSpecialFile(const std::string& userName,\n const std::string& newUserName)\n{\n phosphor::user::shadow::Lock lock();\n\n size_t bytesWritten = 0;\n size_t inBytesLen = 0;\n size_t isUsrFound = false;\n const EVP_CIPHER* cipher = EVP_aes_128_cbc();\n std::vector<uint8_t> dataBuf;\n\n // Read the encrypted file and get the file data\n // Check user existance and return if not exist.\n if (readPasswdFileData(dataBuf) != 0)\n {\n log<level::DEBUG>(\"Error in reading the encrypted pass file\");\n return -EIO;\n }\n\n if (dataBuf.size() != 0)\n {\n inBytesLen =\n dataBuf.size() + newUserName.size() + EVP_CIPHER_block_size(cipher);\n }\n\n std::vector<uint8_t> inBytes(inBytesLen);\n if (inBytesLen != 0)\n {\n char* outPtr = reinterpret_cast<char*>(dataBuf.data());\n char* nToken = NULL;\n char* linePtr = strtok_r(outPtr, \"\\n\", &nToken);\n while (linePtr != NULL)\n {\n size_t userEPos = 0;\n\n std::string lineStr(linePtr);\n if ((userEPos = lineStr.find(\":\")) != std::string::npos)\n {\n if (userName.compare(lineStr.substr(0, userEPos)) == 0)\n {\n isUsrFound = true;\n if (!newUserName.empty())\n {\n bytesWritten += std::snprintf(\n reinterpret_cast<char*>(&inBytes[0]) + bytesWritten,\n (inBytesLen - bytesWritten), \"%s%s\\n\",\n newUserName.c_str(),\n lineStr.substr(userEPos, lineStr.size()).data());\n }\n }\n else\n {\n bytesWritten += std::snprintf(\n reinterpret_cast<char*>(&inBytes[0]) + bytesWritten,\n (inBytesLen - bytesWritten), \"%s\\n\", lineStr.data());\n }\n }\n linePtr = strtok_r(NULL, \"\\n\", &nToken);\n }\n inBytesLen = bytesWritten;\n }\n if (!isUsrFound)\n {\n log<level::DEBUG>(\"User doesn't exist\");\n return 0;\n }\n\n // Read the key buff from key file\n std::array<uint8_t, maxKeySize> keyBuff;\n std::ifstream keyFile(encryptKeyFileName, std::ios::in | std::ios::binary);\n if (!keyFile.good())\n {\n log<level::DEBUG>(\"Error in opening encryption key file\");\n return -EIO;\n }\n keyFile.read(reinterpret_cast<char*>(keyBuff.data()), keyBuff.size());\n if (keyFile.fail())\n {\n log<level::DEBUG>(\"Error in reading encryption key file\");\n return -EIO;\n }\n keyFile.close();\n\n // Read the original passwd file mode\n struct stat st = {};\n if (stat(passwdFileName, &st) != 0)\n {\n log<level::DEBUG>(\"Error in getting password file fstat()\");\n return -EIO;\n }\n\n // Create temporary file for write\n std::string pwdFile(passwdFileName);\n std::vector<char> tempFileName(pwdFile.begin(), pwdFile.end());\n std::vector<char> fileTemplate = {'_', '_', 'X', 'X', 'X',\n 'X', 'X', 'X', '\\0'};\n tempFileName.insert(tempFileName.end(), fileTemplate.begin(),\n fileTemplate.end());\n int fd = mkstemp((char*)tempFileName.data());\n if (fd == -1)\n {\n log<level::DEBUG>(\"Error creating temp file\");\n return -EIO;\n }\n\n std::string strTempFileName(tempFileName.data());\n // Open the temp file for writing from provided fd\n // By \"true\", remove it at exit if still there.\n // This is needed to cleanup the temp file at exception\n phosphor::user::File temp(fd, strTempFileName, \"w\", true);\n if ((temp)() == NULL)\n {\n close(fd);\n log<level::DEBUG>(\"Error creating temp file\");\n return -EIO;\n }\n\n // Set the file mode as read-write for owner only\n if (fchmod(fileno((temp)()), S_IRUSR | S_IWUSR) < 0)\n {\n log<level::DEBUG>(\"Error setting fchmod for temp file\");\n return -EIO;\n }\n\n const EVP_MD* digest = EVP_sha256();\n size_t hashLen = EVP_MD_block_size(digest);\n std::vector<uint8_t> hash(hashLen);\n size_t ivLen = EVP_CIPHER_iv_length(cipher);\n std::vector<uint8_t> iv(ivLen);\n std::array<uint8_t, EVP_MAX_KEY_LENGTH> key;\n size_t keyLen = key.size();\n std::array<uint8_t, EVP_MAX_MD_SIZE> mac;\n size_t macLen = mac.size();\n\n // Create random hash and generate hash key which will be used for\n // encryption.\n if (RAND_bytes(hash.data(), hashLen) != 1)\n {\n log<level::DEBUG>(\"Hash genertion failed, bailing out\");\n return -EIO;\n }\n if (NULL == HMAC(digest, keyBuff.data(), keyBuff.size(), hash.data(),\n hashLen, key.data(),\n reinterpret_cast<unsigned int*>(&keyLen)))\n {\n log<level::DEBUG>(\"Failed to create MAC for authentication\");\n return -EIO;\n }\n\n // Generate IV values\n if (RAND_bytes(iv.data(), ivLen) != 1)\n {\n log<level::DEBUG>(\"UV genertion failed, bailing out\");\n return -EIO;\n }\n\n // Encrypt the input data\n std::vector<uint8_t> outBytes(inBytesLen + EVP_MAX_BLOCK_LENGTH);\n size_t outBytesLen = 0;\n if (inBytesLen != 0)\n {\n if (encryptDecryptData(true, EVP_aes_128_cbc(), key.data(), keyLen,\n iv.data(), ivLen, inBytes.data(), inBytesLen,\n mac.data(), &macLen, outBytes.data(),\n &outBytesLen) != 0)\n {\n log<level::DEBUG>(\"Error while encrypting the data\");\n return -EIO;\n }\n outBytes[outBytesLen] = 0;\n }\n OPENSSL_cleanse(key.data(), keyLen);\n\n // Update the meta password structure.\n MetaPassStruct metaData = {META_PASSWD_SIG, {0, 0}, 0, 0, 0, 0, 0};\n metaData.hashSize = hashLen;\n metaData.ivSize = ivLen;\n metaData.dataSize = bytesWritten;\n metaData.padSize = outBytesLen - bytesWritten;\n metaData.macSize = macLen;\n\n if (fwrite(&metaData, 1, sizeof(metaData), (temp)()) != sizeof(metaData))\n {\n log<level::DEBUG>(\"Error in writing meta data\");\n return -EIO;\n }\n\n if (fwrite(&hash[0], 1, hashLen, (temp)()) != hashLen)\n {\n log<level::DEBUG>(\"Error in writing hash data\");\n return -EIO;\n }\n\n if (fwrite(&iv[0], 1, ivLen, (temp)()) != ivLen)\n {\n log<level::DEBUG>(\"Error in writing IV data\");\n return -EIO;\n }\n\n if (fwrite(&outBytes[0], 1, outBytesLen, (temp)()) != outBytesLen)\n {\n log<level::DEBUG>(\"Error in writing encrypted data\");\n return -EIO;\n }\n\n if (fwrite(&mac[0], 1, macLen, (temp)()) != macLen)\n {\n log<level::DEBUG>(\"Error in writing MAC data\");\n return -EIO;\n }\n\n if (fflush((temp)()))\n {\n log<level::DEBUG>(\n \"File fflush error while writing entries to special file\");\n return -EIO;\n }\n\n OPENSSL_cleanse(iv.data(), ivLen);\n\n // Rename the tmp file to actual file\n if (std::rename(strTempFileName.data(), passwdFileName) != 0)\n {\n log<level::DEBUG>(\"Failed to rename tmp file to ipmi-pass\");\n return -EIO;\n }\n\n return 0;\n}", "idx": 519579, "cwe": "CWE-276", "hash": 122115830430551595209272746493260850260, "dataset": "other"}
  1113. {"project": "bsdiff4", "commit_id": "49a4cee2feef7deaf9d89e5e793a8824930284d7", "target": 1, "func": "static PyObject* patch(PyObject* self, PyObject* args)\n{\n char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr;\n Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength;\n PyObject *controlTuples, *tuple, *results;\n off_t oldpos, newpos, x, y, z;\n int i, j, numTuples;\n\n if (!PyArg_ParseTuple(args, \"s#nO!s#s#\",\n &origData, &origDataLength, &newDataLength,\n &PyList_Type, &controlTuples,\n &diffBlock, &diffBlockLength,\n &extraBlock, &extraBlockLength))\n return NULL;\n\n /* allocate the memory for the new data */\n newData = PyMem_Malloc(newDataLength + 1);\n if (!newData)\n return PyErr_NoMemory();\n\n oldpos = 0;\n newpos = 0;\n diffPtr = diffBlock;\n extraPtr = extraBlock;\n numTuples = PyList_GET_SIZE(controlTuples);\n for (i = 0; i < numTuples; i++) {\n tuple = PyList_GET_ITEM(controlTuples, i);\n if (!PyTuple_Check(tuple)) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_TypeError, \"expecting tuple\");\n return NULL;\n }\n if (PyTuple_GET_SIZE(tuple) != 3) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_TypeError, \"expecting tuple of size 3\");\n return NULL;\n }\n x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));\n y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));\n z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2));\n if (newpos + x > newDataLength ||\n diffPtr + x > diffBlock + diffBlockLength ||\n extraPtr + y > extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (overflow)\");\n return NULL;\n }\n memcpy(newData + newpos, diffPtr, x);\n diffPtr += x;\n for (j = 0; j < x; j++)\n if ((oldpos + j >= 0) && (oldpos + j < origDataLength))\n newData[newpos + j] += origData[oldpos + j];\n newpos += x;\n oldpos += x;\n memcpy(newData + newpos, extraPtr, y);\n extraPtr += y;\n newpos += y;\n oldpos += z;\n }\n\n /* confirm that a valid patch was applied */\n if (newpos != newDataLength ||\n diffPtr != diffBlock + diffBlockLength ||\n extraPtr != extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (underflow)\");\n return NULL;\n }\n\n results = PyBytes_FromStringAndSize(newData, newDataLength);\n PyMem_Free(newData);\n return results;\n}", "idx": 217249, "cwe": "CWE-787", "hash": 263309723372044428910155475489612911037, "dataset": "other"}
  1114. {"project": "bsdiff4", "commit_id": "49a4cee2feef7deaf9d89e5e793a8824930284d7", "target": 0, "func": "static PyObject* patch(PyObject* self, PyObject* args)\n{\n char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr;\n Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength;\n PyObject *controlTuples, *tuple, *results;\n off_t oldpos, newpos, x, y, z;\n int i, j, numTuples;\n\n if (!PyArg_ParseTuple(args, \"s#nO!s#s#\",\n &origData, &origDataLength, &newDataLength,\n &PyList_Type, &controlTuples,\n &diffBlock, &diffBlockLength,\n &extraBlock, &extraBlockLength))\n return NULL;\n\n /* allocate the memory for the new data */\n newData = PyMem_Malloc(newDataLength + 1);\n if (!newData)\n return PyErr_NoMemory();\n\n oldpos = 0;\n newpos = 0;\n diffPtr = diffBlock;\n extraPtr = extraBlock;\n numTuples = PyList_GET_SIZE(controlTuples);\n for (i = 0; i < numTuples; i++) {\n tuple = PyList_GET_ITEM(controlTuples, i);\n if (!PyTuple_Check(tuple)) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_TypeError, \"expecting tuple\");\n return NULL;\n }\n if (PyTuple_GET_SIZE(tuple) != 3) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_TypeError, \"expecting tuple of size 3\");\n return NULL;\n }\n x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));\n y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));\n z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2));\n if (newpos + x > newDataLength ||\n diffPtr + x > diffBlock + diffBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (overflow)\");\n return NULL;\n }\n memcpy(newData + newpos, diffPtr, x);\n diffPtr += x;\n for (j = 0; j < x; j++)\n if ((oldpos + j >= 0) && (oldpos + j < origDataLength))\n newData[newpos + j] += origData[oldpos + j];\n newpos += x;\n oldpos += x;\n if (newpos + y > newDataLength ||\n extraPtr + y > extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (overflow)\");\n return NULL;\n }\n memcpy(newData + newpos, extraPtr, y);\n extraPtr += y;\n newpos += y;\n oldpos += z;\n }\n\n /* confirm that a valid patch was applied */\n if (newpos != newDataLength ||\n diffPtr != diffBlock + diffBlockLength ||\n extraPtr != extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (underflow)\");\n return NULL;\n }\n\n results = PyBytes_FromStringAndSize(newData, newDataLength);\n PyMem_Free(newData);\n return results;\n}", "idx": 519593, "cwe": "CWE-787", "hash": 28471137080724427079748331216528499874, "dataset": "other"}
  1115. {"project": "gilcc", "commit_id": "803969389ca9c06237075a7f8eeb1a19e6651759", "target": 1, "func": "static int src_parser_trans_stage_1_2_3(const int tmp_fd, const char *src, const struct trans_config cfg)\n{\n struct parser_buf pbuf = {\n .f_indx = 0,\n .tmp_indx = 0,\n .f_read_size = 0\n };\n\n int write_count = 0;\n int src_fd;\n int p_state = P_STATE_CODE;\n\n src_fd = open(src, O_RDONLY);\n if (src_fd == -1) {\n fprintf(stderr, \"**Error: Could not open source file: %s.\\n\", src);\n return -1;\n }\n\n while (p_buf_refill(&pbuf, src_fd) > 0) {\n\n while (PBUF_F_REMD(pbuf)) {\n\n switch (p_state) {\n case P_STATE_COMMENT_C:\n\n switch (PBUF_F_CHAR(pbuf)) {\n case '*':\n p_buf_push_tmp_char(&pbuf, '*');\n continue;\n\n case '/':\n if (pbuf.tmp_indx && (PBUF_TMP_PREV_CHAR(pbuf) == '*')) {\n pbuf.tmp_indx--;\n p_state = P_STATE_CODE;\n }\n break;\n\n default:\n if (pbuf.tmp_indx && (PBUF_TMP_PREV_CHAR(pbuf) == '*'))\n pbuf.tmp_indx--;\n break;\n }\n\n pbuf.f_indx++;\n\n case P_STATE_CODE:\n default:\n\n /* TODO: add trigraph support */\n\n switch (PBUF_F_CHAR(pbuf)) {\n case ' ':\n case '\\t':\n if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == ' ' || PBUF_TMP_PREV_CHAR(pbuf) == '\\t' ||\n PBUF_TMP_PREV_CHAR(pbuf) == '\\n'))\n pbuf.f_indx++;\n else\n p_buf_push_tmp_char(&pbuf, ' ');\n\n continue;\n\n case '\\r':\n case '\\n':\n if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == ' ' || PBUF_TMP_PREV_CHAR(pbuf) == '\\t' ||\n PBUF_TMP_PREV_CHAR(pbuf) == '\\n')) {\n pbuf.f_indx++;\n } else if (pbuf.tmp_indx && \n (PBUF_TMP_PREV_CHAR(pbuf) == '\\\\')) {\n pbuf.tmp_indx--;\n pbuf.f_indx++;\n } else {\n p_buf_push_tmp_char(&pbuf, '\\n');\n }\n\n continue;\n\n case '\\\\':\n p_buf_push_tmp_char(&pbuf, '\\\\');\n continue;\n\n case '/':\n p_buf_push_tmp_char(&pbuf, '/');\n continue;\n\n case '*':\n if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == '/')) {\n pbuf.tmp_indx--;\n pbuf.f_indx++;\n p_state = P_STATE_COMMENT_C;\n continue;\n }\n\n default:\n break;\n }\n\n /* TODO: check return values */\n p_buf_write_tmp(&pbuf, tmp_fd);\n p_buf_write_f_char(&pbuf, tmp_fd);\n }\n }\n }\n\n p_buf_write_tmp(&pbuf, tmp_fd);\n return 0;\n}", "idx": 217253, "cwe": "CWE-120", "hash": 156243165944298433475865161512344109547, "dataset": "other"}
  1116. {"project": "gilcc", "commit_id": "803969389ca9c06237075a7f8eeb1a19e6651759", "target": 0, "func": "static int src_parser_trans_stage_1_2_3(const int tmp_fd, const char *src, const struct trans_config cfg)\n{\n struct parser_buf pbuf = {\n .f_indx = 0,\n .tmp_indx = 0,\n .f_read_size = 0\n };\n\n int write_count = 0;\n int src_fd;\n int p_state = P_STATE_CODE;\n\n src_fd = open(src, O_RDONLY);\n if (src_fd == -1) {\n fprintf(stderr, \"**Error: Could not open source file: %s.\\n\", src);\n return -1;\n }\n\n while (p_buf_refill(&pbuf, src_fd) > 0) {\n\n while (PBUF_F_REMD(pbuf)) {\n\n switch (p_state) {\n case P_STATE_COMMENT_C:\n\n switch (PBUF_F_CHAR(pbuf)) {\n case '*':\n p_buf_push_tmp_char(&pbuf, '*');\n continue;\n\n case '/':\n if (pbuf.tmp_indx && (PBUF_TMP_PREV_CHAR(pbuf) == '*')) {\n pbuf.tmp_indx--;\n p_state = P_STATE_CODE;\n }\n break;\n\n default:\n if (pbuf.tmp_indx && (PBUF_TMP_PREV_CHAR(pbuf) == '*'))\n pbuf.tmp_indx--;\n break;\n }\n\n pbuf.f_indx++;\n\n case P_STATE_CODE:\n default:\n\n /* TODO: add trigraph support */\n\n switch (PBUF_F_CHAR(pbuf)) {\n case ' ':\n case '\\t':\n if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == ' ' || PBUF_TMP_PREV_CHAR(pbuf) == '\\t' ||\n PBUF_TMP_PREV_CHAR(pbuf) == '\\n'))\n pbuf.f_indx++;\n else\n p_buf_push_tmp_char(&pbuf, ' ');\n\n continue;\n\n case '\\r':\n case '\\n':\n if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == ' ' || PBUF_TMP_PREV_CHAR(pbuf) == '\\t' ||\n PBUF_TMP_PREV_CHAR(pbuf) == '\\n')) {\n pbuf.f_indx++;\n } else if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == '\\\\')) {\n pbuf.tmp_indx--;\n pbuf.f_indx++;\n } else {\n p_buf_push_tmp_char(&pbuf, '\\n');\n }\n\n continue;\n\n case '\\\\':\n p_buf_write_tmp(&pbuf, tmp_fd);\n p_buf_push_tmp_char(&pbuf, '\\\\');\n continue;\n\n case '/':\n p_buf_write_tmp(&pbuf, tmp_fd);\n p_buf_push_tmp_char(&pbuf, '/');\n continue;\n\n case '*':\n if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == '/')) {\n pbuf.tmp_indx--;\n pbuf.f_indx++;\n p_state = P_STATE_COMMENT_C;\n continue;\n }\n\n default:\n break;\n }\n\n /* TODO: check return values */\n p_buf_write_tmp(&pbuf, tmp_fd);\n p_buf_write_f_char(&pbuf, tmp_fd);\n }\n }\n }\n\n p_buf_write_tmp(&pbuf, tmp_fd);\n return 0;\n}", "idx": 519639, "cwe": "CWE-120", "hash": 243330918601381518712115173837645650891, "dataset": "other"}
  1117. {"project": "ardour", "commit_id": "96daa4036a425ff3f23a7dfcba57bfb0f942bec6", "target": 1, "func": "static XMLSharedNodeList* find_impl(xmlXPathContext* ctxt, const string& xpath)\n{\n\txmlXPathObject* result = xmlXPathEval((const xmlChar*)xpath.c_str(), ctxt);\n\n\tif (!result) {\n\t\txmlXPathFreeContext(ctxt);\n\t\txmlFreeDoc(ctxt->doc);\n\n\t\tthrow XMLException(\"Invalid XPath: \" + xpath);\n\t}\n\n\tif (result->type != XPATH_NODESET) {\n\t\txmlXPathFreeObject(result);\n\t\txmlXPathFreeContext(ctxt);\n\t\txmlFreeDoc(ctxt->doc);\n\n\t\tthrow XMLException(\"Only nodeset result types are supported.\");\n\t}\n\n\txmlNodeSet* nodeset = result->nodesetval;\n\tXMLSharedNodeList* nodes = new XMLSharedNodeList();\n\tif (nodeset) {\n\t\tfor (int i = 0; i < nodeset->nodeNr; ++i) {\n\t\t\tXMLNode* node = readnode(nodeset->nodeTab[i]);\n\t\t\tnodes->push_back(boost::shared_ptr<XMLNode>(node));\n\t\t}\n\t} else {\n\t\t// return empty set\n\t}\n\n\txmlXPathFreeObject(result);\n\n\treturn nodes;\n}", "idx": 217254, "cwe": "CWE-416", "hash": 54268186819182218721269174810414224706, "dataset": "other"}
  1118. {"project": "ardour", "commit_id": "96daa4036a425ff3f23a7dfcba57bfb0f942bec6", "target": 0, "func": "static XMLSharedNodeList* find_impl(xmlXPathContext* ctxt, const string& xpath)\n{\n\txmlXPathObject* result = xmlXPathEval((const xmlChar*)xpath.c_str(), ctxt);\n\n\tif (!result) {\n\t\txmlFreeDoc(ctxt->doc);\n\t\txmlXPathFreeContext(ctxt);\n\n\t\tthrow XMLException(\"Invalid XPath: \" + xpath);\n\t}\n\n\tif (result->type != XPATH_NODESET) {\n\t\txmlXPathFreeObject(result);\n\t\txmlFreeDoc(ctxt->doc);\n\t\txmlXPathFreeContext(ctxt);\n\n\t\tthrow XMLException(\"Only nodeset result types are supported.\");\n\t}\n\n\txmlNodeSet* nodeset = result->nodesetval;\n\tXMLSharedNodeList* nodes = new XMLSharedNodeList();\n\tif (nodeset) {\n\t\tfor (int i = 0; i < nodeset->nodeNr; ++i) {\n\t\t\tXMLNode* node = readnode(nodeset->nodeTab[i]);\n\t\t\tnodes->push_back(boost::shared_ptr<XMLNode>(node));\n\t\t}\n\t} else {\n\t\t// return empty set\n\t}\n\n\txmlXPathFreeObject(result);\n\n\treturn nodes;\n}", "idx": 519644, "cwe": "CWE-416", "hash": 16148318620035569612064845448555816656, "dataset": "other"}
  1119. {"project": "jsish", "commit_id": "858da537bde4de9d8c92466d5a866505310bc328", "target": 1, "func": "int Jsi_ObjArraySizer(Jsi_Interp *interp, Jsi_Obj *obj, uint len)\n{\n int nsiz = len + 1, mod = ALLOC_MOD_SIZE;\n assert(obj->isarrlist);\n if (mod>1)\n nsiz = nsiz + ((mod-1) - (nsiz + mod - 1)%mod);\n if (nsiz > MAX_ARRAY_LIST) {\n Jsi_LogError(\"array size too large\");\n return 0;\n }\n if (len >= obj->arrMaxSize) {\n int oldsz = (nsiz-obj->arrMaxSize);\n obj->arr = (Jsi_Value**)Jsi_Realloc(obj->arr, nsiz*sizeof(Jsi_Value*));\n memset(obj->arr+obj->arrMaxSize, 0, oldsz*sizeof(Jsi_Value*));\n obj->arrMaxSize = nsiz;\n }\n if (len>obj->arrCnt)\n obj->arrCnt = len;\n return nsiz;\n}", "idx": 217321, "cwe": "CWE-190", "hash": 172155516843930203788657327116633597249, "dataset": "other"}
  1120. {"project": "jsish", "commit_id": "858da537bde4de9d8c92466d5a866505310bc328", "target": 0, "func": "int Jsi_ObjArraySizer(Jsi_Interp *interp, Jsi_Obj *obj, uint len)\n{\n uint nsiz = len + 1, mod = ALLOC_MOD_SIZE;\n assert(obj->isarrlist);\n if (mod>1)\n nsiz = nsiz + ((mod-1) - (nsiz + mod - 1)%mod);\n if (len >= interp->maxArrayList || nsiz > interp->maxArrayList) {\n Jsi_LogError(\"array size too big: %u >= %u\", len, interp->maxArrayList);\n return 0;\n }\n if (len >= obj->arrMaxSize) {\n int oldsz = (nsiz-obj->arrMaxSize);\n obj->arr = (Jsi_Value**)Jsi_Realloc(obj->arr, nsiz*sizeof(Jsi_Value*));\n memset(obj->arr+obj->arrMaxSize, 0, oldsz*sizeof(Jsi_Value*));\n obj->arrMaxSize = nsiz;\n }\n if (len>obj->arrCnt)\n obj->arrCnt = len;\n return nsiz;\n}", "idx": 520950, "cwe": "CWE-190", "hash": 185362943759358555372661991746152891573, "dataset": "other"}
  1121. {"project": "spnego-http-auth-nginx-module", "commit_id": "a06f9efca373e25328b1c53639a48decd0854570", "target": 1, "func": "ngx_http_auth_spnego_handler(\n ngx_http_request_t * r)\n{\n ngx_int_t ret = NGX_DECLINED;\n ngx_http_auth_spnego_ctx_t *ctx;\n ngx_http_auth_spnego_loc_conf_t *alcf;\n\n alcf = ngx_http_get_module_loc_conf(r, ngx_http_auth_spnego_module);\n\n if (alcf->protect == 0) {\n return NGX_DECLINED;\n }\n\n ctx = ngx_http_get_module_ctx(r, ngx_http_auth_spnego_module);\n if (NULL == ctx) {\n ctx = ngx_palloc(r->pool, sizeof(ngx_http_auth_spnego_ctx_t));\n if (NULL == ctx) {\n return NGX_HTTP_INTERNAL_SERVER_ERROR;\n }\n ctx->token.len = 0;\n ctx->token.data = NULL;\n ctx->head = 0;\n ctx->ret = NGX_HTTP_UNAUTHORIZED;\n ngx_http_set_ctx(r, ctx, ngx_http_auth_spnego_module);\n }\n\n spnego_debug3(\"SSO auth handling IN: token.len=%d, head=%d, ret=%d\",\n ctx->token.len, ctx->head, ctx->ret);\n\n if (ctx->token.len && ctx->head) {\n spnego_debug1(\"Found token and head, returning %d\", ctx->ret);\n return ctx->ret;\n }\n\n if (NULL != r->headers_in.user.data) {\n spnego_debug0(\"User header set\");\n return NGX_OK;\n }\n\n spnego_debug0(\"Begin auth\");\n\n if (alcf->allow_basic) {\n spnego_debug0(\"Detect basic auth\");\n ret = ngx_http_auth_basic_user(r);\n if (NGX_OK == ret) {\n spnego_debug0(\"Basic auth credentials supplied by client\");\n /* If basic auth is enabled and basic creds are supplied\n * attempt basic auth. If we attempt basic auth, we do\n * not fall through to real SPNEGO */\n if (NGX_DECLINED == ngx_http_auth_spnego_basic(r, ctx, alcf)) {\n spnego_debug0(\"Basic auth failed\");\n if (NGX_ERROR == ngx_http_auth_spnego_headers_basic_only(r, ctx, alcf)) {\n spnego_debug0(\"Error setting headers\");\n return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR);\n }\n return (ctx->ret = NGX_HTTP_UNAUTHORIZED);\n }\n\n if (!ngx_spnego_authorized_principal(r, &r->headers_in.user, alcf)) {\n spnego_debug0(\"User not authorized\");\n return (ctx->ret = NGX_HTTP_FORBIDDEN);\n }\n\n spnego_debug0(\"Basic auth succeeded\");\n return (ctx->ret = NGX_OK);\n }\n }\n\n /* Basic auth either disabled or not supplied by client */\n spnego_debug0(\"Detect SPNEGO token\");\n ret = ngx_http_auth_spnego_token(r, ctx);\n if (NGX_OK == ret) {\n spnego_debug0(\"Client sent a reasonable Negotiate header\");\n ret = ngx_http_auth_spnego_auth_user_gss(r, ctx, alcf);\n if (NGX_ERROR == ret) {\n spnego_debug0(\"GSSAPI failed\");\n return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR);\n }\n /* There are chances that client knows about Negotiate\n * but doesn't support GSSAPI. We could attempt to fall\n * back to basic here... */\n if (NGX_DECLINED == ret) {\n spnego_debug0(\"GSSAPI failed\");\n if(!alcf->allow_basic) {\n return (ctx->ret = NGX_HTTP_FORBIDDEN);\n }\n if (NGX_ERROR == ngx_http_auth_spnego_headers_basic_only(r, ctx, alcf)) {\n spnego_debug0(\"Error setting headers\");\n return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR);\n }\n return (ctx->ret = NGX_HTTP_UNAUTHORIZED);\n }\n\n if (!ngx_spnego_authorized_principal(r, &r->headers_in.user, alcf)) {\n spnego_debug0(\"User not authorized\");\n return (ctx->ret = NGX_HTTP_FORBIDDEN);\n }\n\n spnego_debug0(\"GSSAPI auth succeeded\");\n }\n\n ngx_str_t *token_out_b64 = NULL;\n switch(ret) {\n case NGX_DECLINED: /* DECLINED, but not yet FORBIDDEN */\n ctx->ret = NGX_HTTP_UNAUTHORIZED;\n break;\n case NGX_OK:\n ctx->ret = NGX_OK;\n token_out_b64 = &ctx->token_out_b64;\n break;\n case NGX_ERROR:\n default:\n ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR;\n break;\n }\n\n if (NGX_ERROR == ngx_http_auth_spnego_headers(r, ctx, token_out_b64, alcf)) {\n spnego_debug0(\"Error setting headers\");\n ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR;\n }\n\n spnego_debug3(\"SSO auth handling OUT: token.len=%d, head=%d, ret=%d\",\n ctx->token.len, ctx->head, ctx->ret);\n return ctx->ret;\n}", "idx": 217457, "cwe": "CWE-287", "hash": 86248875192199300747266955157361751740, "dataset": "other"}
  1122. {"project": "spnego-http-auth-nginx-module", "commit_id": "a06f9efca373e25328b1c53639a48decd0854570", "target": 0, "func": "ngx_http_auth_spnego_handler(\n ngx_http_request_t * r)\n{\n ngx_int_t ret = NGX_DECLINED;\n ngx_http_auth_spnego_ctx_t *ctx;\n ngx_http_auth_spnego_loc_conf_t *alcf;\n\n alcf = ngx_http_get_module_loc_conf(r, ngx_http_auth_spnego_module);\n\n if (alcf->protect == 0) {\n return NGX_DECLINED;\n }\n\n ctx = ngx_http_get_module_ctx(r, ngx_http_auth_spnego_module);\n if (NULL == ctx) {\n ctx = ngx_palloc(r->pool, sizeof(ngx_http_auth_spnego_ctx_t));\n if (NULL == ctx) {\n return NGX_HTTP_INTERNAL_SERVER_ERROR;\n }\n ctx->token.len = 0;\n ctx->token.data = NULL;\n ctx->head = 0;\n ctx->ret = NGX_HTTP_UNAUTHORIZED;\n ngx_http_set_ctx(r, ctx, ngx_http_auth_spnego_module);\n }\n\n spnego_debug3(\"SSO auth handling IN: token.len=%d, head=%d, ret=%d\",\n ctx->token.len, ctx->head, ctx->ret);\n\n if (ctx->token.len && ctx->head) {\n spnego_debug1(\"Found token and head, returning %d\", ctx->ret);\n return ctx->ret;\n }\n\n if (NULL != r->headers_in.user.data) {\n spnego_debug0(\"User header set\");\n return NGX_OK;\n }\n\n spnego_debug0(\"Begin auth\");\n\n if (alcf->allow_basic) {\n spnego_debug0(\"Detect basic auth\");\n ret = ngx_http_auth_basic_user(r);\n if (NGX_OK == ret) {\n spnego_debug0(\"Basic auth credentials supplied by client\");\n /* If basic auth is enabled and basic creds are supplied\n * attempt basic auth. If we attempt basic auth, we do\n * not fall through to real SPNEGO */\n if (NGX_OK != ngx_http_auth_spnego_basic(r, ctx, alcf)) {\n spnego_debug0(\"Basic auth failed\");\n if (NGX_ERROR == ngx_http_auth_spnego_headers_basic_only(r, ctx, alcf)) {\n spnego_debug0(\"Error setting headers\");\n return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR);\n }\n return (ctx->ret = NGX_HTTP_UNAUTHORIZED);\n }\n\n if (!ngx_spnego_authorized_principal(r, &r->headers_in.user, alcf)) {\n spnego_debug0(\"User not authorized\");\n return (ctx->ret = NGX_HTTP_FORBIDDEN);\n }\n\n spnego_debug0(\"Basic auth succeeded\");\n return (ctx->ret = NGX_OK);\n }\n }\n\n /* Basic auth either disabled or not supplied by client */\n spnego_debug0(\"Detect SPNEGO token\");\n ret = ngx_http_auth_spnego_token(r, ctx);\n if (NGX_OK == ret) {\n spnego_debug0(\"Client sent a reasonable Negotiate header\");\n ret = ngx_http_auth_spnego_auth_user_gss(r, ctx, alcf);\n if (NGX_ERROR == ret) {\n spnego_debug0(\"GSSAPI failed\");\n return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR);\n }\n /* There are chances that client knows about Negotiate\n * but doesn't support GSSAPI. We could attempt to fall\n * back to basic here... */\n if (NGX_DECLINED == ret) {\n spnego_debug0(\"GSSAPI failed\");\n if(!alcf->allow_basic) {\n return (ctx->ret = NGX_HTTP_FORBIDDEN);\n }\n if (NGX_ERROR == ngx_http_auth_spnego_headers_basic_only(r, ctx, alcf)) {\n spnego_debug0(\"Error setting headers\");\n return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR);\n }\n return (ctx->ret = NGX_HTTP_UNAUTHORIZED);\n }\n\n if (!ngx_spnego_authorized_principal(r, &r->headers_in.user, alcf)) {\n spnego_debug0(\"User not authorized\");\n return (ctx->ret = NGX_HTTP_FORBIDDEN);\n }\n\n spnego_debug0(\"GSSAPI auth succeeded\");\n }\n\n ngx_str_t *token_out_b64 = NULL;\n switch(ret) {\n case NGX_DECLINED: /* DECLINED, but not yet FORBIDDEN */\n ctx->ret = NGX_HTTP_UNAUTHORIZED;\n break;\n case NGX_OK:\n ctx->ret = NGX_OK;\n token_out_b64 = &ctx->token_out_b64;\n break;\n case NGX_ERROR:\n default:\n ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR;\n break;\n }\n\n if (NGX_ERROR == ngx_http_auth_spnego_headers(r, ctx, token_out_b64, alcf)) {\n spnego_debug0(\"Error setting headers\");\n ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR;\n }\n\n spnego_debug3(\"SSO auth handling OUT: token.len=%d, head=%d, ret=%d\",\n ctx->token.len, ctx->head, ctx->ret);\n return ctx->ret;\n}", "idx": 521446, "cwe": "CWE-287", "hash": 103708724397830618393148159210467547382, "dataset": "other"}
  1123. {"project": "skiboot", "commit_id": "5be38b672c1410e2f10acd3ad2eecfdc81d5daf7", "target": 1, "func": "static uint64_t unpack_timestamp(const struct efi_time *timestamp)\n{\n\tuint64_t val = 0;\n\tuint16_t year = le32_to_cpu(timestamp->year);\n\n\t/* pad1, nanosecond, timezone, daylight and pad2 are meant to be zero */\n\tval |= ((uint64_t) timestamp->pad1 & 0xFF) << 0;\n\tval |= ((uint64_t) timestamp->second & 0xFF) << (1*8);\n\tval |= ((uint64_t) timestamp->minute & 0xFF) << (2*8);\n\tval |= ((uint64_t) timestamp->hour & 0xFF) << (3*8);\n\tval |= ((uint64_t) timestamp->day & 0xFF) << (4*8);\n\tval |= ((uint64_t) timestamp->month & 0xFF) << (5*8);\n\tval |= ((uint64_t) year) << (6*8);\n\n\treturn val;\n}", "idx": 217514, "cwe": "CWE-681", "hash": 261903108962534180969470598132431142070, "dataset": "other"}
  1124. {"project": "skiboot", "commit_id": "5be38b672c1410e2f10acd3ad2eecfdc81d5daf7", "target": 0, "func": "static uint64_t unpack_timestamp(const struct efi_time *timestamp)\n{\n\tuint64_t val = 0;\n\tuint16_t year = le16_to_cpu(timestamp->year);\n\n\t/* pad1, nanosecond, timezone, daylight and pad2 are meant to be zero */\n\tval |= ((uint64_t) timestamp->pad1 & 0xFF) << 0;\n\tval |= ((uint64_t) timestamp->second & 0xFF) << (1*8);\n\tval |= ((uint64_t) timestamp->minute & 0xFF) << (2*8);\n\tval |= ((uint64_t) timestamp->hour & 0xFF) << (3*8);\n\tval |= ((uint64_t) timestamp->day & 0xFF) << (4*8);\n\tval |= ((uint64_t) timestamp->month & 0xFF) << (5*8);\n\tval |= ((uint64_t) year) << (6*8);\n\n\treturn val;\n}", "idx": 521649, "cwe": "CWE-681", "hash": 337463125729458282018478225518421551092, "dataset": "other"}