instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ff_jpeg2000_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty) { int reslevelno, bandno, precno; for (reslevelno = 0; comp->reslevel && reslevelno < codsty->nreslevels; reslevelno++) { Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno; for (bandno = 0; bandno < reslevel->nbands; bandno++) { Jpeg2000Band *band = reslevel->band + bandno; for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) { Jpeg2000Prec *prec = band->prec + precno; av_freep(&prec->zerobits); av_freep(&prec->cblkincl); av_freep(&prec->cblk); } av_freep(&band->prec); } av_freep(&reslevel->band); } ff_dwt_destroy(&comp->dwt); av_freep(&comp->reslevel); av_freep(&comp->i_data); av_freep(&comp->f_data); } Commit Message: jpeg2000: fix dereferencing invalid pointers Found-by: Laurent Butti <laurentb@gmail.com> Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID:
void ff_jpeg2000_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty) { int reslevelno, bandno, precno; for (reslevelno = 0; comp->reslevel && reslevelno < codsty->nreslevels; reslevelno++) { Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno; for (bandno = 0; bandno < reslevel->nbands; bandno++) { Jpeg2000Band *band = reslevel->band + bandno; for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) { if (band->prec) { Jpeg2000Prec *prec = band->prec + precno; av_freep(&prec->zerobits); av_freep(&prec->cblkincl); av_freep(&prec->cblk); } } av_freep(&band->prec); } av_freep(&reslevel->band); } ff_dwt_destroy(&comp->dwt); av_freep(&comp->reslevel); av_freep(&comp->i_data); av_freep(&comp->f_data); }
165,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int uio_mmap_physical(struct vm_area_struct *vma) { struct uio_device *idev = vma->vm_private_data; int mi = uio_find_mem_index(vma); if (mi < 0) return -EINVAL; vma->vm_ops = &uio_physical_vm_ops; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); return remap_pfn_range(vma, vma->vm_start, idev->info->mem[mi].addr >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); } Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that really should use the vm_iomap_memory() helper. This trivially converts two of them to the helper, and comments about why the third one really needs to continue to use remap_pfn_range(), and adds the missing size check. Reported-by: Nico Golde <nico@ngolde.de> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org. CWE ID: CWE-119
static int uio_mmap_physical(struct vm_area_struct *vma) { struct uio_device *idev = vma->vm_private_data; int mi = uio_find_mem_index(vma); struct uio_mem *mem; if (mi < 0) return -EINVAL; mem = idev->info->mem + mi; if (vma->vm_end - vma->vm_start > mem->size) return -EINVAL; vma->vm_ops = &uio_physical_vm_ops; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); /* * We cannot use the vm_iomap_memory() helper here, * because vma->vm_pgoff is the map index we looked * up above in uio_find_mem_index(), rather than an * actual page offset into the mmap. * * So we just do the physical mmap without a page * offset. */ return remap_pfn_range(vma, vma->vm_start, mem->addr >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); }
165,934
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static PHP_FUNCTION(readgzfile) { char *filename; int filename_len; int flags = REPORT_ERRORS; php_stream *stream; int size; long use_include_path = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &filename, &filename_len, &use_include_path) == FAILURE) { return; } if (use_include_path) { flags |= USE_PATH; } stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC TSRMLS_CC); if (!stream) { RETURN_FALSE; } size = php_stream_passthru(stream); php_stream_close(stream); RETURN_LONG(size); } Commit Message: CWE ID: CWE-254
static PHP_FUNCTION(readgzfile) { char *filename; int filename_len; int flags = REPORT_ERRORS; php_stream *stream; int size; long use_include_path = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|l", &filename, &filename_len, &use_include_path) == FAILURE) { return; } if (use_include_path) { flags |= USE_PATH; } stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC TSRMLS_CC); if (!stream) { RETURN_FALSE; } size = php_stream_passthru(stream); php_stream_close(stream); RETURN_LONG(size); }
165,320
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2) { if (tl1 > l2) return 0; return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0); } Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2) l_strnstart(netdissect_options *ndo, const char *tstr1, u_int tl1, const char *str2, u_int l2) { if (!ND_TTEST2(*str2, tl1)) { /* * We don't have tl1 bytes worth of captured data * for the string, so we can't check for this * string. */ return 0; } if (tl1 > l2) return 0; return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0); }
167,885
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(snmp_set_oid_output_format) { long a1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) { RETURN_FALSE; } switch((int) a1) { case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: case NETSNMP_OID_OUTPUT_UCD: case NETSNMP_OID_OUTPUT_NONE: netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1); RETURN_TRUE; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1); RETURN_FALSE; break; } } Commit Message: CWE ID: CWE-416
PHP_FUNCTION(snmp_set_oid_output_format) { long a1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) { RETURN_FALSE; } switch((int) a1) { case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: case NETSNMP_OID_OUTPUT_UCD: case NETSNMP_OID_OUTPUT_NONE: netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1); RETURN_TRUE; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1); RETURN_FALSE; break; }
164,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void a2dp_open_ctrl_path(struct a2dp_stream_common *common) { int i; /* retry logic to catch any timing variations on control channel */ for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) { /* connect control channel if not already connected */ if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0) { /* success, now check if stack is ready */ if (check_a2dp_ready(common) == 0) break; ERROR("error : a2dp not ready, wait 250 ms and retry"); usleep(250000); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; } /* ctrl channel not ready, wait a bit */ usleep(250000); } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void a2dp_open_ctrl_path(struct a2dp_stream_common *common) { int i; /* retry logic to catch any timing variations on control channel */ for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) { /* connect control channel if not already connected */ if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0) { /* success, now check if stack is ready */ if (check_a2dp_ready(common) == 0) break; ERROR("error : a2dp not ready, wait 250 ms and retry"); TEMP_FAILURE_RETRY(usleep(250000)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; } /* ctrl channel not ready, wait a bit */ TEMP_FAILURE_RETRY(usleep(250000)); } }
173,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_error_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { ENUM_ENTRY (MY_OBJECT_ERROR_FOO, "Foo"), ENUM_ENTRY (MY_OBJECT_ERROR_BAR, "Bar"), { 0, 0, 0 } }; etype = g_enum_register_static ("MyObjectError", values); } return etype; } Commit Message: CWE ID: CWE-264
my_object_error_get_type (void)
165,097
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CoordinatorImpl::RequestGlobalMemoryDumpForPid( base::ProcessId pid, const RequestGlobalMemoryDumpForPidCallback& callback) { if (pid == base::kNullProcessId) { callback.Run(false, nullptr); return; } auto adapter = [](const RequestGlobalMemoryDumpForPidCallback& callback, bool success, uint64_t, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args( base::trace_event::MemoryDumpType::SUMMARY_ONLY, base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND, {}, false /* addToTrace */, pid); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <lalitm@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: oysteine <oysteine@chromium.org> Reviewed-by: Albert J. Wong <ajwong@chromium.org> Reviewed-by: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void CoordinatorImpl::RequestGlobalMemoryDumpForPid( base::ProcessId pid, const RequestGlobalMemoryDumpForPidCallback& callback) { if (pid == base::kNullProcessId) { callback.Run(false, nullptr); return; } auto adapter = [](const RequestGlobalMemoryDumpForPidCallback& callback, bool success, uint64_t, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args( base::trace_event::MemoryDumpType::SUMMARY_ONLY, base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND, {}, false /* add_to_trace */, pid); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); }
172,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition) { ASSERT(m_document); ASSERT(!hasParserBlockingScript()); { ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script); ASSERT(scriptLoader); if (!scriptLoader) return; ASSERT(scriptLoader->isParserInserted()); if (!isExecutingScript()) Microtask::performCheckpoint(); InsertionPointRecord insertionPointRecord(m_host->inputStream()); NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); scriptLoader->prepareScript(scriptStartPosition); if (!scriptLoader->willBeParserExecuted()) return; if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) { requestDeferredScript(script); } else if (scriptLoader->readyToBeParserExecuted()) { if (m_scriptNestingLevel == 1) { m_parserBlockingScript.setElement(script); m_parserBlockingScript.setStartingPosition(scriptStartPosition); } else { ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition); scriptLoader->executeScript(sourceCode); } } else { requestParsingBlockingScript(script); } } } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 R=haraken@chromium.org Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254
void HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition) { ASSERT(m_document); ASSERT(!hasParserBlockingScript()); { ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script); ASSERT(scriptLoader); if (!scriptLoader) return; ASSERT(scriptLoader->isParserInserted()); if (!isExecutingScript()) Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate()); InsertionPointRecord insertionPointRecord(m_host->inputStream()); NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); scriptLoader->prepareScript(scriptStartPosition); if (!scriptLoader->willBeParserExecuted()) return; if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) { requestDeferredScript(script); } else if (scriptLoader->readyToBeParserExecuted()) { if (m_scriptNestingLevel == 1) { m_parserBlockingScript.setElement(script); m_parserBlockingScript.setStartingPosition(scriptStartPosition); } else { ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition); scriptLoader->executeScript(sourceCode); } } else { requestParsingBlockingScript(script); } } }
171,947
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int linear_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct linear_c *lc = (struct linear_c *) ti->private; return __blkdev_driver_ioctl(lc->dev->bdev, lc->dev->mode, cmd, arg); } Commit Message: dm: do not forward ioctls from logical volumes to the underlying device A logical volume can map to just part of underlying physical volume. In this case, it must be treated like a partition. Based on a patch from Alasdair G Kergon. Cc: Alasdair G Kergon <agk@redhat.com> Cc: dm-devel@redhat.com Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
static int linear_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct linear_c *lc = (struct linear_c *) ti->private; struct dm_dev *dev = lc->dev; int r = 0; /* * Only pass ioctls through if the device sizes match exactly. */ if (lc->start || ti->len != i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT) r = scsi_verify_blk_ioctl(NULL, cmd); return r ? : __blkdev_driver_ioctl(dev->bdev, dev->mode, cmd, arg); }
165,723
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents) : profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_)), web_contents_(web_contents), delegate_(new DefaultBindingsDelegate(web_contents_)), devices_updates_enabled_(false), frontend_loaded_(false), reloading_(false), weak_factory_(this) { g_instances.Get().push_back(this); frontend_contents_observer_.reset(new FrontendWebContentsObserver(this)); web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false; file_helper_.reset(new DevToolsFileHelper(web_contents_, profile_, this)); file_system_indexer_ = new DevToolsFileSystemIndexer(); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_); embedder_message_dispatcher_.reset( DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); frontend_host_.reset(content::DevToolsFrontendHost::Create( web_contents_->GetMainFrame(), base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, base::Unretained(this)))); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents) : profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_)), web_contents_(web_contents), delegate_(new DefaultBindingsDelegate(web_contents_)), devices_updates_enabled_(false), frontend_loaded_(false), reloading_(false), weak_factory_(this) { g_instances.Get().push_back(this); frontend_contents_observer_.reset(new FrontendWebContentsObserver(this)); web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false; file_helper_.reset(new DevToolsFileHelper(web_contents_, profile_, this)); file_system_indexer_ = new DevToolsFileSystemIndexer(); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_); embedder_message_dispatcher_.reset( DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); UpdateFrontendHost(); }
172,452
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Plugin::LoadNaClModuleContinuationIntern(ErrorInfo* error_info) { if (using_ipc_proxy_) return true; if (!main_subprocess_.StartSrpcServices()) { error_info->SetReport(ERROR_SRPC_CONNECTION_FAIL, "SRPC connection failure for " + main_subprocess_.description()); return false; } if (!main_subprocess_.StartJSObjectProxy(this, error_info)) { return false; } PLUGIN_PRINTF(("Plugin::LoadNaClModule (%s)\n", main_subprocess_.detailed_description().c_str())); return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool Plugin::LoadNaClModuleContinuationIntern(ErrorInfo* error_info) { if (!main_subprocess_.StartSrpcServices()) { error_info->SetReport(ERROR_SRPC_CONNECTION_FAIL, "SRPC connection failure for " + main_subprocess_.description()); return false; } if (!main_subprocess_.StartJSObjectProxy(this, error_info)) { return false; } PLUGIN_PRINTF(("Plugin::LoadNaClModule (%s)\n", main_subprocess_.detailed_description().c_str())); return true; }
170,743
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CheckClientDownloadRequest::UploadBinary( DownloadCheckResult result, DownloadCheckResultReason reason) { saved_result_ = result; saved_reason_ = reason; bool upload_for_dlp = ShouldUploadForDlpScan(); bool upload_for_malware = ShouldUploadForMalwareScan(reason); auto request = std::make_unique<DownloadItemRequest>( item_, /*read_immediately=*/true, base::BindOnce(&CheckClientDownloadRequest::OnDeepScanningComplete, weakptr_factory_.GetWeakPtr())); Profile* profile = Profile::FromBrowserContext(GetBrowserContext()); if (upload_for_dlp) { DlpDeepScanningClientRequest dlp_request; dlp_request.set_content_source(DlpDeepScanningClientRequest::FILE_DOWNLOAD); request->set_request_dlp_scan(std::move(dlp_request)); } if (upload_for_malware) { MalwareDeepScanningClientRequest malware_request; malware_request.set_population( MalwareDeepScanningClientRequest::POPULATION_ENTERPRISE); malware_request.set_download_token( DownloadProtectionService::GetDownloadPingToken(item_)); request->set_request_malware_scan(std::move(malware_request)); } request->set_dm_token( policy::BrowserDMTokenStorage::Get()->RetrieveDMToken()); service()->UploadForDeepScanning(profile, std::move(request)); } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <domfc@chromium.org> Reviewed-by: Tien Mai <tienmai@chromium.org> Reviewed-by: Daniel Rubery <drubery@chromium.org> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
void CheckClientDownloadRequest::UploadBinary( DownloadCheckResult result, DownloadCheckResultReason reason) { saved_result_ = result; saved_reason_ = reason; bool upload_for_dlp = ShouldUploadForDlpScan(); bool upload_for_malware = ShouldUploadForMalwareScan(reason); auto request = std::make_unique<DownloadItemRequest>( item_, /*read_immediately=*/true, base::BindOnce(&CheckClientDownloadRequest::OnDeepScanningComplete, weakptr_factory_.GetWeakPtr())); Profile* profile = Profile::FromBrowserContext(GetBrowserContext()); if (upload_for_dlp) { DlpDeepScanningClientRequest dlp_request; dlp_request.set_content_source(DlpDeepScanningClientRequest::FILE_DOWNLOAD); request->set_request_dlp_scan(std::move(dlp_request)); } if (upload_for_malware) { MalwareDeepScanningClientRequest malware_request; malware_request.set_population( MalwareDeepScanningClientRequest::POPULATION_ENTERPRISE); malware_request.set_download_token( DownloadProtectionService::GetDownloadPingToken(item_)); request->set_request_malware_scan(std::move(malware_request)); } auto dm_token = BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken(); DCHECK(dm_token.is_valid()); request->set_dm_token(dm_token.value()); service()->UploadForDeepScanning(profile, std::move(request)); }
172,358
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_METHOD(Phar, getSupportedSignatures) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); add_next_index_stringl(return_value, "MD5", 3, 1); add_next_index_stringl(return_value, "SHA-1", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, "SHA-256", 7, 1); add_next_index_stringl(return_value, "SHA-512", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, "OpenSSL", 7, 1); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { add_next_index_stringl(return_value, "OpenSSL", 7, 1); } #endif } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, getSupportedSignatures) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); add_next_index_stringl(return_value, "MD5", 3, 1); add_next_index_stringl(return_value, "SHA-1", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, "SHA-256", 7, 1); add_next_index_stringl(return_value, "SHA-512", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, "OpenSSL", 7, 1); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { add_next_index_stringl(return_value, "OpenSSL", 7, 1); } #endif }
165,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection( blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) { DCHECK_EQ(WORKER_NOT_READY, state_); state_ = WORKER_READY; agent_ptr_.Bind(std::move(devtools_agent_ptr_info)); if (!sessions().empty()) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } RenderProcessHost* host = RenderProcessHost::FromID(worker_process_id_); for (DevToolsSession* session : sessions()) { session->SetRenderer(host, nullptr); session->AttachToAgent(agent_ptr_); } } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection( blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) { DCHECK_EQ(WORKER_NOT_READY, state_); state_ = WORKER_READY; agent_ptr_.Bind(std::move(devtools_agent_ptr_info)); if (!sessions().empty()) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } for (DevToolsSession* session : sessions()) { session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } }
172,785
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void HeapObjectHeader::zapMagic() { ASSERT(checkHeader()); m_magic = zappedMagic; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
void HeapObjectHeader::zapMagic() { checkHeader(); m_magic = zappedMagic; }
172,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: LockContentsView::UserState::UserState(AccountId account_id) : account_id(account_id) {} Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
LockContentsView::UserState::UserState(AccountId account_id)
172,198
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GfxImageColorMap::getGrayLine(Guchar *in, Guchar *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmalloc (length * nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getGrayLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getGrayLine(in, out, length); break; } } Commit Message: CWE ID: CWE-189
void GfxImageColorMap::getGrayLine(Guchar *in, Guchar *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmallocn (length, nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getGrayLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getGrayLine(in, out, length); break; } }
164,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int av_reallocp_array(void *ptr, size_t nmemb, size_t size) { void **ptrptr = ptr; *ptrptr = av_realloc_f(*ptrptr, nmemb, size); if (!*ptrptr && !(nmemb && size)) return AVERROR(ENOMEM); return 0; } Commit Message: avutil/mem: Fix flipped condition Fixes return code and later null pointer dereference Found-by: Laurent Butti <laurentb@gmail.com> Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID:
int av_reallocp_array(void *ptr, size_t nmemb, size_t size) { void **ptrptr = ptr; *ptrptr = av_realloc_f(*ptrptr, nmemb, size); if (!*ptrptr && nmemb && size) return AVERROR(ENOMEM); return 0; }
165,995
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual size_t GetNumActiveInputMethods() { scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods()); return descriptors->size(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual size_t GetNumActiveInputMethods() { scoped_ptr<input_method::InputMethodDescriptors> descriptors( GetActiveInputMethods()); return descriptors->size(); }
170,491
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CoordinatorImpl::RequestGlobalMemoryDump( MemoryDumpType dump_type, MemoryDumpLevelOfDetail level_of_detail, const std::vector<std::string>& allocator_dump_names, const RequestGlobalMemoryDumpCallback& callback) { auto adapter = [](const RequestGlobalMemoryDumpCallback& callback, bool success, uint64_t, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args(dump_type, level_of_detail, allocator_dump_names, false /* add_to_trace */, base::kNullProcessId); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <lalitm@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: oysteine <oysteine@chromium.org> Reviewed-by: Albert J. Wong <ajwong@chromium.org> Reviewed-by: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void CoordinatorImpl::RequestGlobalMemoryDump( MemoryDumpType dump_type, MemoryDumpLevelOfDetail level_of_detail, const std::vector<std::string>& allocator_dump_names, const RequestGlobalMemoryDumpCallback& callback) { // Don't allow arbitary processes to obtain VM regions. Only the heap profiler // is allowed to obtain them using the special method on the different // interface. if (level_of_detail == MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER) { bindings_.ReportBadMessage( "Requested global memory dump using level of detail reserved for the " "heap profiler."); return; } auto adapter = [](const RequestGlobalMemoryDumpCallback& callback, bool success, uint64_t, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args(dump_type, level_of_detail, allocator_dump_names, false /* add_to_trace */, base::kNullProcessId); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); }
172,915
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long long Segment::GetDuration() const { assert(m_pInfo); return m_pInfo->GetDuration(); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Segment::GetDuration() const
174,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FrameSelection::MoveCaretSelection(const IntPoint& point) { DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); Element* const editable = ComputeVisibleSelectionInDOMTree().RootEditableElement(); if (!editable) return; const VisiblePosition position = VisiblePositionForContentsPoint(point, GetFrame()); SelectionInDOMTree::Builder builder; builder.SetIsDirectional(GetSelectionInDOMTree().IsDirectional()); builder.SetIsHandleVisible(true); if (position.IsNotNull()) builder.Collapse(position.ToPositionWithAffinity()); SetSelection(builder.Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetSetSelectionBy(SetSelectionBy::kUser) .Build()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Reviewed-by: Kent Tamura <tkent@chromium.org> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
void FrameSelection::MoveCaretSelection(const IntPoint& point) { DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); Element* const editable = ComputeVisibleSelectionInDOMTree().RootEditableElement(); if (!editable) return; const VisiblePosition position = VisiblePositionForContentsPoint(point, GetFrame()); SelectionInDOMTree::Builder builder; builder.SetIsDirectional(GetSelectionInDOMTree().IsDirectional()); if (position.IsNotNull()) builder.Collapse(position.ToPositionWithAffinity()); SetSelection(builder.Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetSetSelectionBy(SetSelectionBy::kUser) .SetShouldShowHandle(true) .Build()); }
171,756
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintPreviewMessageHandler::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { int page_number = params.page_number; if (page_number < FIRST_PAGE_INDEX || !params.data_size) return; PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; scoped_refptr<base::RefCountedBytes> data_bytes = GetDataFromHandle(params.metafile_data_handle, params.data_size); DCHECK(data_bytes); print_preview_ui->SetPrintPreviewDataForIndex(page_number, std::move(data_bytes)); print_preview_ui->OnDidPreviewPage(page_number, params.preview_request_id); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. TBR=jzfeng@chromium.org BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <weili@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
void PrintPreviewMessageHandler::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { int page_number = params.page_number; if (page_number < FIRST_PAGE_INDEX || !params.data_size) return; PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; if (IsOopifEnabled() && print_preview_ui->source_is_modifiable()) { auto* client = PrintCompositeClient::FromWebContents(web_contents()); DCHECK(client); // Use utility process to convert skia metafile to pdf. client->DoComposite( params.metafile_data_handle, params.data_size, base::BindOnce(&PrintPreviewMessageHandler::OnCompositePdfPageDone, weak_ptr_factory_.GetWeakPtr(), params.page_number, params.preview_request_id)); } else { NotifyUIPreviewPageReady( page_number, params.preview_request_id, GetDataFromHandle(params.metafile_data_handle, params.data_size)); } }
171,888
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void __fput_sync(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; file_sb_list_del(file); BUG_ON(!(task->flags & PF_KTHREAD)); __fput(file); } } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-17
void __fput_sync(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; BUG_ON(!(task->flags & PF_KTHREAD)); __fput(file); } }
166,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void LocalFileSystem::resolveURLInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, const KURL& fileSystemURL, PassRefPtr<CallbackWrapper> callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } fileSystem()->resolveURL(fileSystemURL, callbacks->release()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::resolveURLInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, const KURL& fileSystemURL, CallbackWrapper* callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } fileSystem()->resolveURL(fileSystemURL, callbacks->release()); }
171,431
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: base::string16 GetAppForProtocolUsingAssocQuery(const GURL& url) { base::string16 url_scheme = base::ASCIIToUTF16(url.scheme()); if (url_scheme.empty()) return base::string16(); wchar_t out_buffer[1024]; DWORD buffer_size = arraysize(out_buffer); HRESULT hr = AssocQueryString(ASSOCF_IS_PROTOCOL, ASSOCSTR_FRIENDLYAPPNAME, url_scheme.c_str(), NULL, out_buffer, &buffer_size); if (FAILED(hr)) { DLOG(WARNING) << "AssocQueryString failed!"; return base::string16(); } return base::string16(out_buffer); } Commit Message: Validate external protocols before launching on Windows Bug: 889459 Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef Reviewed-on: https://chromium-review.googlesource.com/c/1256208 Reviewed-by: Greg Thompson <grt@chromium.org> Commit-Queue: Mustafa Emre Acer <meacer@chromium.org> Cr-Commit-Position: refs/heads/master@{#597611} CWE ID: CWE-20
base::string16 GetAppForProtocolUsingAssocQuery(const GURL& url) { const base::string16 url_scheme = base::ASCIIToUTF16(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) return base::string16(); wchar_t out_buffer[1024]; DWORD buffer_size = arraysize(out_buffer); HRESULT hr = AssocQueryString(ASSOCF_IS_PROTOCOL, ASSOCSTR_FRIENDLYAPPNAME, url_scheme.c_str(), NULL, out_buffer, &buffer_size); if (FAILED(hr)) { DLOG(WARNING) << "AssocQueryString failed!"; return base::string16(); } return base::string16(out_buffer); }
172,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint32 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ Commit Message: * tools/tiffcrop.c: fix readContigStripsIntoBuffer() in -i (ignore) mode so that the output buffer is correctly incremented to avoid write outside bounds. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2620 CWE ID: CWE-119
static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint32 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += stripsize; } return 1; } /* end readContigStripsIntoBuffer */
168,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */ int i; if (heap->count+1 > heap->max_size) { /* we need to allocate more memory */ heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size))); heap->max_size *= 2; } heap->ctor(elem TSRMLS_CC); /* sifting up */ for(i = heap->count++; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) { heap->elements[i] = heap->elements[(i-1)/2]; } if (EG(exception)) { /* exception thrown during comparison */ } heap->elements[i] = elem; } /* }}} */ Commit Message: CWE ID:
static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */ int i; if (heap->count+1 > heap->max_size) { /* we need to allocate more memory */ heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size))); heap->max_size *= 2; } heap->ctor(elem TSRMLS_CC); /* sifting up */ for(i = heap->count; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) { heap->elements[i] = heap->elements[(i-1)/2]; } heap->count++; if (EG(exception)) { /* exception thrown during comparison */ } heap->elements[i] = elem; } /* }}} */
165,307
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int rc, xprefix; switch (type) { case ACL_TYPE_ACCESS: xprefix = JFFS2_XPREFIX_ACL_ACCESS; if (acl) { umode_t mode = inode->i_mode; rc = posix_acl_equiv_mode(acl, &mode); if (rc < 0) return rc; if (inode->i_mode != mode) { struct iattr attr; attr.ia_valid = ATTR_MODE | ATTR_CTIME; attr.ia_mode = mode; attr.ia_ctime = CURRENT_TIME_SEC; rc = jffs2_do_setattr(inode, &attr); if (rc < 0) return rc; } if (rc == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: xprefix = JFFS2_XPREFIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } rc = __jffs2_set_acl(inode, xprefix, acl); if (!rc) set_cached_acl(inode, type, acl); return rc; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int rc, xprefix; switch (type) { case ACL_TYPE_ACCESS: xprefix = JFFS2_XPREFIX_ACL_ACCESS; if (acl) { umode_t mode; rc = posix_acl_update_mode(inode, &mode, &acl); if (rc) return rc; if (inode->i_mode != mode) { struct iattr attr; attr.ia_valid = ATTR_MODE | ATTR_CTIME; attr.ia_mode = mode; attr.ia_ctime = CURRENT_TIME_SEC; rc = jffs2_do_setattr(inode, &attr); if (rc < 0) return rc; } } break; case ACL_TYPE_DEFAULT: xprefix = JFFS2_XPREFIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } rc = __jffs2_set_acl(inode, xprefix, acl); if (!rc) set_cached_acl(inode, type, acl); return rc; }
166,974
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xdr_krb5_principal(XDR *xdrs, krb5_principal *objp) { int ret; char *p = NULL; krb5_principal pr = NULL; static krb5_context context = NULL; /* using a static context here is ugly, but should work ok, and the other solutions are even uglier */ if (!context && kadm5_init_krb5_context(&context)) return(FALSE); switch(xdrs->x_op) { case XDR_ENCODE: if (*objp) { if((ret = krb5_unparse_name(context, *objp, &p)) != 0) return FALSE; } if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) free(p); break; case XDR_DECODE: if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) { ret = krb5_parse_name(context, p, &pr); if(ret != 0) return FALSE; *objp = pr; free(p); } else *objp = NULL; break; case XDR_FREE: if(*objp != NULL) krb5_free_principal(context, *objp); break; } return TRUE; } Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421] [MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free partial deserialization results upon failure to deserialize. This responsibility belongs to the callers, svctcp_getargs() and svcudp_getargs(); doing it in the unwrap function results in freeing the results twice. In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers we are freeing, as other XDR functions such as xdr_bytes() and xdr_string(). ticket: 8056 (new) target_version: 1.13.1 tags: pullup CWE ID:
xdr_krb5_principal(XDR *xdrs, krb5_principal *objp) { int ret; char *p = NULL; krb5_principal pr = NULL; static krb5_context context = NULL; /* using a static context here is ugly, but should work ok, and the other solutions are even uglier */ if (!context && kadm5_init_krb5_context(&context)) return(FALSE); switch(xdrs->x_op) { case XDR_ENCODE: if (*objp) { if((ret = krb5_unparse_name(context, *objp, &p)) != 0) return FALSE; } if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) free(p); break; case XDR_DECODE: if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) { ret = krb5_parse_name(context, p, &pr); if(ret != 0) return FALSE; *objp = pr; free(p); } else *objp = NULL; break; case XDR_FREE: if(*objp != NULL) krb5_free_principal(context, *objp); *objp = NULL; break; } return TRUE; }
166,790
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC) { GC_REFCOUNT(ht) = 1; GC_TYPE_INFO(ht) = IS_ARRAY; ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS; ht->nTableSize = zend_hash_check_size(nSize); ht->nTableMask = HT_MIN_MASK; HT_SET_DATA_ADDR(ht, &uninitialized_bucket); ht->nNumUsed = 0; ht->nNumOfElements = 0; ht->nInternalPointer = HT_INVALID_IDX; ht->nNextFreeElement = 0; ht->pDestructor = pDestructor; } Commit Message: Fix #73832 - leave the table in a safe state if the size is too big. CWE ID: CWE-190
ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC) { GC_REFCOUNT(ht) = 1; GC_TYPE_INFO(ht) = IS_ARRAY; ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS; ht->nTableMask = HT_MIN_MASK; HT_SET_DATA_ADDR(ht, &uninitialized_bucket); ht->nNumUsed = 0; ht->nNumOfElements = 0; ht->nInternalPointer = HT_INVALID_IDX; ht->nNextFreeElement = 0; ht->pDestructor = pDestructor; ht->nTableSize = zend_hash_check_size(nSize); }
168,410
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static sk_sp<SkImage> unPremulSkImageToPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kPremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(input->width()) * info.bytesPerPixel()); } Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936} CWE ID: CWE-787
static sk_sp<SkImage> unPremulSkImageToPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kPremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<unsigned>(input->width()) * info.bytesPerPixel()); }
172,507
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BookmarksIOFunction::ShowSelectFileDialog( ui::SelectFileDialog::Type type, const base::FilePath& default_path) { AddRef(); WebContents* web_contents = dispatcher()->delegate()-> GetAssociatedWebContents(); select_file_dialog_ = ui::SelectFileDialog::Create( this, new ChromeSelectFilePolicy(web_contents)); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html")); if (type == ui::SelectFileDialog::SELECT_OPEN_FILE) file_type_info.support_drive = true; select_file_dialog_->SelectFile(type, string16(), default_path, &file_type_info, 0, FILE_PATH_LITERAL(""), NULL, NULL); } Commit Message: Fix heap-use-after-free in BookmarksIOFunction::ShowSelectFileDialog. BUG=177410 Review URL: https://chromiumcodereview.appspot.com/12326086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void BookmarksIOFunction::ShowSelectFileDialog( ui::SelectFileDialog::Type type, const base::FilePath& default_path) { if (!dispatcher()) return; // Extension was unloaded. AddRef(); WebContents* web_contents = dispatcher()->delegate()-> GetAssociatedWebContents(); select_file_dialog_ = ui::SelectFileDialog::Create( this, new ChromeSelectFilePolicy(web_contents)); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html")); if (type == ui::SelectFileDialog::SELECT_OPEN_FILE) file_type_info.support_drive = true; select_file_dialog_->SelectFile(type, string16(), default_path, &file_type_info, 0, FILE_PATH_LITERAL(""), NULL, NULL); }
171,435
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: magic_getparam(struct magic_set *ms, int param, void *val) { switch (param) { case MAGIC_PARAM_INDIR_MAX: *(size_t *)val = ms->indir_max; return 0; case MAGIC_PARAM_NAME_MAX: *(size_t *)val = ms->name_max; return 0; case MAGIC_PARAM_ELF_PHNUM_MAX: *(size_t *)val = ms->elf_phnum_max; return 0; case MAGIC_PARAM_ELF_SHNUM_MAX: *(size_t *)val = ms->elf_shnum_max; return 0; default: errno = EINVAL; return -1; } } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
magic_getparam(struct magic_set *ms, int param, void *val) { switch (param) { case MAGIC_PARAM_INDIR_MAX: *(size_t *)val = ms->indir_max; return 0; case MAGIC_PARAM_NAME_MAX: *(size_t *)val = ms->name_max; return 0; case MAGIC_PARAM_ELF_PHNUM_MAX: *(size_t *)val = ms->elf_phnum_max; return 0; case MAGIC_PARAM_ELF_SHNUM_MAX: *(size_t *)val = ms->elf_shnum_max; return 0; case MAGIC_PARAM_ELF_NOTES_MAX: *(size_t *)val = ms->elf_notes_max; return 0; default: errno = EINVAL; return -1; } }
166,774
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: check_mountpoint(const char *progname, char *mountpoint) { int err; struct stat statbuf; /* does mountpoint exist and is it a directory? */ err = stat(mountpoint, &statbuf); if (err) { fprintf(stderr, "%s: failed to stat %s: %s\n", progname, mountpoint, strerror(errno)); return EX_USAGE; } if (!S_ISDIR(statbuf.st_mode)) { fprintf(stderr, "%s: %s is not a directory!", progname, mountpoint); return EX_USAGE; } #if CIFS_LEGACY_SETUID_CHECK /* do extra checks on mountpoint for legacy setuid behavior */ if (!getuid() || geteuid()) return 0; if (statbuf.st_uid != getuid()) { fprintf(stderr, "%s: %s is not owned by user\n", progname, mountpoint); return EX_USAGE; } if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) { fprintf(stderr, "%s: invalid permissions on %s\n", progname, mountpoint); return EX_USAGE; } #endif /* CIFS_LEGACY_SETUID_CHECK */ return 0; } Commit Message: CWE ID: CWE-59
check_mountpoint(const char *progname, char *mountpoint) { int err; struct stat statbuf; /* does mountpoint exist and is it a directory? */ err = stat(".", &statbuf); if (err) { fprintf(stderr, "%s: failed to stat %s: %s\n", progname, mountpoint, strerror(errno)); return EX_USAGE; } if (!S_ISDIR(statbuf.st_mode)) { fprintf(stderr, "%s: %s is not a directory!", progname, mountpoint); return EX_USAGE; } #if CIFS_LEGACY_SETUID_CHECK /* do extra checks on mountpoint for legacy setuid behavior */ if (!getuid() || geteuid()) return 0; if (statbuf.st_uid != getuid()) { fprintf(stderr, "%s: %s is not owned by user\n", progname, mountpoint); return EX_USAGE; } if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) { fprintf(stderr, "%s: invalid permissions on %s\n", progname, mountpoint); return EX_USAGE; } #endif /* CIFS_LEGACY_SETUID_CHECK */ return 0; }
165,168
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Huff_Compress(msg_t *mbuf, int offset) { int i, ch, size; byte seq[65536]; byte* buffer; huff_t huff; size = mbuf->cursize - offset; buffer = mbuf->data+ + offset; if (size<=0) { return; } Com_Memset(&huff, 0, sizeof(huff_t)); huff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]); huff.tree->symbol = NYT; huff.tree->weight = 0; huff.lhead->next = huff.lhead->prev = NULL; huff.tree->parent = huff.tree->left = huff.tree->right = NULL; seq[0] = (size>>8); seq[1] = size&0xff; bloc = 16; for (i=0; i<size; i++ ) { ch = buffer[i]; Huff_transmit(&huff, ch, seq); /* Transmit symbol */ Huff_addRef(&huff, (byte)ch); /* Do update */ } bloc += 8; // next byte mbuf->cursize = (bloc>>3) + offset; Com_Memcpy(mbuf->data+offset, seq, (bloc>>3)); } Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left. CWE ID: CWE-119
void Huff_Compress(msg_t *mbuf, int offset) { int i, ch, size; byte seq[65536]; byte* buffer; huff_t huff; size = mbuf->cursize - offset; buffer = mbuf->data+ + offset; if (size<=0) { return; } Com_Memset(&huff, 0, sizeof(huff_t)); huff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]); huff.tree->symbol = NYT; huff.tree->weight = 0; huff.lhead->next = huff.lhead->prev = NULL; huff.tree->parent = huff.tree->left = huff.tree->right = NULL; seq[0] = (size>>8); seq[1] = size&0xff; bloc = 16; for (i=0; i<size; i++ ) { ch = buffer[i]; Huff_transmit(&huff, ch, seq, size<<3); /* Transmit symbol */ Huff_addRef(&huff, (byte)ch); /* Do update */ } bloc += 8; // next byte mbuf->cursize = (bloc>>3) + offset; Com_Memcpy(mbuf->data+offset, seq, (bloc>>3)); }
167,993
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderProcessHostImpl::OnCompositorSurfaceBuffersSwappedNoHost( int32 surface_id, uint64 surface_handle, int32 route_id, const gfx::Size& size, int32 gpu_process_host_id) { TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwappedNoHost"); RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id, gpu_process_host_id, false, 0); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderProcessHostImpl::OnCompositorSurfaceBuffersSwappedNoHost( int32 surface_id, uint64 surface_handle, int32 route_id, const gfx::Size& size, int32 gpu_process_host_id) { TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwappedNoHost"); RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id, gpu_process_host_id, surface_handle, 0); }
171,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: do_async_increment (IncrementData *data) { gint32 newx = data->x + 1; dbus_g_method_return (data->context, newx); g_free (data); return FALSE; } Commit Message: CWE ID: CWE-264
do_async_increment (IncrementData *data)
165,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int dtls1_listen(SSL *s, struct sockaddr *client) { int ret; SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE); s->d1->listen = 1; (void)BIO_dgram_get_peer(SSL_get_rbio(s), client); return 1; } Commit Message: CWE ID:
int dtls1_listen(SSL *s, struct sockaddr *client) { int ret; /* Ensure there is no state left over from a previous invocation */ SSL_clear(s); SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE); s->d1->listen = 1; (void)BIO_dgram_get_peer(SSL_get_rbio(s), client); return 1; }
164,821
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) + len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); } Commit Message: Add bounds check before length read CWE ID: CWE-125
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) + len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); }
169,265
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static u32 svc_rdma_get_inv_rkey(struct rpcrdma_msg *rdma_argp, struct rpcrdma_write_array *wr_ary, struct rpcrdma_write_array *rp_ary) { struct rpcrdma_read_chunk *rd_ary; struct rpcrdma_segment *arg_ch; rd_ary = (struct rpcrdma_read_chunk *)&rdma_argp->rm_body.rm_chunks[0]; if (rd_ary->rc_discrim != xdr_zero) return be32_to_cpu(rd_ary->rc_target.rs_handle); if (wr_ary && be32_to_cpu(wr_ary->wc_nchunks)) { arg_ch = &wr_ary->wc_array[0].wc_target; return be32_to_cpu(arg_ch->rs_handle); } if (rp_ary && be32_to_cpu(rp_ary->wc_nchunks)) { arg_ch = &rp_ary->wc_array[0].wc_target; return be32_to_cpu(arg_ch->rs_handle); } return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static u32 svc_rdma_get_inv_rkey(struct rpcrdma_msg *rdma_argp, static u32 svc_rdma_get_inv_rkey(__be32 *rdma_argp, __be32 *wr_lst, __be32 *rp_ch) { __be32 *p; p = rdma_argp + rpcrdma_fixed_maxsz; if (*p != xdr_zero) p += 2; else if (wr_lst && be32_to_cpup(wr_lst + 1)) p = wr_lst + 2; else if (rp_ch && be32_to_cpup(rp_ch + 1)) p = rp_ch + 2; else return 0; return be32_to_cpup(p); } /* ib_dma_map_page() is used here because svc_rdma_dma_unmap() * is used during completion to DMA-unmap this memory, and * it uses ib_dma_unmap_page() exclusively. */ static int svc_rdma_dma_map_buf(struct svcxprt_rdma *rdma, struct svc_rdma_op_ctxt *ctxt, unsigned int sge_no, unsigned char *base, unsigned int len) { unsigned long offset = (unsigned long)base & ~PAGE_MASK; struct ib_device *dev = rdma->sc_cm_id->device; dma_addr_t dma_addr; dma_addr = ib_dma_map_page(dev, virt_to_page(base), offset, len, DMA_TO_DEVICE); if (ib_dma_mapping_error(dev, dma_addr)) return -EIO; ctxt->sge[sge_no].addr = dma_addr; ctxt->sge[sge_no].length = len; ctxt->sge[sge_no].lkey = rdma->sc_pd->local_dma_lkey; svc_rdma_count_mappings(rdma, ctxt); return 0; }
168,171
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); }
167,027
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void TabStripModelObserver::TabDetachedAt(TabContents* contents, int index) { } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void TabStripModelObserver::TabDetachedAt(TabContents* contents, void TabStripModelObserver::TabDetachedAt(WebContents* contents, int index) { }
171,518
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: DWORD UnprivilegedProcessDelegate::GetExitCode() { DCHECK(main_task_runner_->BelongsToCurrentThread()); DWORD exit_code = CONTROL_C_EXIT; if (worker_process_.IsValid()) { if (!::GetExitCodeProcess(worker_process_, &exit_code)) { LOG_GETLASTERROR(INFO) << "Failed to query the exit code of the worker process"; exit_code = CONTROL_C_EXIT; } } return exit_code; } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
DWORD UnprivilegedProcessDelegate::GetExitCode() { DWORD UnprivilegedProcessDelegate::GetProcessId() const { if (worker_process_.IsValid()) { return ::GetProcessId(worker_process_); } else { return 0; } } bool UnprivilegedProcessDelegate::IsPermanentError(int failure_count) const { // Get exit code of the worker process if it is available. DWORD exit_code = CONTROL_C_EXIT; if (worker_process_.IsValid()) { if (!::GetExitCodeProcess(worker_process_, &exit_code)) { LOG_GETLASTERROR(INFO) << "Failed to query the exit code of the worker process"; exit_code = CONTROL_C_EXIT; } } // Stop trying to restart the worker process if it exited due to // misconfiguration. return (kMinPermanentErrorExitCode <= exit_code && exit_code <= kMaxPermanentErrorExitCode); }
171,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static JSON_INLINE size_t num_buckets(hashtable_t *hashtable) { return primes[hashtable->num_buckets]; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
static JSON_INLINE size_t num_buckets(hashtable_t *hashtable)
166,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const { USHORT Res; auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset), GetDataLength(), __FUNCTION__); if (ppr.ipStatus != ppresNotIP) { Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize); } else { DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__)); Res = 0; } return Res; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <yhindin@rehat.com> CWE ID: CWE-20
USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const { USHORT Res; auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset), GetDataLength(), FALSE, __FUNCTION__); if (ppr.ipStatus != ppresNotIP) { Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize); } else { DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__)); Res = 0; } return Res; }
170,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PromoResourceService::ScheduleNotification(double promo_start, double promo_end) { if (promo_start > 0 && promo_end > 0) { const int64 ms_until_start = static_cast<int64>((base::Time::FromDoubleT( promo_start) - base::Time::Now()).InMilliseconds()); const int64 ms_until_end = static_cast<int64>((base::Time::FromDoubleT( promo_end) - base::Time::Now()).InMilliseconds()); if (ms_until_start > 0) { PostNotification(ms_until_start); } else if (ms_until_end > 0) { if (ms_until_start <= 0) { PostNotification(0); } PostNotification(ms_until_end); } } } Commit Message: Refresh promo notifications as they're fetched The "guard" existed for notification scheduling was preventing "turn-off a promo" and "update a promo" scenarios. Yet I do not believe it was adding any actual safety: if things on a server backend go wrong, the clients will be affected one way or the other, and it is better to have an option to shut the malformed promo down "as quickly as possible" (~in 12-24 hours). BUG= TEST= Review URL: https://chromiumcodereview.appspot.com/10696204 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void PromoResourceService::ScheduleNotification(double promo_start, double promo_end) { if (promo_start > 0 && promo_end > 0) { const int64 ms_until_start = static_cast<int64>((base::Time::FromDoubleT( promo_start) - base::Time::Now()).InMilliseconds()); const int64 ms_until_end = static_cast<int64>((base::Time::FromDoubleT( promo_end) - base::Time::Now()).InMilliseconds()); if (ms_until_start > 0) { PostNotification(ms_until_start); } else if (ms_until_end > 0) { if (ms_until_start <= 0) { // The promo is active. Notify immediately. PostNotification(0); } PostNotification(ms_until_end); } else { // The promo (if any) has finished. Notify immediately. PostNotification(0); } } else { // The promo (if any) was apparently cancelled. Notify immediately. PostNotification(0); } }
170,784
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DiscardAndExplicitlyReloadTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); background_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false)); tab_strip_model_->GetWebContentsAt(0)->GetController().Reload( content::ReloadType::NORMAL, false); testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DiscardAndExplicitlyReloadTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); background_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false)); tab_strip_model_->GetWebContentsAt(0)->GetController().Reload( content::ReloadType::NORMAL, false); ::testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); }
172,225
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ChromeMockRenderThread::OnGetDefaultPrintSettings( PrintMsg_Print_Params* params) { if (printer_.get()) printer_->GetDefaultPrintSettings(params); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnGetDefaultPrintSettings( PrintMsg_Print_Params* params) { printer_->GetDefaultPrintSettings(params); }
170,851
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: TestFeaturesNativeHandler::TestFeaturesNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("GetAPIFeatures", base::Bind(&TestFeaturesNativeHandler::GetAPIFeatures, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
TestFeaturesNativeHandler::TestFeaturesNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("GetAPIFeatures", "test", base::Bind(&TestFeaturesNativeHandler::GetAPIFeatures, base::Unretained(this))); }
172,254
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void exitErrorHandler(jpeg_common_struct *error) { j_decompress_ptr cinfo = (j_decompress_ptr)error; str_src_mgr * src = (struct str_src_mgr *)cinfo->src; src->abort = true; } Commit Message: CWE ID: CWE-20
static void exitErrorHandler(jpeg_common_struct *error) { j_decompress_ptr cinfo = (j_decompress_ptr)error; str_src_mgr * src = (struct str_src_mgr *)cinfo->src; longjmp(src->setjmp_buffer, 1); }
165,392
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool HeapAllocator::backingShrink(void* address, size_t quantizedCurrentSize, size_t quantizedShrunkSize) { if (!address || quantizedShrunkSize == quantizedCurrentSize) return true; ASSERT(quantizedShrunkSize < quantizedCurrentSize); ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return false; ASSERT(!state->isInGC()); ASSERT(state->isAllocationAllowed()); DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return false; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); ASSERT(header->checkHeader()); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); if (quantizedCurrentSize <= quantizedShrunkSize + sizeof(HeapObjectHeader) + sizeof(void*) * 32 && !arena->isObjectAllocatedAtAllocationPoint(header)) return true; bool succeededAtAllocationPoint = arena->shrinkObject(header, quantizedShrunkSize); if (succeededAtAllocationPoint) state->allocationPointAdjusted(arena->arenaIndex()); return true; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
bool HeapAllocator::backingShrink(void* address, size_t quantizedCurrentSize, size_t quantizedShrunkSize) { if (!address || quantizedShrunkSize == quantizedCurrentSize) return true; ASSERT(quantizedShrunkSize < quantizedCurrentSize); ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return false; ASSERT(!state->isInGC()); ASSERT(state->isAllocationAllowed()); DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return false; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); header->checkHeader(); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); if (quantizedCurrentSize <= quantizedShrunkSize + sizeof(HeapObjectHeader) + sizeof(void*) * 32 && !arena->isObjectAllocatedAtAllocationPoint(header)) return true; bool succeededAtAllocationPoint = arena->shrinkObject(header, quantizedShrunkSize); if (succeededAtAllocationPoint) state->allocationPointAdjusted(arena->arenaIndex()); return true; }
172,707
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void SetUp() { const tuple<int, int, VarianceFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; variance_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = new uint8_t[block_size_]; ref_ = new uint8_t[block_size_]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(ref_ != NULL); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { const tuple<int, int, VarianceFunctionType, int>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; variance_ = get<2>(params); if (get<3>(params)) { bit_depth_ = static_cast<vpx_bit_depth_t>(get<3>(params)); use_high_bit_depth_ = true; } else { bit_depth_ = VPX_BITS_8; use_high_bit_depth_ = false; } mask_ = (1 << bit_depth_) - 1; rnd_.Reset(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; if (!use_high_bit_depth_) { src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_ * 2)); ref_ = new uint8_t[block_size_ * 2]; #if CONFIG_VP9_HIGHBITDEPTH } else { src_ = CONVERT_TO_BYTEPTR(reinterpret_cast<uint16_t *>( vpx_memalign(16, block_size_ * 2 * sizeof(uint16_t)))); ref_ = CONVERT_TO_BYTEPTR(new uint16_t[block_size_ * 2]); #endif // CONFIG_VP9_HIGHBITDEPTH } ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(ref_ != NULL); }
174,589
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: char* _single_string_alloc_and_copy( LPCWSTR in ) { char *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( len + 1 ); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = 0xFF & in[ len ]; len ++; } chr[ len ++ ] = '\0'; return chr; } Commit Message: New Pre Source CWE ID: CWE-119
char* _single_string_alloc_and_copy( LPCWSTR in ) { char *chr; int len = 0; if ( !in ) { return NULL; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( len + 1 ); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = 0xFF & in[ len ]; len ++; } chr[ len ++ ] = '\0'; return chr; }
169,315
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MountLibrary* CrosLibrary::GetMountLibrary() { return mount_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
MountLibrary* CrosLibrary::GetMountLibrary() {
170,626
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == input_method::ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); }
170,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; } zval_add_ref(&object); return (zend_object_iterator*)iterator; } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; } zval_add_ref(&object); return (zend_object_iterator*)iterator; }
167,086
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bool ExecuteTranspose(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.GetEditor().Transpose(); return true; } Commit Message: Move Editor::Transpose() out of Editor class This patch moves |Editor::Transpose()| out of |Editor| class as preparation of expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor| class simpler for improving code health. Following patch will expand |Transpose()| into |ExecutTranspose()|. Bug: 672405 Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6 Reviewed-on: https://chromium-review.googlesource.com/583880 Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Cr-Commit-Position: refs/heads/master@{#489518} CWE ID:
static bool ExecuteTranspose(LocalFrame& frame, Event*, EditorCommandSource, const String&) { Transpose(frame); return true; }
172,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: zsetstrokecolor(i_ctx_t * i_ctx_p) { int code; code = zswapcolors(i_ctx_p); if (code < 0) /* Set up for the continuation procedure which will finish by restoring the fill colour space */ /* Make sure the exec stack has enough space */ check_estack(1); /* Now, the actual continuation routine */ push_op_estack(setstrokecolor_cont); code = zsetcolor(i_ctx_p); if (code >= 0) if (code >= 0) return o_push_estack; return code; } Commit Message: CWE ID: CWE-119
zsetstrokecolor(i_ctx_t * i_ctx_p) { int code; es_ptr iesp = esp; /* preserve exec stack in case of error */ code = zswapcolors(i_ctx_p); if (code < 0) /* Set up for the continuation procedure which will finish by restoring the fill colour space */ /* Make sure the exec stack has enough space */ check_estack(1); /* Now, the actual continuation routine */ push_op_estack(setstrokecolor_cont); code = zsetcolor(i_ctx_p); if (code >= 0) if (code >= 0) return o_push_estack; /* Something went wrong, swap back to the non-stroking colour and restore the exec stack */ esp = iesp; (void)zswapcolors(i_ctx_p); return code; }
164,699
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: DefragVlanQinQTest(void) { Packet *p1 = NULL, *p2 = NULL, *r = NULL; int ret = 0; DefragInit(); p1 = BuildTestPacket(1, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(1, 1, 0, 'B', 8); if (p2 == NULL) goto end; /* With no VLAN IDs set, packets should re-assemble. */ if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL) goto end; SCFree(r); /* With mismatched VLANs, packets should not re-assemble. */ p1->vlan_id[0] = 1; p2->vlan_id[0] = 1; p1->vlan_id[1] = 1; p2->vlan_id[1] = 2; if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL) goto end; /* Pass. */ ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragVlanQinQTest(void) { Packet *p1 = NULL, *p2 = NULL, *r = NULL; int ret = 0; DefragInit(); p1 = BuildTestPacket(IPPROTO_ICMP, 1, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(IPPROTO_ICMP, 1, 1, 0, 'B', 8); if (p2 == NULL) goto end; /* With no VLAN IDs set, packets should re-assemble. */ if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL) goto end; SCFree(r); /* With mismatched VLANs, packets should not re-assemble. */ p1->vlan_id[0] = 1; p2->vlan_id[0] = 1; p1->vlan_id[1] = 1; p2->vlan_id[1] = 2; if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL) goto end; /* Pass. */ ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); DefragDestroy(); return ret; }
168,305
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: size_t NormalPage::objectPayloadSizeForTesting() { size_t objectPayloadSize = 0; Address headerAddress = payload(); markAsSwept(); ASSERT(headerAddress != payloadEnd()); do { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); if (!header->isFree()) { ASSERT(header->checkHeader()); objectPayloadSize += header->payloadSize(); } ASSERT(header->size() < blinkPagePayloadSize()); headerAddress += header->size(); ASSERT(headerAddress <= payloadEnd()); } while (headerAddress < payloadEnd()); return objectPayloadSize; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
size_t NormalPage::objectPayloadSizeForTesting() { size_t objectPayloadSize = 0; Address headerAddress = payload(); markAsSwept(); ASSERT(headerAddress != payloadEnd()); do { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); if (!header->isFree()) { header->checkHeader(); objectPayloadSize += header->payloadSize(); } ASSERT(header->size() < blinkPagePayloadSize()); headerAddress += header->size(); ASSERT(headerAddress <= payloadEnd()); } while (headerAddress < payloadEnd()); return objectPayloadSize; }
172,713
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void SetUp() { source_stride_ = (width_ + 31) & ~31; reference_stride_ = width_ * 2; rnd_.Reset(ACMRandom::DeterministicSeed()); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { if (bd_ == -1) { use_high_bit_depth_ = false; bit_depth_ = VPX_BITS_8; source_data_ = source_data8_; reference_data_ = reference_data8_; second_pred_ = second_pred8_; #if CONFIG_VP9_HIGHBITDEPTH } else { use_high_bit_depth_ = true; bit_depth_ = static_cast<vpx_bit_depth_t>(bd_); source_data_ = CONVERT_TO_BYTEPTR(source_data16_); reference_data_ = CONVERT_TO_BYTEPTR(reference_data16_); second_pred_ = CONVERT_TO_BYTEPTR(second_pred16_); #endif // CONFIG_VP9_HIGHBITDEPTH } mask_ = (1 << bit_depth_) - 1; source_stride_ = (width_ + 31) & ~31; reference_stride_ = width_ * 2; rnd_.Reset(ACMRandom::DeterministicSeed()); }
174,577
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: LIBOPENMPT_MODPLUG_API unsigned int ModPlug_SampleName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_sample_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; } Commit Message: [Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team) git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-120
LIBOPENMPT_MODPLUG_API unsigned int ModPlug_SampleName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; char buf[32]; if(!file) return 0; str = openmpt_module_get_sample_name(file->mod,qual-1); memset(buf,0,32); if(str){ strncpy(buf,str,31); openmpt_free_string(str); } if(buff){ strncpy(buff,buf,32); } return (unsigned int)strlen(buf); }
169,501
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } }
167,046
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: set_hunkmax (void) { if (!p_line) p_line = (char **) malloc (hunkmax * sizeof *p_line); if (!p_len) p_len = (size_t *) malloc (hunkmax * sizeof *p_len); if (!p_Char) p_Char = malloc (hunkmax * sizeof *p_Char); } Commit Message: CWE ID: CWE-399
set_hunkmax (void) { if (!p_line) p_line = (char **) xmalloc (hunkmax * sizeof *p_line); if (!p_len) p_len = (size_t *) xmalloc (hunkmax * sizeof *p_len); if (!p_Char) p_Char = xmalloc (hunkmax * sizeof *p_Char); }
165,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); // Prevents the renderers from manipulating low-integrity processes. policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; }
170,912
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Cues::DoneParsing() const { const long long stop = m_start + m_size; return (m_pos >= stop); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Cues::DoneParsing() const
174,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name) { zval** ele_value = NULL; if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) { if(Z_TYPE_PP(ele_value)!= IS_STRING ){ /* element value is not a string */ return FAILURE; } if(strcmp(key_name, LOC_LANG_TAG) != 0 && strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) { /* not lang or grandfathered tag */ smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); } smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); return SUCCESS; } return LOC_NOT_FOUND; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name) { zval** ele_value = NULL; if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) { if(Z_TYPE_PP(ele_value)!= IS_STRING ){ /* element value is not a string */ return FAILURE; } if(strcmp(key_name, LOC_LANG_TAG) != 0 && strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) { /* not lang or grandfathered tag */ smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); } smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); return SUCCESS; } return LOC_NOT_FOUND; }
167,198
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1586 CWE ID: CWE-119
static PixelChannels **AcquirePixelThreadSet(const Image *image) static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); }
170,205
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ProxyChannelDelegate::ProxyChannelDelegate() : shutdown_event_(true, false) { } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
ProxyChannelDelegate::ProxyChannelDelegate()
170,737
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; _TIFFmemset(buf, 0, stripsize); for (s = 0; s < ns; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; } Commit Message: * tools/tiffcp.c: avoid uint32 underflow in cpDecodedStrips that can cause various issues, such as buffer overflows in the library. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2598 CWE ID: CWE-191
DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; _TIFFmemset(buf, 0, stripsize); for (s = 0; s < ns && row < imagelength; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; }
168,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode) { ASSERT(m_alreadyStarted); if (sourceCode.isEmpty()) return; RefPtr<Document> elementDocument(m_element->document()); RefPtr<Document> contextDocument = elementDocument->contextDocument().get(); if (!contextDocument) return; LocalFrame* frame = contextDocument->frame(); bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source()); if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber))) return; if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) { contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled."); return; } if (frame) { const bool isImportedScript = contextDocument != elementDocument; IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0); if (isHTMLScriptLoader(m_element)) contextDocument->pushCurrentScript(toHTMLScriptElement(m_element)); AccessControlStatus corsCheck = NotSharableCrossOrigin; if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin())) corsCheck = SharableCrossOrigin; frame->script().executeScriptInMainWorld(sourceCode, corsCheck); if (isHTMLScriptLoader(m_element)) { ASSERT(contextDocument->currentScript() == m_element); contextDocument->popCurrentScript(); } } } Commit Message: Apply 'x-content-type-options' check to dynamically inserted script. BUG=348581 Review URL: https://codereview.chromium.org/185593011 git-svn-id: svn://svn.chromium.org/blink/trunk@168570 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-362
void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode) { ASSERT(m_alreadyStarted); if (sourceCode.isEmpty()) return; RefPtr<Document> elementDocument(m_element->document()); RefPtr<Document> contextDocument = elementDocument->contextDocument().get(); if (!contextDocument) return; LocalFrame* frame = contextDocument->frame(); bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source()); if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber))) return; if (m_isExternalScript) { ScriptResource* resource = m_resource ? m_resource.get() : sourceCode.resource(); if (resource && !resource->mimeTypeAllowedByNosniff()) { contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + resource->url().elidedString() + "' because its MIME type ('" + resource->mimeType() + "') is not executable, and strict MIME type checking is enabled."); return; } } if (frame) { const bool isImportedScript = contextDocument != elementDocument; IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0); if (isHTMLScriptLoader(m_element)) contextDocument->pushCurrentScript(toHTMLScriptElement(m_element)); AccessControlStatus corsCheck = NotSharableCrossOrigin; if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin())) corsCheck = SharableCrossOrigin; frame->script().executeScriptInMainWorld(sourceCode, corsCheck); if (isHTMLScriptLoader(m_element)) { ASSERT(contextDocument->currentScript() == m_element); contextDocument->popCurrentScript(); } } }
171,408
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool CSPSourceList::matches(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const { if (m_allowStar) return true; KURL effectiveURL = m_policy->selfMatchesInnerURL() && SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url; if (m_allowSelf && m_policy->urlMatchesSelf(effectiveURL)) return true; for (size_t i = 0; i < m_list.size(); ++i) { if (m_list[i].matches(effectiveURL, redirectStatus)) return true; } return false; } Commit Message: Disallow CSP source * matching of data:, blob:, and filesystem: URLs The CSP spec specifically excludes matching of data:, blob:, and filesystem: URLs with the source '*' wildcard. This adds checks to make sure that doesn't happen, along with tests. BUG=534570 R=mkwst@chromium.org Review URL: https://codereview.chromium.org/1361763005 Cr-Commit-Position: refs/heads/master@{#350950} CWE ID: CWE-264
bool CSPSourceList::matches(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const { // The CSP spec specifically states that data:, blob:, and filesystem URLs // should not be captured by a '*" source // (http://www.w3.org/TR/CSP2/#source-list-guid-matching). Thus, in the // case of a full wildcard, data:, blob:, and filesystem: URLs are // explicitly checked for in the source list before allowing them through. if (m_allowStar) { if (url.protocolIs("blob") || url.protocolIs("data") || url.protocolIs("filesystem")) return hasSourceMatchInList(url, redirectStatus); return true; } KURL effectiveURL = m_policy->selfMatchesInnerURL() && SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url; if (m_allowSelf && m_policy->urlMatchesSelf(effectiveURL)) return true; return hasSourceMatchInList(effectiveURL, redirectStatus); }
171,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool IsSiteMuted(const TabStripModel& tab_strip, const int index) { content::WebContents* web_contents = tab_strip.GetWebContentsAt(index); GURL url = web_contents->GetLastCommittedURL(); if (url.SchemeIs(content::kChromeUIScheme)) { return web_contents->IsAudioMuted() && GetTabAudioMutedReason(web_contents) == TabMutedReason::CONTENT_SETTING_CHROME; } Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); return settings->GetContentSetting(url, url, CONTENT_SETTINGS_TYPE_SOUND, std::string()) == CONTENT_SETTING_BLOCK; } Commit Message: Fix nullptr crash in IsSiteMuted This CL adds a nullptr check in IsSiteMuted to prevent a crash on Mac. Bug: 797647 Change-Id: Ic36f0fb39f2dbdf49d2bec9e548a4a6e339dc9a2 Reviewed-on: https://chromium-review.googlesource.com/848245 Reviewed-by: Mounir Lamouri <mlamouri@chromium.org> Reviewed-by: Yuri Wiitala <miu@chromium.org> Commit-Queue: Tommy Steimel <steimel@chromium.org> Cr-Commit-Position: refs/heads/master@{#526825} CWE ID:
bool IsSiteMuted(const TabStripModel& tab_strip, const int index) { content::WebContents* web_contents = tab_strip.GetWebContentsAt(index); // TODO(steimel): Why was this not a problem for AreAllTabsMuted? Is this // going to be a problem for SetSitesMuted? // Prevent crashes with null WebContents (https://crbug.com/797647). if (!web_contents) return false; GURL url = web_contents->GetLastCommittedURL(); if (url.SchemeIs(content::kChromeUIScheme)) { return web_contents->IsAudioMuted() && GetTabAudioMutedReason(web_contents) == TabMutedReason::CONTENT_SETTING_CHROME; } Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); return settings->GetContentSetting(url, url, CONTENT_SETTINGS_TYPE_SOUND, std::string()) == CONTENT_SETTING_BLOCK; }
171,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string ExtensionTtsPlatformImpl::error() { return error_; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
std::string ExtensionTtsPlatformImpl::error() {
170,394
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof, char *errbuf) { size_t amt_read; amt_read = fread(buf, 1, bytes_to_read, fp); if (amt_read != bytes_to_read) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); } else { if (amt_read == 0 && !fail_on_eof) return (0); /* EOF */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "truncated dump file; tried to read %" PRIsize " bytes, only got %" PRIsize, bytes_to_read, amt_read); } return (-1); } return (1); } Commit Message: do sanity checks on PHB header length before allocating memory. There was no fault; but doing the check results in a more consistent error CWE ID: CWE-20
read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof, char *errbuf) { size_t amt_read; amt_read = fread(buf, 1, bytes_to_read, fp); if (amt_read != bytes_to_read) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); } else { if (amt_read == 0 && !fail_on_eof) return (0); /* EOF */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "truncated pcapng dump file; tried to read %" PRIsize " bytes, only got %" PRIsize, bytes_to_read, amt_read); } return (-1); } return (1); }
170,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) { bloc = *offset; while (node && node->symbol == INTERNAL_NODE) { if (get_bit(fin)) { node = node->right; } else { node = node->left; } } if (!node) { *ch = 0; return; } *ch = node->symbol; *offset = bloc; } Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left. CWE ID: CWE-119
void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) { void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset, int maxoffset) { bloc = *offset; while (node && node->symbol == INTERNAL_NODE) { if (bloc >= maxoffset) { *ch = 0; *offset = maxoffset + 1; return; } if (get_bit(fin)) { node = node->right; } else { node = node->left; } } if (!node) { *ch = 0; return; } *ch = node->symbol; *offset = bloc; }
167,994
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: StatisticsRecorderTest() : use_persistent_histogram_allocator_(GetParam()) { PersistentHistogramAllocator::GetCreateHistogramResultHistogram(); InitializeStatisticsRecorder(); if (use_persistent_histogram_allocator_) { GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0, "StatisticsRecorderTest"); } } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <bcwhite@chromium.org> Reviewed-by: Alexei Svitkine <asvitkine@chromium.org> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
StatisticsRecorderTest() : use_persistent_histogram_allocator_(GetParam()) { InitializeStatisticsRecorder(); if (use_persistent_histogram_allocator_) { GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0, "StatisticsRecorderTest"); } }
172,139
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcic; zval z_fname; zval * zresource_ptr = &intern->u.file.zresource, *retval; int result; int num_args = pass_num_args + (arg2 ? 2 : 1); zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); params[0] = &zresource_ptr; if (arg2) { params[1] = &arg2; } zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1)); ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object_ptr = NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = &retval; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; fcic.initialized = 1; fcic.function_handler = func_ptr; fcic.calling_scope = NULL; fcic.called_scope = NULL; fcic.object_ptr = NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); if (result == FAILURE) { RETVAL_FALSE; } else { ZVAL_ZVAL(return_value, retval, 1, 1); } efree(params); return result; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcic; zval z_fname; zval * zresource_ptr = &intern->u.file.zresource, *retval; int result; int num_args = pass_num_args + (arg2 ? 2 : 1); zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); params[0] = &zresource_ptr; if (arg2) { params[1] = &arg2; } zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1)); ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object_ptr = NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = &retval; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; fcic.initialized = 1; fcic.function_handler = func_ptr; fcic.calling_scope = NULL; fcic.called_scope = NULL; fcic.object_ptr = NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); if (result == FAILURE) { RETVAL_FALSE; } else { ZVAL_ZVAL(return_value, retval, 1, 1); } efree(params); return result; } /* }}} */
167,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void V8Window::namedPropertyGetterCustom(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) { if (!name->IsString()) return; auto nameString = name.As<v8::String>(); LocalDOMWindow* window = toLocalDOMWindow(V8Window::toImpl(info.Holder())); if (!window) return; LocalFrame* frame = window->frame(); if (!frame) return; AtomicString propName = toCoreAtomicString(nameString); Frame* child = frame->tree().scopedChild(propName); if (child) { v8SetReturnValueFast(info, child->domWindow(), window); return; } if (!info.Holder()->GetRealNamedProperty(nameString).IsEmpty()) return; Document* doc = frame->document(); if (doc && doc->isHTMLDocument()) { if (toHTMLDocument(doc)->hasNamedItem(propName) || doc->hasElementWithId(propName)) { RefPtrWillBeRawPtr<HTMLCollection> items = doc->windowNamedItems(propName); if (!items->isEmpty()) { if (items->hasExactlyOneItem()) { v8SetReturnValueFast(info, items->item(0), window); return; } v8SetReturnValueFast(info, items.release(), window); return; } } } } Commit Message: Reload frame in V8Window::namedPropertyGetterCustom after js call R=marja@chromium.org BUG=454954 Review URL: https://codereview.chromium.org/901053006 git-svn-id: svn://svn.chromium.org/blink/trunk@189574 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void V8Window::namedPropertyGetterCustom(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) { if (!name->IsString()) return; auto nameString = name.As<v8::String>(); LocalDOMWindow* window = toLocalDOMWindow(V8Window::toImpl(info.Holder())); if (!window) return; LocalFrame* frame = window->frame(); if (!frame) return; AtomicString propName = toCoreAtomicString(nameString); Frame* child = frame->tree().scopedChild(propName); if (child) { v8SetReturnValueFast(info, child->domWindow(), window); return; } if (!info.Holder()->GetRealNamedProperty(nameString).IsEmpty()) return; // Frame could have been detached in call to GetRealNamedProperty. frame = window->frame(); // window is detached. if (!frame) return; Document* doc = frame->document(); if (doc && doc->isHTMLDocument()) { if (toHTMLDocument(doc)->hasNamedItem(propName) || doc->hasElementWithId(propName)) { RefPtrWillBeRawPtr<HTMLCollection> items = doc->windowNamedItems(propName); if (!items->isEmpty()) { if (items->hasExactlyOneItem()) { v8SetReturnValueFast(info, items->item(0), window); return; } v8SetReturnValueFast(info, items.release(), window); return; } } } }
172,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method) { char q_user[SHORT_STRING], q_pass[SHORT_STRING]; char buf[STRING]; int rc; if (mutt_bit_isset(idata->capabilities, LOGINDISABLED)) { mutt_message(_("LOGIN disabled on this server.")); return IMAP_AUTH_UNAVAIL; } if (mutt_account_getuser(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; mutt_message(_("Logging in...")); imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user); imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass); /* don't print the password unless we're at the ungodly debugging level * of 5 or higher */ if (DebugLevel < IMAP_LOG_PASS) mutt_debug(2, "Sending LOGIN command for %s...\n", idata->conn->account.user); snprintf(buf, sizeof(buf), "LOGIN %s %s", q_user, q_pass); rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS); if (!rc) { mutt_clear_error(); /* clear "Logging in...". fixes #3524 */ return IMAP_AUTH_SUCCESS; } mutt_error(_("Login failed.")); return IMAP_AUTH_FAILURE; } Commit Message: quote imap strings more carefully Co-authored-by: JerikoOne <jeriko.one@gmx.us> CWE ID: CWE-77
enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method) { char q_user[SHORT_STRING], q_pass[SHORT_STRING]; char buf[STRING]; int rc; if (mutt_bit_isset(idata->capabilities, LOGINDISABLED)) { mutt_message(_("LOGIN disabled on this server.")); return IMAP_AUTH_UNAVAIL; } if (mutt_account_getuser(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; mutt_message(_("Logging in...")); imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user, false); imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass, false); /* don't print the password unless we're at the ungodly debugging level * of 5 or higher */ if (DebugLevel < IMAP_LOG_PASS) mutt_debug(2, "Sending LOGIN command for %s...\n", idata->conn->account.user); snprintf(buf, sizeof(buf), "LOGIN %s %s", q_user, q_pass); rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS); if (!rc) { mutt_clear_error(); /* clear "Logging in...". fixes #3524 */ return IMAP_AUTH_SUCCESS; } mutt_error(_("Login failed.")); return IMAP_AUTH_FAILURE; }
169,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ExtensionTtsSpeakFunction::RunImpl() { std::string text; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &text)); DictionaryValue* options = NULL; if (args_->GetSize() >= 2) EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &options)); Task* completion_task = NewRunnableMethod( this, &ExtensionTtsSpeakFunction::SpeechFinished); utterance_ = new Utterance(profile(), text, options, completion_task); AddRef(); // Balanced in SpeechFinished(). ExtensionTtsController::GetInstance()->SpeakOrEnqueue(utterance_); return true; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool ExtensionTtsSpeakFunction::RunImpl() { int src_id = -1; EXTENSION_FUNCTION_VALIDATE( options->GetInteger(constants::kSrcIdKey, &src_id)); // If we got this far, the arguments were all in the valid format, so // send the success response to the callback now - this ensures that // the callback response always arrives before events, which makes // the behavior more predictable and easier to write unit tests for too. SendResponse(true); UtteranceContinuousParameters continuous_params; continuous_params.rate = rate; continuous_params.pitch = pitch; continuous_params.volume = volume; Utterance* utterance = new Utterance(profile()); utterance->set_text(text); utterance->set_voice_name(voice_name); utterance->set_src_extension_id(extension_id()); utterance->set_src_id(src_id); utterance->set_src_url(source_url()); utterance->set_lang(lang); utterance->set_gender(gender); utterance->set_continuous_parameters(continuous_params); utterance->set_can_enqueue(can_enqueue); utterance->set_required_event_types(required_event_types); utterance->set_desired_event_types(desired_event_types); utterance->set_extension_id(voice_extension_id); utterance->set_options(options.get()); ExtensionTtsController* controller = ExtensionTtsController::GetInstance(); controller->SpeakOrEnqueue(utterance); return true; }
170,384
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); }
174,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void sync_lockstate_on_connect(btif_hh_device_t *p_dev) { int keylockstates; BTIF_TRACE_EVENT("%s: Syncing keyboard lock states after "\ "reconnect...",__FUNCTION__); /*If the device is connected, update keyboard state */ update_keyboard_lockstates(p_dev); /*Check if the lockstate of caps,scroll,num is set. If so, send a report to the kernel so the lockstate is in sync */ keylockstates = get_keylockstates(); if (keylockstates) { BTIF_TRACE_DEBUG("%s: Sending hid report to kernel "\ "indicating lock key state 0x%x",__FUNCTION__, keylockstates); usleep(200000); toggle_os_keylockstates(p_dev->fd, keylockstates); } else { BTIF_TRACE_DEBUG("%s: NOT sending hid report to kernel "\ "indicating lock key state 0x%x",__FUNCTION__, keylockstates); } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void sync_lockstate_on_connect(btif_hh_device_t *p_dev) { int keylockstates; BTIF_TRACE_EVENT("%s: Syncing keyboard lock states after "\ "reconnect...",__FUNCTION__); /*If the device is connected, update keyboard state */ update_keyboard_lockstates(p_dev); /*Check if the lockstate of caps,scroll,num is set. If so, send a report to the kernel so the lockstate is in sync */ keylockstates = get_keylockstates(); if (keylockstates) { BTIF_TRACE_DEBUG("%s: Sending hid report to kernel "\ "indicating lock key state 0x%x",__FUNCTION__, keylockstates); TEMP_FAILURE_RETRY(usleep(200000)); toggle_os_keylockstates(p_dev->fd, keylockstates); } else { BTIF_TRACE_DEBUG("%s: NOT sending hid report to kernel "\ "indicating lock key state 0x%x",__FUNCTION__, keylockstates); } }
173,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void scsi_write_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode != SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_write_complete(r, -EINVAL); return; } n = r->iov.iov_len / 512; if (n) { if (s->tray_open) { scsi_write_complete(r, -ENOMEDIUM); } qemu_iovec_init_external(&r->qiov, &r->iov, 1); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE); r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n, scsi_write_complete, r); if (r->req.aiocb == NULL) { scsi_write_complete(r, -ENOMEM); } } else { /* Invoke completion routine to fetch data from host. */ scsi_write_complete(r, 0); } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Kevin Wolf <kwolf@redhat.com> CWE ID: CWE-119
static void scsi_write_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode != SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_write_complete(r, -EINVAL); return; } n = r->qiov.size / 512; if (n) { if (s->tray_open) { scsi_write_complete(r, -ENOMEDIUM); } bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE); r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n, scsi_write_complete, r); if (r->req.aiocb == NULL) { scsi_write_complete(r, -ENOMEM); } } else { /* Called for the first time. Ask the driver to send us more data. */ scsi_write_complete(r, 0); } }
169,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmElementEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmElementEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) { free (ptr); return ret; } ut32 j = 0; while (i < len && j < ptr->num_elem ) { ut32 e; if (!(consume_u32 (buf + i, buf + len, &e, &i))) { free (ptr); return ret; } } r_list_append (ret, ptr); r += 1; } return ret; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125
static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmElementEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; int buflen = bin->buf->length - (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmElementEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { goto beach; } if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) { goto beach; } ut32 j = 0; while (i < len && j < ptr->num_elem) { ut32 e; if (!(consume_u32 (buf + i, buf + len, &e, &i))) { free (ptr); return ret; } } r_list_append (ret, ptr); r += 1; } return ret; beach: free (ptr); return ret; }
168,252
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHPAPI char *php_lookup_class_name(zval *object, zend_uint *nlen) { zval **val; char *retval = NULL; HashTable *object_properties; TSRMLS_FETCH(); object_properties = Z_OBJPROP_P(object); if (zend_hash_find(object_properties, MAGIC_MEMBER, sizeof(MAGIC_MEMBER), (void **) &val) == SUCCESS) { retval = estrndup(Z_STRVAL_PP(val), Z_STRLEN_PP(val)); if (nlen) { *nlen = Z_STRLEN_PP(val); } } return retval; } Commit Message: CWE ID:
PHPAPI char *php_lookup_class_name(zval *object, zend_uint *nlen) { zval **val; char *retval = NULL; HashTable *object_properties; TSRMLS_FETCH(); object_properties = Z_OBJPROP_P(object); if (zend_hash_find(object_properties, MAGIC_MEMBER, sizeof(MAGIC_MEMBER), (void **) &val) == SUCCESS && Z_TYPE_PP(val) == IS_STRING) { retval = estrndup(Z_STRVAL_PP(val), Z_STRLEN_PP(val)); if (nlen) { *nlen = Z_STRLEN_PP(val); } } return retval; }
165,303
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required) : field_types_(field_types), upload_required_(upload_required) { DCHECK(upload_required_); } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required, std::string* experiment_id) : field_types_(field_types), upload_required_(upload_required), experiment_id_(experiment_id) { DCHECK(upload_required_); DCHECK(experiment_id_); }
170,653
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfs4_state_set_mode_locked(struct nfs4_state *state, mode_t mode) { if (state->state == mode) return; /* NB! List reordering - see the reclaim code for why. */ if ((mode & FMODE_WRITE) != (state->state & FMODE_WRITE)) { if (mode & FMODE_WRITE) list_move(&state->open_states, &state->owner->so_states); else list_move_tail(&state->open_states, &state->owner->so_states); } state->state = mode; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
nfs4_state_set_mode_locked(struct nfs4_state *state, mode_t mode) nfs4_state_set_mode_locked(struct nfs4_state *state, fmode_t fmode) { if (state->state == fmode) return; /* NB! List reordering - see the reclaim code for why. */ if ((fmode & FMODE_WRITE) != (state->state & FMODE_WRITE)) { if (fmode & FMODE_WRITE) list_move(&state->open_states, &state->owner->so_states); else list_move_tail(&state->open_states, &state->owner->so_states); } state->state = fmode; }
165,712
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void DetectFlow(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { /* No need to perform any detection on this packet, if the the given flag is set.*/ if ((p->flags & PKT_NOPACKET_INSPECTION) || (PACKET_TEST_ACTION(p, ACTION_DROP))) { /* hack: if we are in pass the entire flow mode, we need to still * update the inspect_id forward. So test for the condition here, * and call the update code if necessary. */ const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION)); const AppProto alproto = FlowGetAppProtocol(p->flow); if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) { uint8_t flags; if (p->flowflags & FLOW_PKT_TOSERVER) { flags = STREAM_TOSERVER; } else { flags = STREAM_TOCLIENT; } flags = FlowGetDisruptionFlags(p->flow, flags); DeStateUpdateInspectTransactionId(p->flow, flags, true); } return; } /* see if the packet matches one or more of the sigs */ (void)DetectRun(tv, de_ctx, det_ctx, p); } Commit Message: stream: still inspect packets dropped by stream The detect engine would bypass packets that are set as dropped. This seems sane, as these packets are going to be dropped anyway. However, it lead to the following corner case: stream events that triggered the drop could not be matched on the rules. The packet with the event wouldn't make it to the detect engine due to the bypass. This patch changes the logic to not bypass DROP packets anymore. Packets that are dropped by the stream engine will set the no payload inspection flag, so avoid needless cost. CWE ID: CWE-693
static void DetectFlow(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { if (p->flags & PKT_NOPACKET_INSPECTION) { /* hack: if we are in pass the entire flow mode, we need to still * update the inspect_id forward. So test for the condition here, * and call the update code if necessary. */ const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION)); const AppProto alproto = FlowGetAppProtocol(p->flow); if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) { uint8_t flags; if (p->flowflags & FLOW_PKT_TOSERVER) { flags = STREAM_TOSERVER; } else { flags = STREAM_TOCLIENT; } flags = FlowGetDisruptionFlags(p->flow, flags); DeStateUpdateInspectTransactionId(p->flow, flags, true); } SCLogDebug("p->pcap %"PRIu64": no detection on packet, " "PKT_NOPACKET_INSPECTION is set", p->pcap_cnt); return; } /* see if the packet matches one or more of the sigs */ (void)DetectRun(tv, de_ctx, det_ctx, p); }
169,332
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SSLCertErrorHandler::SSLCertErrorHandler( base::WeakPtr<Delegate> delegate, const content::GlobalRequestID& id, ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id, const net::SSLInfo& ssl_info, bool fatal) : SSLErrorHandler(delegate, id, resource_type, url, render_process_id, render_view_id), ssl_info_(ssl_info), cert_error_(net::MapCertStatusToNetError(ssl_info.cert_status)), fatal_(fatal) { } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
SSLCertErrorHandler::SSLCertErrorHandler( const base::WeakPtr<Delegate>& delegate, const content::GlobalRequestID& id, ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id, const net::SSLInfo& ssl_info, bool fatal) : SSLErrorHandler(delegate, id, resource_type, url, render_process_id, render_view_id), ssl_info_(ssl_info), cert_error_(net::MapCertStatusToNetError(ssl_info.cert_status)), fatal_(fatal) { }
170,994
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool_t xdr_nullstring(XDR *xdrs, char **objp) { u_int size; if (xdrs->x_op == XDR_ENCODE) { if (*objp == NULL) size = 0; else size = strlen(*objp) + 1; } if (! xdr_u_int(xdrs, &size)) { return FALSE; } switch (xdrs->x_op) { case XDR_DECODE: if (size == 0) { *objp = NULL; return TRUE; } else if (*objp == NULL) { *objp = (char *) mem_alloc(size); if (*objp == NULL) { errno = ENOMEM; return FALSE; } } return (xdr_opaque(xdrs, *objp, size)); case XDR_ENCODE: if (size != 0) return (xdr_opaque(xdrs, *objp, size)); return TRUE; case XDR_FREE: if (*objp != NULL) mem_free(*objp, size); *objp = NULL; return TRUE; } return FALSE; } Commit Message: Verify decoded kadmin C strings [CVE-2015-8629] In xdr_nullstring(), check that the decoded string is terminated with a zero byte and does not contain any internal zero bytes. CVE-2015-8629: In all versions of MIT krb5, an authenticated attacker can cause kadmind to read beyond the end of allocated memory by sending a string without a terminating zero byte. Information leakage may be possible for an attacker with permission to modify the database. CVSSv2 Vector: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C ticket: 8341 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
bool_t xdr_nullstring(XDR *xdrs, char **objp) { u_int size; if (xdrs->x_op == XDR_ENCODE) { if (*objp == NULL) size = 0; else size = strlen(*objp) + 1; } if (! xdr_u_int(xdrs, &size)) { return FALSE; } switch (xdrs->x_op) { case XDR_DECODE: if (size == 0) { *objp = NULL; return TRUE; } else if (*objp == NULL) { *objp = (char *) mem_alloc(size); if (*objp == NULL) { errno = ENOMEM; return FALSE; } } if (!xdr_opaque(xdrs, *objp, size)) return FALSE; /* Check that the unmarshalled bytes are a C string. */ if ((*objp)[size - 1] != '\0') return FALSE; if (memchr(*objp, '\0', size - 1) != NULL) return FALSE; return TRUE; case XDR_ENCODE: if (size != 0) return (xdr_opaque(xdrs, *objp, size)); return TRUE; case XDR_FREE: if (*objp != NULL) mem_free(*objp, size); *objp = NULL; return TRUE; } return FALSE; }
167,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } }
167,103
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current()
167,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static scoped_refptr<Extension> MakeSyncTestExtension( SyncTestExtensionType type, const GURL& update_url, const GURL& launch_url, Manifest::Location location, int num_plugins, const base::FilePath& extension_path, int creation_flags) { base::DictionaryValue source; source.SetString(keys::kName, "PossiblySyncableExtension"); source.SetString(keys::kVersion, "0.0.0.0"); if (type == APP) source.SetString(keys::kApp, "true"); if (type == THEME) source.Set(keys::kTheme, new base::DictionaryValue()); if (!update_url.is_empty()) { source.SetString(keys::kUpdateURL, update_url.spec()); } if (!launch_url.is_empty()) { source.SetString(keys::kLaunchWebURL, launch_url.spec()); } if (type != THEME) { source.SetBoolean(keys::kConvertedFromUserScript, type == USER_SCRIPT); base::ListValue* plugins = new base::ListValue(); for (int i = 0; i < num_plugins; ++i) { base::DictionaryValue* plugin = new base::DictionaryValue(); plugin->SetString(keys::kPluginsPath, std::string()); plugins->Set(i, plugin); } source.Set(keys::kPlugins, plugins); } std::string error; scoped_refptr<Extension> extension = Extension::Create( extension_path, location, source, creation_flags, &error); EXPECT_TRUE(extension.get()); EXPECT_EQ("", error); return extension; } Commit Message: Fix syncing of NPAPI plugins. This fix adds a check for |plugin| permission while syncing NPAPI plugins. BUG=252034 Review URL: https://chromiumcodereview.appspot.com/16816024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207830 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
static scoped_refptr<Extension> MakeSyncTestExtension( static scoped_refptr<Extension> MakeSyncTestExtensionWithPluginPermission( SyncTestExtensionType type, const GURL& update_url, const GURL& launch_url, Manifest::Location location, int num_plugins, const base::FilePath& extension_path, int creation_flags, bool has_plugin_permission) { base::DictionaryValue source; source.SetString(keys::kName, "PossiblySyncableExtension"); source.SetString(keys::kVersion, "0.0.0.0"); if (type == APP) source.SetString(keys::kApp, "true"); if (type == THEME) source.Set(keys::kTheme, new base::DictionaryValue()); if (!update_url.is_empty()) { source.SetString(keys::kUpdateURL, update_url.spec()); } if (!launch_url.is_empty()) { source.SetString(keys::kLaunchWebURL, launch_url.spec()); } if (type != THEME) { source.SetBoolean(keys::kConvertedFromUserScript, type == USER_SCRIPT); base::ListValue* plugins = new base::ListValue(); for (int i = 0; i < num_plugins; ++i) { base::DictionaryValue* plugin = new base::DictionaryValue(); plugin->SetString(keys::kPluginsPath, std::string()); plugins->Set(i, plugin); } source.Set(keys::kPlugins, plugins); } if (has_plugin_permission) { ListValue* plugins = new ListValue(); plugins->Set(0, new StringValue("plugin")); source.Set(keys::kPermissions, plugins); } std::string error; scoped_refptr<Extension> extension = Extension::Create( extension_path, location, source, creation_flags, &error); EXPECT_TRUE(extension.get()); EXPECT_EQ("", error); return extension; }
171,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: socket_t *socket_accept(const socket_t *socket) { assert(socket != NULL); int fd = accept(socket->fd, NULL, NULL); if (fd == INVALID_FD) { LOG_ERROR("%s unable to accept socket: %s", __func__, strerror(errno)); return NULL; } socket_t *ret = (socket_t *)osi_calloc(sizeof(socket_t)); if (!ret) { close(fd); LOG_ERROR("%s unable to allocate memory for socket.", __func__); return NULL; } ret->fd = fd; return ret; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
socket_t *socket_accept(const socket_t *socket) { assert(socket != NULL); int fd = TEMP_FAILURE_RETRY(accept(socket->fd, NULL, NULL)); if (fd == INVALID_FD) { LOG_ERROR("%s unable to accept socket: %s", __func__, strerror(errno)); return NULL; } socket_t *ret = (socket_t *)osi_calloc(sizeof(socket_t)); if (!ret) { close(fd); LOG_ERROR("%s unable to allocate memory for socket.", __func__); return NULL; } ret->fd = fd; return ret; }
173,484
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: raptor_rdfxml_parse_start(raptor_parser* rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rdfxml_parser* rdf_xml_parser; rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context; /* base URI required for RDF/XML */ if(!uri) return 1; /* Optionally normalize language to lowercase * http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE)); /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rdf_xml_parser->sax2, uri); /* Delete any existing id_set */ if(rdf_xml_parser->id_set) { raptor_free_id_set(rdf_xml_parser->id_set); rdf_xml_parser->id_set = NULL; } /* Create a new id_set if needed */ if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) { rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world); if(!rdf_xml_parser->id_set) return 1; } return 0; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_rdfxml_parse_start(raptor_parser* rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rdfxml_parser* rdf_xml_parser; rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context; /* base URI required for RDF/XML */ if(!uri) return 1; /* Optionally normalize language to lowercase * http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE)); /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rdf_xml_parser->sax2, uri); /* Delete any existing id_set */ if(rdf_xml_parser->id_set) { raptor_free_id_set(rdf_xml_parser->id_set); rdf_xml_parser->id_set = NULL; } /* Create a new id_set if needed */ if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) { rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world); if(!rdf_xml_parser->id_set) return 1; } return 0; }
165,660
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void LoadingStatsCollector::CleanupAbandonedStats() { base::TimeTicks time_now = base::TimeTicks::Now(); for (auto it = preconnect_stats_.begin(); it != preconnect_stats_.end();) { if (time_now - it->second->start_time > max_stats_age_) { ReportPreconnectAccuracy(*it->second, std::map<GURL, OriginRequestSummary>()); it = preconnect_stats_.erase(it); } else { ++it; } } } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void LoadingStatsCollector::CleanupAbandonedStats() { base::TimeTicks time_now = base::TimeTicks::Now(); for (auto it = preconnect_stats_.begin(); it != preconnect_stats_.end();) { if (time_now - it->second->start_time > max_stats_age_) { ReportPreconnectAccuracy(*it->second, {}); it = preconnect_stats_.erase(it); } else { ++it; } } }
172,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric) { NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config); guint32 mtu = nm_ip4_config_get_mtu (config); int i; g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (config != NULL, FALSE); /* Addresses */ nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric); /* Routes */ { int count = nm_ip4_config_get_num_routes (config); GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count); const NMPlatformIP4Route *route; gboolean success; for (i = 0; i < count; i++) { route = nm_ip4_config_get_route (config, i); /* Don't add the route if it's more specific than one of the subnets * the device already has an IP address on. */ if ( route->gateway == 0 && nm_ip4_config_destination_is_direct (config, route->network, route->plen)) continue; g_array_append_vals (routes, route, 1); } success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes); g_array_unref (routes); return FALSE; } /* MTU */ if (mtu && mtu != nm_platform_link_get_mtu (ifindex)) nm_platform_link_set_mtu (ifindex, mtu); return TRUE; } Commit Message: CWE ID: CWE-20
nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric) { NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config); int i; g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (config != NULL, FALSE); /* Addresses */ nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric); /* Routes */ { int count = nm_ip4_config_get_num_routes (config); GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count); const NMPlatformIP4Route *route; gboolean success; for (i = 0; i < count; i++) { route = nm_ip4_config_get_route (config, i); /* Don't add the route if it's more specific than one of the subnets * the device already has an IP address on. */ if ( route->gateway == 0 && nm_ip4_config_destination_is_direct (config, route->network, route->plen)) continue; g_array_append_vals (routes, route, 1); } success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes); g_array_unref (routes); return FALSE; } return TRUE; }
164,815