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: bool ChromeOSChangeInputMethod( InputMethodStatusConnection* connection, const char* name) { DCHECK(name); DLOG(INFO) << "ChangeInputMethod: " << name; g_return_val_if_fail(connection, false); return connection->ChangeInputMethod(name); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChromeOSChangeInputMethod(
170,521
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: unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int sad = 0; const uint8_t* const reference = GetReference(block_idx); for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { sad += abs(source_data_[h * source_stride_ + w] - reference[h * reference_stride_ + w]); } if (sad > max_sad) { break; } } return sad; } 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
unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int ReferenceSAD(int block_idx) { unsigned int sad = 0; const uint8_t *const reference8 = GetReference(block_idx); const uint8_t *const source8 = source_data_; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *const reference16 = CONVERT_TO_SHORTPTR(GetReference(block_idx)); const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { sad += abs(source8[h * source_stride_ + w] - reference8[h * reference_stride_ + w]); #if CONFIG_VP9_HIGHBITDEPTH } else { sad += abs(source16[h * source_stride_ + w] - reference16[h * reference_stride_ + w]); #endif // CONFIG_VP9_HIGHBITDEPTH } } } return sad; }
174,574
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 js_Ast *memberexp(js_State *J) { js_Ast *a; INCREC(); a = newexp(J); loop: if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } DECREC(); return a; } Commit Message: CWE ID: CWE-674
static js_Ast *memberexp(js_State *J) { js_Ast *a = newexp(J); SAVEREC(); loop: INCREC(); if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } POPREC(); return a; }
165,136
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: WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), get_named_pipe_client_pid_(NULL), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); }
171,555
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: status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; } Commit Message: Check effect command reply size in AudioFlinger Bug: 29251553 Change-Id: I1bcc1281f1f0542bb645f6358ce31631f2a8ffbf CWE ID: CWE-20
status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } if (cmdCode == EFFECT_CMD_GET_PARAM && (*replySize < sizeof(effect_param_t) || ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) { android_errorWriteLog(0x534e4554, "29251553"); return -EINVAL; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; }
173,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: void HeapObjectHeader::Finalize(Address object, size_t object_size) { HeapAllocHooks::FreeHookIfEnabled(object); const GCInfo* gc_info = ThreadHeap::GcInfo(GcInfoIndex()); if (gc_info->HasFinalizer()) gc_info->finalize_(object); ASAN_RETIRE_CONTAINER_ANNOTATION(object, object_size); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <mlippautz@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void HeapObjectHeader::Finalize(Address object, size_t object_size) { HeapAllocHooks::FreeHookIfEnabled(object); const GCInfo* gc_info = GCInfoTable::Get().GCInfoFromIndex(GcInfoIndex()); if (gc_info->HasFinalizer()) gc_info->finalize_(object); ASAN_RETIRE_CONTAINER_ANNOTATION(object, object_size); }
173,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: PHP_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); }
165,295
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: OMX_ERRORTYPE SoftVorbis::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.vorbis", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioVorbis: { const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams = (const OMX_AUDIO_PARAM_VORBISTYPE *)params; if (vorbisParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftVorbis::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_decoder.vorbis", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioVorbis: { const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams = (const OMX_AUDIO_PARAM_VORBISTYPE *)params; if (!isValidOMXParam(vorbisParams)) { return OMX_ErrorBadParameter; } if (vorbisParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,221
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 Cluster::GetEntryCount() const { return m_entries_count; } 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 Cluster::GetEntryCount() const
174,318
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: status_t OMXNodeInstance::sendCommand( OMX_COMMANDTYPE cmd, OMX_S32 param) { if (cmd == OMX_CommandStateSet) { mSailed = true; } const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && cmd == OMX_CommandStateSet) { if (param == OMX_StateIdle) { bufferSource->omxIdle(); } else if (param == OMX_StateLoaded) { bufferSource->omxLoaded(); setGraphicBufferSource(NULL); } } Mutex::Autolock autoLock(mLock); { Mutex::Autolock _l(mDebugLock); bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */); } const char *paramString = cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param); CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL); CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); return StatusFromOMXError(err); } Commit Message: IOMX: allow configuration after going to loaded state This was disallowed recently but we still use it as MediaCodcec.stop only goes to loaded state, and does not free component. Bug: 31450460 Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d (cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b) CWE ID: CWE-200
status_t OMXNodeInstance::sendCommand( OMX_COMMANDTYPE cmd, OMX_S32 param) { if (cmd == OMX_CommandStateSet) { // There are no configurations past first StateSet command. mSailed = true; } const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && cmd == OMX_CommandStateSet) { if (param == OMX_StateIdle) { bufferSource->omxIdle(); } else if (param == OMX_StateLoaded) { bufferSource->omxLoaded(); setGraphicBufferSource(NULL); } } Mutex::Autolock autoLock(mLock); { Mutex::Autolock _l(mDebugLock); bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */); } const char *paramString = cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param); CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL); CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); return StatusFromOMXError(err); }
173,380
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: videobuf_vm_close(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; struct videobuf_queue *q = map->q; int i; dprintk(2,"vm_close %p [count=%d,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count--; if (0 == map->count) { dprintk(1,"munmap %p q=%p\n",map,q); mutex_lock(&q->lock); for (i = 0; i < VIDEO_MAX_FRAME; i++) { if (NULL == q->bufs[i]) continue; if (q->bufs[i]->map != map) continue; q->ops->buf_release(q,q->bufs[i]); q->bufs[i]->map = NULL; q->bufs[i]->baddr = 0; } mutex_unlock(&q->lock); kfree(map); } return; } Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap This is pretty serious bug. map->count is never initialized after the call to kmalloc making the count start at some random trash value. The end result is leaking videobufs. Also, fix up the debug statements to print unsigned values. Pushed to http://ifup.org/hg/v4l-dvb too Signed-off-by: Brandon Philips <bphilips@suse.de> Signed-off-by: Mauro Carvalho Chehab <mchehab@infradead.org> CWE ID: CWE-119
videobuf_vm_close(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; struct videobuf_queue *q = map->q; int i; dprintk(2,"vm_close %p [count=%u,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count--; if (0 == map->count) { dprintk(1,"munmap %p q=%p\n",map,q); mutex_lock(&q->lock); for (i = 0; i < VIDEO_MAX_FRAME; i++) { if (NULL == q->bufs[i]) continue; if (q->bufs[i]->map != map) continue; q->ops->buf_release(q,q->bufs[i]); q->bufs[i]->map = NULL; q->bufs[i]->baddr = 0; } mutex_unlock(&q->lock); kfree(map); } return; }
168,918
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: gs_main_init1(gs_main_instance * minst) { if (minst->init_done < 1) { gs_dual_memory_t idmem; int code = ialloc_init(&idmem, minst->heap, minst->memory_clump_size, gs_have_level2()); if (code < 0) return code; code = gs_lib_init1((gs_memory_t *)idmem.space_system); if (code < 0) return code; alloc_save_init(&idmem); { gs_memory_t *mem = (gs_memory_t *)idmem.space_system; name_table *nt = names_init(minst->name_table_size, idmem.space_system); if (nt == 0) return_error(gs_error_VMerror); mem->gs_lib_ctx->gs_name_table = nt; code = gs_register_struct_root(mem, NULL, (void **)&mem->gs_lib_ctx->gs_name_table, "the_gs_name_table"); "the_gs_name_table"); if (code < 0) return code; } code = obj_init(&minst->i_ctx_p, &idmem); /* requires name_init */ if (code < 0) if (code < 0) return code; code = i_iodev_init(minst->i_ctx_p); if (code < 0) return code; minst->init_done = 1; } return 0; } Commit Message: CWE ID: CWE-20
gs_main_init1(gs_main_instance * minst) { if (minst->init_done < 1) { gs_dual_memory_t idmem; int code = ialloc_init(&idmem, minst->heap, minst->memory_clump_size, gs_have_level2()); if (code < 0) return code; code = gs_lib_init1((gs_memory_t *)idmem.space_system); if (code < 0) return code; alloc_save_init(&idmem); { gs_memory_t *mem = (gs_memory_t *)idmem.space_system; name_table *nt = names_init(minst->name_table_size, idmem.space_system); if (nt == 0) return_error(gs_error_VMerror); mem->gs_lib_ctx->gs_name_table = nt; code = gs_register_struct_root(mem, NULL, (void **)&mem->gs_lib_ctx->gs_name_table, "the_gs_name_table"); "the_gs_name_table"); if (code < 0) return code; mem->gs_lib_ctx->client_check_file_permission = z_check_file_permissions; } code = obj_init(&minst->i_ctx_p, &idmem); /* requires name_init */ if (code < 0) if (code < 0) return code; code = i_iodev_init(minst->i_ctx_p); if (code < 0) return code; minst->init_done = 1; } return 0; }
165,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: void RenderWidgetHostViewAura::AdjustSurfaceProtection() { bool surface_is_protected = current_surface_ || !host_->is_hidden() || (current_surface_is_protected_ && (pending_thumbnail_tasks_ > 0 || current_surface_in_use_by_compositor_)); if (current_surface_is_protected_ == surface_is_protected) return; current_surface_is_protected_ = surface_is_protected; ++protection_state_id_; if (!surface_route_id_ || !shared_surface_handle_.parent_gpu_process_id) return; RenderWidgetHostImpl::SendFrontSurfaceIsProtected( surface_is_protected, protection_state_id_, surface_route_id_, shared_surface_handle_.parent_gpu_process_id); } 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 RenderWidgetHostViewAura::AdjustSurfaceProtection() { void RenderWidgetHostViewAura::SetSurfaceNotInUseByCompositor( scoped_refptr<ui::Texture>) { }
171,376
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 GetAppForProtocolUsingRegistry(const GURL& url) { base::string16 command_to_launch; base::string16 cmd_key_path = base::ASCIIToUTF16(url.scheme()); base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS && !command_to_launch.empty()) { return command_to_launch; } cmd_key_path = base::ASCIIToUTF16(url.scheme() + "\\shell\\open\\command"); base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); return command_line.GetProgram().BaseName().value(); } return base::string16(); } 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 GetAppForProtocolUsingRegistry(const GURL& url) { const base::string16 url_scheme = base::ASCIIToUTF16(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) return base::string16(); base::string16 command_to_launch; base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, url_scheme.c_str(), KEY_READ); if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS && !command_to_launch.empty()) { return command_to_launch; } const base::string16 cmd_key_path = url_scheme + L"\\shell\\open\\command"; base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); return command_line.GetProgram().BaseName().value(); } return base::string16(); }
172,636
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: mojom::AppPtr AppControllerImpl::CreateAppPtr(const apps::AppUpdate& update) { auto app = chromeos::kiosk_next_home::mojom::App::New(); app->app_id = update.AppId(); app->type = update.AppType(); app->display_name = update.Name(); app->readiness = update.Readiness(); if (app->type == apps::mojom::AppType::kArc) { app->android_package_name = MaybeGetAndroidPackageName(app->app_id); } return app; } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <michaelpg@chromium.org> Commit-Queue: Lucas Tenório <ltenorio@chromium.org> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
mojom::AppPtr AppControllerImpl::CreateAppPtr(const apps::AppUpdate& update) { mojom::AppPtr AppControllerService::CreateAppPtr( const apps::AppUpdate& update) { auto app = chromeos::kiosk_next_home::mojom::App::New(); app->app_id = update.AppId(); app->type = update.AppType(); app->display_name = update.Name(); app->readiness = update.Readiness(); if (app->type == apps::mojom::AppType::kArc) { app->android_package_name = MaybeGetAndroidPackageName(app->app_id); } return app; }
172,081
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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: PowerLibrary* CrosLibrary::GetPowerLibrary() { return power_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
PowerLibrary* CrosLibrary::GetPowerLibrary() {
170,628
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 rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *sigalg, ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey)) /* Carry on */ return 2; return -1; } Commit Message: CWE ID:
static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *sigalg, ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) { /* Carry on */ return 2; } return -1; }
164,820
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(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); }
167,043
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: safecat_color_encoding(char *buffer, size_t bufsize, size_t pos, PNG_CONST color_encoding *e, double encoding_gamma) { if (e != 0) { if (encoding_gamma != 0) pos = safecat(buffer, bufsize, pos, "("); pos = safecat(buffer, bufsize, pos, "R("); pos = safecatd(buffer, bufsize, pos, e->red.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->red.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->red.Z, 4); pos = safecat(buffer, bufsize, pos, "),G("); pos = safecatd(buffer, bufsize, pos, e->green.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->green.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->green.Z, 4); pos = safecat(buffer, bufsize, pos, "),B("); pos = safecatd(buffer, bufsize, pos, e->blue.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4); pos = safecat(buffer, bufsize, pos, ")"); if (encoding_gamma != 0) pos = safecat(buffer, bufsize, pos, ")"); } if (encoding_gamma != 0) { pos = safecat(buffer, bufsize, pos, "^"); pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5); } return pos; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
safecat_color_encoding(char *buffer, size_t bufsize, size_t pos, const color_encoding *e, double encoding_gamma) { if (e != 0) { if (encoding_gamma != 0) pos = safecat(buffer, bufsize, pos, "("); pos = safecat(buffer, bufsize, pos, "R("); pos = safecatd(buffer, bufsize, pos, e->red.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->red.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->red.Z, 4); pos = safecat(buffer, bufsize, pos, "),G("); pos = safecatd(buffer, bufsize, pos, e->green.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->green.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->green.Z, 4); pos = safecat(buffer, bufsize, pos, "),B("); pos = safecatd(buffer, bufsize, pos, e->blue.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4); pos = safecat(buffer, bufsize, pos, ")"); if (encoding_gamma != 0) pos = safecat(buffer, bufsize, pos, ")"); } if (encoding_gamma != 0) { pos = safecat(buffer, bufsize, pos, "^"); pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5); } return pos; }
173,690
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 qrio_prstcfg(u8 bit, u8 mode) { u32 prstcfg; u8 i; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; prstcfg = in_be32(qrio_base + PRSTCFG_OFF); for (i = 0; i < 2; i++) { if (mode & (1<<i)) set_bit(2*bit+i, &prstcfg); else clear_bit(2*bit+i, &prstcfg); } out_be32(qrio_base + PRSTCFG_OFF, prstcfg); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
void qrio_prstcfg(u8 bit, u8 mode) { u32 prstcfg; u8 i; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; prstcfg = in_be32(qrio_base + PRSTCFG_OFF); for (i = 0; i < 2; i++) { if (mode & (1 << i)) set_bit(2 * bit + i, &prstcfg); else clear_bit(2 * bit + i, &prstcfg); } out_be32(qrio_base + PRSTCFG_OFF, prstcfg); }
169,625
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 RemoveActionCallback(const ActionCallback& callback) { DCHECK(g_task_runner.Get()); DCHECK(g_task_runner.Get()->BelongsToCurrentThread()); std::vector<ActionCallback>* callbacks = g_callbacks.Pointer(); for (size_t i = 0; i < callbacks->size(); ++i) { if ((*callbacks)[i].Equals(callback)) { callbacks->erase(callbacks->begin() + i); return; } } } Commit Message: Convert Uses of base::RepeatingCallback<>::Equals to Use == or != in //base Staging this change because some conversions will have semantic changes. BUG=937566 Change-Id: I2d4950624c0fab00e107814421a161e43da965cc Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1507245 Reviewed-by: Gabriel Charette <gab@chromium.org> Commit-Queue: Gabriel Charette <gab@chromium.org> Cr-Commit-Position: refs/heads/master@{#639702} CWE ID: CWE-20
void RemoveActionCallback(const ActionCallback& callback) { DCHECK(g_task_runner.Get()); DCHECK(g_task_runner.Get()->BelongsToCurrentThread()); std::vector<ActionCallback>* callbacks = g_callbacks.Pointer(); for (size_t i = 0; i < callbacks->size(); ++i) { if ((*callbacks)[i] == callback) { callbacks->erase(callbacks->begin() + i); return; } } }
172,099
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: av_cold void ff_mpv_idct_init(MpegEncContext *s) { ff_idctdsp_init(&s->idsp, s->avctx); /* load & permutate scantables * note: only wmv uses different ones */ if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); } ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } Commit Message: avcodec/idctdsp: Transmit studio_profile to init instead of using AVCodecContext profile These 2 fields are not always the same, it is simpler to always use the same field for detecting studio profile Fixes: null pointer dereference Fixes: ffmpeg_crash_3.avi Found-by: Thuan Pham <thuanpv@comp.nus.edu.sg>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-476
av_cold void ff_mpv_idct_init(MpegEncContext *s) { if (s->codec_id == AV_CODEC_ID_MPEG4) s->idsp.mpeg4_studio_profile = s->studio_profile; ff_idctdsp_init(&s->idsp, s->avctx); /* load & permutate scantables * note: only wmv uses different ones */ if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); } ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); }
169,190
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 UserSelectionScreen::FillMultiProfileUserPrefs( user_manager::User* user, base::DictionaryValue* user_dict, bool is_signin_to_add) { if (!is_signin_to_add) { user_dict->SetBoolean(kKeyMultiProfilesAllowed, true); return; } bool is_user_allowed; ash::mojom::MultiProfileUserBehavior policy; GetMultiProfilePolicy(user, &is_user_allowed, &policy); user_dict->SetBoolean(kKeyMultiProfilesAllowed, is_user_allowed); user_dict->SetInteger(kKeyMultiProfilesPolicy, static_cast<int>(policy)); } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
void UserSelectionScreen::FillMultiProfileUserPrefs( const user_manager::User* user, base::DictionaryValue* user_dict, bool is_signin_to_add) { if (!is_signin_to_add) { user_dict->SetBoolean(kKeyMultiProfilesAllowed, true); return; } bool is_user_allowed; ash::mojom::MultiProfileUserBehavior policy; GetMultiProfilePolicy(user, &is_user_allowed, &policy); user_dict->SetBoolean(kKeyMultiProfilesAllowed, is_user_allowed); user_dict->SetInteger(kKeyMultiProfilesPolicy, static_cast<int>(policy)); }
172,199
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: status_t OMXNodeInstance::updateGraphicBufferInMeta( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id buffer) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); return updateGraphicBufferInMeta_l(portIndex, graphicBuffer, buffer, header); } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::updateGraphicBufferInMeta( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id buffer) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex); return updateGraphicBufferInMeta_l(portIndex, graphicBuffer, buffer, header); }
173,531
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: InputMethodStatusConnection() : current_input_method_changed_(NULL), register_ime_properties_(NULL), update_ime_property_(NULL), connection_change_handler_(NULL), language_library_(NULL), ibus_(NULL), ibus_config_(NULL) { } 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
InputMethodStatusConnection() // Functions that end with Thunk are used to deal with glib callbacks. // // Note that we cannot use CHROMEG_CALLBACK_0() here as we'll define // IBusBusConnected() inline. If we are to define the function outside // of the class definition, we should use CHROMEG_CALLBACK_0() here. // // CHROMEG_CALLBACK_0(Impl, // void, IBusBusConnected, IBusBus*); static void IBusBusConnectedThunk(IBusBus* sender, gpointer userdata) { return reinterpret_cast<IBusControllerImpl*>(userdata) ->IBusBusConnected(sender); } static void IBusBusDisconnectedThunk(IBusBus* sender, gpointer userdata) { return reinterpret_cast<IBusControllerImpl*>(userdata) ->IBusBusDisconnected(sender); } static void IBusBusGlobalEngineChangedThunk(IBusBus* sender, const gchar* engine_name, gpointer userdata) { return reinterpret_cast<IBusControllerImpl*>(userdata) ->IBusBusGlobalEngineChanged(sender, engine_name); } static void IBusBusNameOwnerChangedThunk(IBusBus* sender, const gchar* name, const gchar* old_name, const gchar* new_name, gpointer userdata) { return reinterpret_cast<IBusControllerImpl*>(userdata) ->IBusBusNameOwnerChanged(sender, name, old_name, new_name); } static void FocusInThunk(IBusPanelService* sender, const gchar* input_context_path, gpointer userdata) { return reinterpret_cast<IBusControllerImpl*>(userdata) ->FocusIn(sender, input_context_path); } static void RegisterPropertiesThunk(IBusPanelService* sender, IBusPropList* prop_list, gpointer userdata) { return reinterpret_cast<IBusControllerImpl*>(userdata) ->RegisterProperties(sender, prop_list); } static void UpdatePropertyThunk(IBusPanelService* sender, IBusProperty* ibus_prop, gpointer userdata) { return reinterpret_cast<IBusControllerImpl*>(userdata) ->UpdateProperty(sender, ibus_prop); } friend struct DefaultSingletonTraits<IBusControllerImpl>; IBusControllerImpl() : ibus_(NULL), ibus_config_(NULL) { }
170,540
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: build_config(char *prefix, struct server *server) { char *path = NULL; int path_size = strlen(prefix) + strlen(server->port) + 20; path = ss_malloc(path_size); snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port); FILE *f = fopen(path, "w+"); if (f == NULL) { if (verbose) { LOGE("unable to open config file"); } ss_free(path); return; } fprintf(f, "{\n"); fprintf(f, "\"server_port\":%d,\n", atoi(server->port)); fprintf(f, "\"password\":\"%s\"", server->password); if (server->fast_open[0]) fprintf(f, ",\n\"fast_open\": %s", server->fast_open); if (server->mode) fprintf(f, ",\n\"mode\":\"%s\"", server->mode); if (server->method) fprintf(f, ",\n\"method\":\"%s\"", server->method); if (server->plugin) fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin); if (server->plugin_opts) fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts); fprintf(f, "\n}\n"); fclose(f); ss_free(path); } Commit Message: Fix #1734 CWE ID: CWE-78
build_config(char *prefix, struct server *server) build_config(char *prefix, struct manager_ctx *manager, struct server *server) { char *path = NULL; int path_size = strlen(prefix) + strlen(server->port) + 20; path = ss_malloc(path_size); snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port); FILE *f = fopen(path, "w+"); if (f == NULL) { if (verbose) { LOGE("unable to open config file"); } ss_free(path); return; } fprintf(f, "{\n"); fprintf(f, "\"server_port\":%d,\n", atoi(server->port)); fprintf(f, "\"password\":\"%s\"", server->password); if (server->method) fprintf(f, ",\n\"method\":\"%s\"", server->method); else if (manager->method) fprintf(f, ",\n\"method\":\"%s\"", manager->method); if (server->fast_open[0]) fprintf(f, ",\n\"fast_open\": %s", server->fast_open); if (server->mode) fprintf(f, ",\n\"mode\":\"%s\"", server->mode); if (server->plugin) fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin); if (server->plugin_opts) fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts); fprintf(f, "\n}\n"); fclose(f); ss_free(path); }
167,713
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 DataReductionProxyConfig::InitializeOnIOThread( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, WarmupURLFetcher::CreateCustomProxyConfigCallback create_custom_proxy_config_callback, NetworkPropertiesManager* manager, const std::string& user_agent) { DCHECK(thread_checker_.CalledOnValidThread()); network_properties_manager_ = manager; network_properties_manager_->ResetWarmupURLFetchMetrics(); secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory)); warmup_url_fetcher_.reset(new WarmupURLFetcher( create_custom_proxy_config_callback, base::BindRepeating( &DataReductionProxyConfig::HandleWarmupFetcherResponse, base::Unretained(this)), base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate, base::Unretained(this)), ui_task_runner_, user_agent)); AddDefaultProxyBypassRules(); network_connection_tracker_->AddNetworkConnectionObserver(this); network_connection_tracker_->GetConnectionType( &connection_type_, base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged, weak_factory_.GetWeakPtr())); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
void DataReductionProxyConfig::InitializeOnIOThread( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, WarmupURLFetcher::CreateCustomProxyConfigCallback create_custom_proxy_config_callback, NetworkPropertiesManager* manager, const std::string& user_agent) { DCHECK(thread_checker_.CalledOnValidThread()); network_properties_manager_ = manager; network_properties_manager_->ResetWarmupURLFetchMetrics(); if (!params::IsIncludedInHoldbackFieldTrial()) { secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory)); warmup_url_fetcher_.reset(new WarmupURLFetcher( create_custom_proxy_config_callback, base::BindRepeating( &DataReductionProxyConfig::HandleWarmupFetcherResponse, base::Unretained(this)), base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate, base::Unretained(this)), ui_task_runner_, user_agent)); } AddDefaultProxyBypassRules(); network_connection_tracker_->AddNetworkConnectionObserver(this); network_connection_tracker_->GetConnectionType( &connection_type_, base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged, weak_factory_.GetWeakPtr())); }
172,416
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 InputConnectionImpl::CommitText(const base::string16& text, int new_cursor_pos) { StartStateUpdateTimer(); std::string error; if (!ime_engine_->ClearComposition(input_context_id_, &error)) LOG(ERROR) << "ClearComposition failed: error=\"" << error << "\""; if (IsControlChar(text)) { SendControlKeyEvent(text); return; } if (!ime_engine_->CommitText(input_context_id_, base::UTF16ToUTF8(text).c_str(), &error)) LOG(ERROR) << "CommitText failed: error=\"" << error << "\""; } Commit Message: Clear |composing_text_| after CommitText() is called. |composing_text_| of InputConnectionImpl should be cleared after CommitText() is called. Otherwise, FinishComposingText() will commit the same text twice. Bug: 899736 Test: unit_tests Change-Id: Idb22d968ffe95d946789fbe62454e8e79cb0b384 Reviewed-on: https://chromium-review.googlesource.com/c/1304773 Commit-Queue: Yusuke Sato <yusukes@chromium.org> Reviewed-by: Yusuke Sato <yusukes@chromium.org> Cr-Commit-Position: refs/heads/master@{#603518} CWE ID: CWE-119
void InputConnectionImpl::CommitText(const base::string16& text, int new_cursor_pos) { StartStateUpdateTimer(); std::string error; if (!ime_engine_->ClearComposition(input_context_id_, &error)) LOG(ERROR) << "ClearComposition failed: error=\"" << error << "\""; if (IsControlChar(text)) { SendControlKeyEvent(text); return; } if (!ime_engine_->CommitText(input_context_id_, base::UTF16ToUTF8(text).c_str(), &error)) LOG(ERROR) << "CommitText failed: error=\"" << error << "\""; composing_text_.clear(); }
173,333
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: unsigned int subpel_avg_variance_ref(const uint8_t *ref, const uint8_t *src, const uint8_t *second_pred, int l2w, int l2h, int xoff, int yoff, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); int diff = ((r + second_pred[w * y + x] + 1) >> 1) - src[w * y + x]; se += diff; sse += diff * diff; } } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } 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
unsigned int subpel_avg_variance_ref(const uint8_t *ref,
174,594
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: struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) { struct lib_t *libs; int i; if (!bin->nlibs) return NULL; if (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t)))) return NULL; for (i = 0; i < bin->nlibs; i++) { strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH); libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0'; libs[i].last = 0; } libs[i].last = 1; return libs; } Commit Message: Fix null deref and uaf in mach0 parser CWE ID: CWE-416
struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) { struct lib_t *libs; int i; if (!bin->nlibs) { return NULL; } if (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t)))) { return NULL; } for (i = 0; i < bin->nlibs; i++) { strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH); libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0'; libs[i].last = 0; } libs[i].last = 1; return libs; }
168,234
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 uint8_t* GetReference(int block_idx) { return reference_data_ + block_idx * kDataBlockSize; } 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 uint8_t* GetReference(int block_idx) { virtual uint8_t *GetReference(int block_idx) { #if CONFIG_VP9_HIGHBITDEPTH if (use_high_bit_depth_) return CONVERT_TO_BYTEPTR(CONVERT_TO_SHORTPTR(reference_data_) + block_idx * kDataBlockSize); #endif // CONFIG_VP9_HIGHBITDEPTH return reference_data_ + block_idx * kDataBlockSize; }
174,573
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 *arm_coherent_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs) { pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel); void *memory; if (dma_alloc_from_coherent(dev, size, handle, &memory)) return memory; return __dma_alloc(dev, size, handle, gfp, prot, true, __builtin_return_address(0)); } Commit Message: ARM: dma-mapping: don't allow DMA mappings to be marked executable DMA mapping permissions were being derived from pgprot_kernel directly without using PAGE_KERNEL. This causes them to be marked with executable permission, which is not what we want. Fix this. Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk> CWE ID: CWE-264
static void *arm_coherent_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs) { pgprot_t prot = __get_dma_pgprot(attrs, PAGE_KERNEL); void *memory; if (dma_alloc_from_coherent(dev, size, handle, &memory)) return memory; return __dma_alloc(dev, size, handle, gfp, prot, true, __builtin_return_address(0)); }
167,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: pdf_load_xobject(fz_context *ctx, pdf_document *doc, pdf_obj *dict) { pdf_xobject *form; if ((form = pdf_find_item(ctx, pdf_drop_xobject_imp, dict)) != NULL) return form; form->iteration = 0; /* Store item immediately, to avoid possible recursion if objects refer back to this one */ pdf_store_item(ctx, dict, form, pdf_xobject_size(form)); form->obj = pdf_keep_obj(ctx, dict); return form; } Commit Message: CWE ID: CWE-20
pdf_load_xobject(fz_context *ctx, pdf_document *doc, pdf_obj *dict) { pdf_xobject *form; if (!pdf_is_stream(ctx, dict)) fz_throw(ctx, FZ_ERROR_SYNTAX, "XObject must be a stream"); if ((form = pdf_find_item(ctx, pdf_drop_xobject_imp, dict)) != NULL) return form; form->iteration = 0; /* Store item immediately, to avoid possible recursion if objects refer back to this one */ pdf_store_item(ctx, dict, form, pdf_xobject_size(form)); form->obj = pdf_keep_obj(ctx, dict); return form; }
164,582
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 UnprivilegedProcessDelegate::CreateConnectedIpcChannel( const std::string& channel_name, IPC::Listener* delegate, ScopedHandle* client_out, scoped_ptr<IPC::ChannelProxy>* server_out) { scoped_ptr<IPC::ChannelProxy> server; if (!CreateIpcChannel(channel_name, kDaemonIpcSecurityDescriptor, io_task_runner_, delegate, &server)) { return false; } std::string pipe_name(kChromePipeNamePrefix); pipe_name.append(channel_name); SECURITY_ATTRIBUTES security_attributes; security_attributes.nLength = sizeof(security_attributes); security_attributes.lpSecurityDescriptor = NULL; security_attributes.bInheritHandle = TRUE; ScopedHandle client; client.Set(CreateFile(UTF8ToUTF16(pipe_name).c_str(), GENERIC_READ | GENERIC_WRITE, 0, &security_attributes, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION | FILE_FLAG_OVERLAPPED, NULL)); if (!client.IsValid()) return false; *client_out = client.Pass(); *server_out = server.Pass(); return true; } 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
bool UnprivilegedProcessDelegate::CreateConnectedIpcChannel(
171,544
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: const CuePoint* Cues::GetNext(const CuePoint* pCurr) const { if (pCurr == NULL) return NULL; assert(pCurr->GetTimeCode() >= 0); assert(m_cue_points); assert(m_count >= 1); #if 0 const size_t count = m_count + m_preload_count; size_t index = pCurr->m_index; assert(index < count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); pNext->Load(m_pSegment->m_pReader); #else long index = pCurr->m_index; assert(index < m_count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= m_count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); assert(pNext->GetTimeCode() >= 0); #endif return pNext; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const CuePoint* Cues::GetNext(const CuePoint* pCurr) const assert(pCurr->GetTimeCode() >= 0); assert(m_cue_points); assert(m_count >= 1); #if 0 const size_t count = m_count + m_preload_count; size_t index = pCurr->m_index; assert(index < count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); pNext->Load(m_pSegment->m_pReader); #else long index = pCurr->m_index; assert(index < m_count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= m_count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); assert(pNext->GetTimeCode() >= 0); #endif return pNext; }
174,346
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 socket_accept(int fd, uint16_t port) { #ifdef WIN32 int addr_len; #else socklen_t addr_len; #endif int result; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); addr_len = sizeof(addr); result = accept(fd, (struct sockaddr*)&addr, &addr_len); return result; } Commit Message: common: [security fix] Make sure sockets only listen locally CWE ID: CWE-284
int socket_accept(int fd, uint16_t port) { #ifdef WIN32 int addr_len; #else socklen_t addr_len; #endif int result; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_port = htons(port); addr_len = sizeof(addr); result = accept(fd, (struct sockaddr*)&addr, &addr_len); return result; }
167,165
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 AudioOutputDevice::OnStreamCreated( base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle, int length) { DCHECK(message_loop()->BelongsToCurrentThread()); #if defined(OS_WIN) DCHECK(handle); DCHECK(socket_handle); #else DCHECK_GE(handle.fd, 0); DCHECK_GE(socket_handle, 0); #endif DCHECK(stream_id_); if (!audio_thread_.get()) return; DCHECK(audio_thread_->IsStopped()); audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback( audio_parameters_, input_channels_, handle, length, callback_)); audio_thread_->Start( audio_callback_.get(), socket_handle, "AudioOutputDevice"); is_started_ = true; if (play_on_start_) PlayOnIOThread(); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void AudioOutputDevice::OnStreamCreated( base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle, int length) { DCHECK(message_loop()->BelongsToCurrentThread()); #if defined(OS_WIN) DCHECK(handle); DCHECK(socket_handle); #else DCHECK_GE(handle.fd, 0); DCHECK_GE(socket_handle, 0); #endif DCHECK(stream_id_); DCHECK(audio_thread_.IsStopped()); audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback( audio_parameters_, input_channels_, handle, length, callback_)); audio_thread_.Start(audio_callback_.get(), socket_handle, "AudioOutputDevice"); is_started_ = true; if (play_on_start_) PlayOnIOThread(); }
170,705
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 SyncTest::TriggerSetSyncTabs() { ASSERT_TRUE(ServerSupportsErrorTriggering()); std::string path = "chromiumsync/synctabs"; ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path)); ASSERT_EQ("Sync Tabs", UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle())); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncTest::TriggerSetSyncTabs() {
170,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: void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) { if (len > outHeader->nAllocLen) { ALOGE("memset buffer too small: got %lu, expected %zu", outHeader->nAllocLen, len); android_errorWriteLog(0x534e4554, "29422022"); notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL); mSignalledError = true; return NULL; } return memset(outHeader->pBuffer, c, len); } Commit Message: Fix build Change-Id: I96a9c437eec53a285ac96794cc1ad0c8954b27e0 CWE ID: CWE-264
void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) { if (len > outHeader->nAllocLen) { ALOGE("memset buffer too small: got %lu, expected %zu", (unsigned long)outHeader->nAllocLen, len); android_errorWriteLog(0x534e4554, "29422022"); notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL); mSignalledError = true; return NULL; } return memset(outHeader->pBuffer, c, len); }
174,157
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: ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) { ut64 addr = 0LL; struct symbol_t *symbols; int i; if (!(symbols = MACH0_(get_symbols) (bin))) { return 0; } for (i = 0; !symbols[i].last; i++) { if (!strcmp (symbols[i].name, "_main")) { addr = symbols[i].addr; break; } } free (symbols); if (!addr && bin->main_cmd.cmd == LC_MAIN) { addr = bin->entry + bin->baddr; } if (!addr) { ut8 b[128]; ut64 entry = addr_to_offset(bin, bin->entry); if (entry > bin->size || entry + sizeof (b) > bin->size) return 0; i = r_buf_read_at (bin->b, entry, b, sizeof (b)); if (i < 1) { return 0; } for (i = 0; i < 64; i++) { if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) { int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24); return bin->entry + i + 5 + delta; } } } return addr; } Commit Message: Fix null deref and uaf in mach0 parser CWE ID: CWE-416
ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) { ut64 addr = 0LL; struct symbol_t *symbols; int i; if (!(symbols = MACH0_(get_symbols) (bin))) { return 0; } for (i = 0; !symbols[i].last; i++) { if (!strcmp (symbols[i].name, "_main")) { addr = symbols[i].addr; break; } } free (symbols); if (!addr && bin->main_cmd.cmd == LC_MAIN) { addr = bin->entry + bin->baddr; } if (!addr) { ut8 b[128]; ut64 entry = addr_to_offset(bin, bin->entry); if (entry > bin->size || entry + sizeof (b) > bin->size) { return 0; } i = r_buf_read_at (bin->b, entry, b, sizeof (b)); if (i < 1) { return 0; } for (i = 0; i < 64; i++) { if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) { int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24); return bin->entry + i + 5 + delta; } } } return addr; }
168,235
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 GestureProviderAura::OnTouchEvent(const TouchEvent& event) { last_touch_event_flags_ = event.flags(); bool pointer_id_is_active = false; for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) { if (event.touch_id() != pointer_state_.GetPointerId(i)) continue; pointer_id_is_active = true; break; } if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) { return false; } else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) { return false; } pointer_state_.OnTouch(event); bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_); pointer_state_.CleanupRemovedTouchPoints(event); return result; } Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool GestureProviderAura::OnTouchEvent(const TouchEvent& event) { bool pointer_id_is_active = false; for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) { if (event.touch_id() != pointer_state_.GetPointerId(i)) continue; pointer_id_is_active = true; break; } if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) { return false; } else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) { return false; } last_touch_event_flags_ = event.flags(); last_touch_event_latency_info_ = *event.latency(); pointer_state_.OnTouch(event); bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_); pointer_state_.CleanupRemovedTouchPoints(event); return result; }
171,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: void close_connection(h2o_http2_conn_t *conn) { conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING; if (conn->_write.buf_in_flight != NULL || h2o_timeout_is_linked(&conn->_write.timeout_entry)) { /* there is a pending write, let on_write_complete actually close the connection */ } else { close_connection_now(conn); } } Commit Message: h2: use after free on premature connection close #920 lib/http2/connection.c:on_read() calls parse_input(), which might free `conn`. It does so in particular if the connection preface isn't the expected one in expect_preface(). `conn` is then used after the free in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`. We fix this by adding a return value to close_connection that returns a negative value if `conn` has been free'd and can't be used anymore. Credits for finding the bug to Tim Newsham. CWE ID:
void close_connection(h2o_http2_conn_t *conn) int close_connection(h2o_http2_conn_t *conn) { conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING; if (conn->_write.buf_in_flight != NULL || h2o_timeout_is_linked(&conn->_write.timeout_entry)) { /* there is a pending write, let on_write_complete actually close the connection */ } else { close_connection_now(conn); return -1; } return 0; }
167,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: static dma_addr_t dma_map_xdr(struct svcxprt_rdma *xprt, struct xdr_buf *xdr, u32 xdr_off, size_t len, int dir) { struct page *page; dma_addr_t dma_addr; if (xdr_off < xdr->head[0].iov_len) { /* This offset is in the head */ xdr_off += (unsigned long)xdr->head[0].iov_base & ~PAGE_MASK; page = virt_to_page(xdr->head[0].iov_base); } else { xdr_off -= xdr->head[0].iov_len; if (xdr_off < xdr->page_len) { /* This offset is in the page list */ xdr_off += xdr->page_base; page = xdr->pages[xdr_off >> PAGE_SHIFT]; xdr_off &= ~PAGE_MASK; } else { /* This offset is in the tail */ xdr_off -= xdr->page_len; xdr_off += (unsigned long) xdr->tail[0].iov_base & ~PAGE_MASK; page = virt_to_page(xdr->tail[0].iov_base); } } dma_addr = ib_dma_map_page(xprt->sc_cm_id->device, page, xdr_off, min_t(size_t, PAGE_SIZE, len), dir); return dma_addr; } 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 dma_addr_t dma_map_xdr(struct svcxprt_rdma *xprt, /* The client provided a Write list in the Call message. Fill in * the segments in the first Write chunk in the Reply's transport * header with the number of bytes consumed in each segment. * Remaining chunks are returned unused. * * Assumptions: * - Client has provided only one Write chunk */ static void svc_rdma_xdr_encode_write_list(__be32 *rdma_resp, __be32 *wr_ch, unsigned int consumed) { unsigned int nsegs; __be32 *p, *q; /* RPC-over-RDMA V1 replies never have a Read list. */ p = rdma_resp + rpcrdma_fixed_maxsz + 1; q = wr_ch; while (*q != xdr_zero) { nsegs = xdr_encode_write_chunk(p, q, consumed); q += 2 + nsegs * rpcrdma_segment_maxsz; p += 2 + nsegs * rpcrdma_segment_maxsz; consumed = 0; } /* Terminate Write list */ *p++ = xdr_zero; /* Reply chunk discriminator; may be replaced later */ *p = xdr_zero; } /* The client provided a Reply chunk in the Call message. Fill in * the segments in the Reply chunk in the Reply message with the * number of bytes consumed in each segment. * * Assumptions: * - Reply can always fit in the provided Reply chunk */ static void svc_rdma_xdr_encode_reply_chunk(__be32 *rdma_resp, __be32 *rp_ch, unsigned int consumed) { __be32 *p; /* Find the Reply chunk in the Reply's xprt header. * RPC-over-RDMA V1 replies never have a Read list. */ p = rdma_resp + rpcrdma_fixed_maxsz + 1; /* Skip past Write list */ while (*p++ != xdr_zero) p += 1 + be32_to_cpup(p) * rpcrdma_segment_maxsz; xdr_encode_write_chunk(p, rp_ch, consumed); }
168,166
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: PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool( ResourceProvider* resource_provider, ContextProvider* context_provider, size_t num_threads, size_t max_transfer_buffer_usage_bytes) : RasterWorkerPool(resource_provider, context_provider, num_threads), shutdown_(false), scheduled_raster_task_count_(0), bytes_pending_upload_(0), max_bytes_pending_upload_(max_transfer_buffer_usage_bytes), has_performed_uploads_since_last_flush_(false), check_for_completed_raster_tasks_pending_(false), should_notify_client_if_no_tasks_are_pending_(false), should_notify_client_if_no_tasks_required_for_activation_are_pending_( false) { } Commit Message: cc: Simplify raster task completion notification logic (Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/) Previously the pixel buffer raster worker pool used a combination of polling and explicit notifications from the raster worker pool to decide when to tell the client about the completion of 1) all tasks or 2) the subset of tasks required for activation. This patch simplifies the logic by only triggering the notification based on the OnRasterTasksFinished and OnRasterTasksRequiredForActivationFinished calls from the worker pool. BUG=307841,331534 Review URL: https://codereview.chromium.org/99873007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool( ResourceProvider* resource_provider, ContextProvider* context_provider, size_t num_threads, size_t max_transfer_buffer_usage_bytes) : RasterWorkerPool(resource_provider, context_provider, num_threads), shutdown_(false), scheduled_raster_task_count_(0), bytes_pending_upload_(0), max_bytes_pending_upload_(max_transfer_buffer_usage_bytes), has_performed_uploads_since_last_flush_(false), check_for_completed_raster_tasks_pending_(false), should_notify_client_if_no_tasks_are_pending_(false), should_notify_client_if_no_tasks_required_for_activation_are_pending_( false), raster_finished_task_pending_(false), raster_required_for_activation_finished_task_pending_(false) { }
171,262
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 BrowserWindowGtk::TabDetachedAt(TabContents* contents, int index) { if (index == browser_->active_index()) { infobar_container_->ChangeTabContents(NULL); UpdateDevToolsForContents(NULL); } contents_container_->DetachTab(contents); } 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 BrowserWindowGtk::TabDetachedAt(TabContents* contents, int index) { void BrowserWindowGtk::TabDetachedAt(WebContents* contents, int index) { if (index == browser_->active_index()) { infobar_container_->ChangeTabContents(NULL); UpdateDevToolsForContents(NULL); } contents_container_->DetachTab(contents); }
171,513
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 command_timed_out(UNUSED_ATTR void *context) { pthread_mutex_lock(&commands_pending_response_lock); if (list_is_empty(commands_pending_response)) { LOG_ERROR("%s with no commands pending response", __func__); } else { waiting_command_t *wait_entry = list_front(commands_pending_response); pthread_mutex_unlock(&commands_pending_response_lock); LOG_ERROR("%s hci layer timeout waiting for response to a command. opcode: 0x%x", __func__, wait_entry->opcode); } LOG_ERROR("%s restarting the bluetooth process.", __func__); usleep(10000); kill(getpid(), SIGKILL); } 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 command_timed_out(UNUSED_ATTR void *context) { pthread_mutex_lock(&commands_pending_response_lock); if (list_is_empty(commands_pending_response)) { LOG_ERROR("%s with no commands pending response", __func__); } else { waiting_command_t *wait_entry = list_front(commands_pending_response); pthread_mutex_unlock(&commands_pending_response_lock); LOG_ERROR("%s hci layer timeout waiting for response to a command. opcode: 0x%x", __func__, wait_entry->opcode); } LOG_ERROR("%s restarting the bluetooth process.", __func__); TEMP_FAILURE_RETRY(usleep(10000)); kill(getpid(), SIGKILL); }
173,478
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 *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269
void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; // Don't load any DLLs that end with the pk3 extension if (COM_CompareExtension(name, ".pk3")) { Com_Printf("Rejecting DLL named \"%s\"", name); return NULL; } if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; }
170,090
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 AppShortcutManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSIONS_READY: { OnceOffCreateShortcuts(); break; } case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: { #if defined(OS_MACOSX) if (!apps::IsAppShimsEnabled()) break; #endif // defined(OS_MACOSX) const extensions::InstalledExtensionInfo* installed_info = content::Details<const extensions::InstalledExtensionInfo>(details) .ptr(); const Extension* extension = installed_info->extension; if (installed_info->is_update) { web_app::UpdateAllShortcuts( base::UTF8ToUTF16(installed_info->old_name), profile_, extension); } else if (ShouldCreateShortcutFor(profile_, extension)) { CreateShortcutsInApplicationsMenu(profile_, extension); } break; } case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: { const Extension* extension = content::Details<const Extension>( details).ptr(); web_app::DeleteAllShortcuts(profile_, extension); break; } default: NOTREACHED(); } } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AppShortcutManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSIONS_READY: { OnceOffCreateShortcuts(); break; } case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: { const extensions::InstalledExtensionInfo* installed_info = content::Details<const extensions::InstalledExtensionInfo>(details) .ptr(); const Extension* extension = installed_info->extension; if (installed_info->is_update) { web_app::UpdateAllShortcuts( base::UTF8ToUTF16(installed_info->old_name), profile_, extension); } else if (ShouldCreateShortcutFor(profile_, extension)) { CreateShortcutsInApplicationsMenu(profile_, extension); } break; } case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: { const Extension* extension = content::Details<const Extension>( details).ptr(); web_app::DeleteAllShortcuts(profile_, extension); break; } default: NOTREACHED(); } }
171,145
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 scoped_pixel_buffer_object::Init(CGLContextObj cgl_context, int size_in_bytes) { cgl_context_ = cgl_context; CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glGenBuffersARB(1, &pixel_buffer_object_); if (glGetError() == GL_NO_ERROR) { glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pixel_buffer_object_); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, size_in_bytes, NULL, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); if (glGetError() != GL_NO_ERROR) { Release(); } } else { cgl_context_ = NULL; pixel_buffer_object_ = 0; } return pixel_buffer_object_ != 0; } Commit Message: Workaround for bad driver issue with NVIDIA GeForce 7300 GT on Mac 10.5. BUG=87283 TEST=Run on a machine with NVIDIA GeForce 7300 GT on Mac 10.5 immediately after booting. Review URL: http://codereview.chromium.org/7373018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@92651 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool scoped_pixel_buffer_object::Init(CGLContextObj cgl_context, int size_in_bytes) { // The PBO path is only done on 10.6 (SnowLeopard) and above due to // a driver issue that was found on 10.5 // (specifically on a NVIDIA GeForce 7300 GT). // http://crbug.com/87283 if (base::mac::IsOSLeopardOrEarlier()) { return false; } cgl_context_ = cgl_context; CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glGenBuffersARB(1, &pixel_buffer_object_); if (glGetError() == GL_NO_ERROR) { glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pixel_buffer_object_); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, size_in_bytes, NULL, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); if (glGetError() != GL_NO_ERROR) { Release(); } } else { cgl_context_ = NULL; pixel_buffer_object_ = 0; } return pixel_buffer_object_ != 0; }
170,317
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 BluetoothDeviceChromeOS::DisplayPinCode( const dbus::ObjectPath& device_path, const std::string& pincode) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": DisplayPinCode: " << pincode; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_DISPLAY_PINCODE, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); pairing_delegate_->DisplayPinCode(this, pincode); pairing_delegate_used_ = true; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::DisplayPinCode(
171,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 const char *lua_authz_parse(cmd_parms *cmd, const char *require_line, const void **parsed_require_line) { const char *provider_name; lua_authz_provider_spec *spec; apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE, cmd->temp_pool); ap_assert(provider_name != NULL); spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING); ap_assert(spec != NULL); if (require_line && *require_line) { const char *arg; spec->args = apr_array_make(cmd->pool, 2, sizeof(const char *)); while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) { APR_ARRAY_PUSH(spec->args, const char *) = arg; } } *parsed_require_line = spec; return NULL; } Commit Message: Merge r1642499 from trunk: *) SECURITY: CVE-2014-8109 (cve.mitre.org) mod_lua: Fix handling of the Require line when a LuaAuthzProvider is used in multiple Require directives with different arguments. PR57204 [Edward Lu <Chaosed0 gmail.com>] Submitted By: Edward Lu Committed By: covener Submitted by: covener Reviewed/backported by: jim git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1642861 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-264
static const char *lua_authz_parse(cmd_parms *cmd, const char *require_line, const void **parsed_require_line) { const char *provider_name; lua_authz_provider_spec *spec; lua_authz_provider_func *func = apr_pcalloc(cmd->pool, sizeof(lua_authz_provider_func)); apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE, cmd->temp_pool); ap_assert(provider_name != NULL); spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING); ap_assert(spec != NULL); func->spec = spec; if (require_line && *require_line) { const char *arg; func->args = apr_array_make(cmd->pool, 2, sizeof(const char *)); while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) { APR_ARRAY_PUSH(func->args, const char *) = arg; } } *parsed_require_line = func; return NULL; }
166,251
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: ModuleExport size_t RegisterMPCImage(void) { MagickInfo *entry; entry=SetMagickInfo("CACHE"); entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); entry->seekable_stream=MagickTrue; entry->stealth=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("MPC"); entry->decoder=(DecodeImageHandler *) ReadMPCImage; entry->encoder=(EncodeImageHandler *) WriteMPCImage; entry->magick=(IsImageFormatHandler *) IsMPC; entry->description=ConstantString("Magick Persistent Cache image format"); entry->seekable_stream=MagickTrue; entry->module=ConstantString("MPC"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: ... CWE ID: CWE-20
ModuleExport size_t RegisterMPCImage(void) { MagickInfo *entry; entry=SetMagickInfo("CACHE"); entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); entry->stealth=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("MPC"); entry->decoder=(DecodeImageHandler *) ReadMPCImage; entry->encoder=(EncodeImageHandler *) WriteMPCImage; entry->magick=(IsImageFormatHandler *) IsMPC; entry->description=ConstantString("Magick Persistent Cache image format"); entry->seekable_stream=MagickTrue; entry->module=ConstantString("MPC"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
170,040
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 IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) { IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id()); DCHECK(!processing_event_queue_); if (state_ == FINISHED) return; UMA_HISTOGRAM_ENUMERATION("WebCore.IndexedDB.TransactionAbortReason", ExceptionCodeToUmaEnum(error.code()), UmaIDBExceptionExclusiveMaxValue); timeout_timer_.Stop(); state_ = FINISHED; should_process_queue_ = false; if (backing_store_transaction_begun_) transaction_->Rollback(); while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(); preemptive_task_queue_.clear(); pending_preemptive_events_ = 0; task_queue_.clear(); CloseOpenCursors(); transaction_->Reset(); database_->transaction_coordinator().DidFinishTransaction(this); #ifndef NDEBUG DCHECK(!database_->transaction_coordinator().IsActive(this)); #endif if (callbacks_.get()) callbacks_->OnAbort(*this, error); database_->TransactionFinished(this, false); connection_->RemoveTransaction(id_); } Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose Patch is as small as possible for merging. Bug: 842990 Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f Reviewed-on: https://chromium-review.googlesource.com/1062935 Commit-Queue: Daniel Murphy <dmurph@chromium.org> Commit-Queue: Victor Costan <pwnall@chromium.org> Reviewed-by: Victor Costan <pwnall@chromium.org> Cr-Commit-Position: refs/heads/master@{#559383} CWE ID:
void IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) { IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id()); DCHECK(!processing_event_queue_); if (state_ == FINISHED) return; UMA_HISTOGRAM_ENUMERATION("WebCore.IndexedDB.TransactionAbortReason", ExceptionCodeToUmaEnum(error.code()), UmaIDBExceptionExclusiveMaxValue); timeout_timer_.Stop(); state_ = FINISHED; should_process_queue_ = false; if (backing_store_transaction_begun_) transaction_->Rollback(); while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(); preemptive_task_queue_.clear(); pending_preemptive_events_ = 0; task_queue_.clear(); CloseOpenCursors(); transaction_->Reset(); database_->transaction_coordinator().DidFinishTransaction(this); #ifndef NDEBUG DCHECK(!database_->transaction_coordinator().IsActive(this)); #endif if (callbacks_.get()) callbacks_->OnAbort(*this, error); database_->TransactionFinished(this, false); // Note: During force-close situations, the connection can be destroyed during // the |IndexedDBDatabase::TransactionFinished| call if (connection_) connection_->RemoveTransaction(id_); }
173,219
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 mkvparser::ParseElementHeader(IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; // success } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long mkvparser::ParseElementHeader(IMkvReader* pReader, long long& pos, long ParseElementHeader(IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; long len; id = ReadID(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume id if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0 || len < 1 || len > 8) { // Invalid: Negative payload size, negative or 0 length integer, or integer // larger than 64 bits (libwebm cannot handle them). return E_FILE_FORMAT_INVALID; } // Avoid rolling over pos when very close to LONG_LONG_MAX. const unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; return 0; // success }
173,853
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 nbd_recv_coroutines_enter_all(NBDClientSession *s) { int i; for (i = 0; i < MAX_NBD_REQUESTS; i++) { qemu_coroutine_enter(s->recv_coroutine[i]); qemu_coroutine_enter(s->recv_coroutine[i]); } } Commit Message: CWE ID: CWE-20
static void nbd_recv_coroutines_enter_all(NBDClientSession *s) static void nbd_recv_coroutines_enter_all(BlockDriverState *bs) { NBDClientSession *s = nbd_get_client_session(bs); int i; for (i = 0; i < MAX_NBD_REQUESTS; i++) { qemu_coroutine_enter(s->recv_coroutine[i]); qemu_coroutine_enter(s->recv_coroutine[i]); } }
165,449
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 board_init_f_init_reserve(ulong base) { struct global_data *gd_ptr; /* * clear GD entirely and set it up. * Use gd_ptr, as gd may not be properly set yet. */ gd_ptr = (struct global_data *)base; /* zero the area */ memset(gd_ptr, '\0', sizeof(*gd)); /* set GD unless architecture did it already */ #if !defined(CONFIG_ARM) arch_setup_gd(gd_ptr); #endif if (CONFIG_IS_ENABLED(SYS_REPORT_STACK_F_USAGE)) board_init_f_init_stack_protection_addr(base); /* next alloc will be higher by one GD plus 16-byte alignment */ base += roundup(sizeof(struct global_data), 16); /* * record early malloc arena start. * Use gd as it is now properly set for all architectures. */ #if CONFIG_VAL(SYS_MALLOC_F_LEN) /* go down one 'early malloc arena' */ gd->malloc_base = base; /* next alloc will be higher by one 'early malloc arena' size */ base += CONFIG_VAL(SYS_MALLOC_F_LEN); #endif if (CONFIG_IS_ENABLED(SYS_REPORT_STACK_F_USAGE)) board_init_f_init_stack_protection(); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
void board_init_f_init_reserve(ulong base) { struct global_data *gd_ptr; /* * clear GD entirely and set it up. * Use gd_ptr, as gd may not be properly set yet. */ gd_ptr = (struct global_data *)base; /* zero the area */ memset(gd_ptr, '\0', sizeof(*gd)); /* set GD unless architecture did it already */ #if !defined(CONFIG_ARM) arch_setup_gd(gd_ptr); #endif if (CONFIG_IS_ENABLED(SYS_REPORT_STACK_F_USAGE)) board_init_f_init_stack_protection_addr(base); /* next alloc will be higher by one GD plus 16-byte alignment */ base += roundup(sizeof(struct global_data), 16); /* * record early malloc arena start. * Use gd as it is now properly set for all architectures. */ #if CONFIG_VAL(SYS_MALLOC_F_LEN) /* go down one 'early malloc arena' */ gd->malloc_base = base; #endif if (CONFIG_IS_ENABLED(SYS_REPORT_STACK_F_USAGE)) board_init_f_init_stack_protection(); }
169,639
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: WebGLRenderingContextBase::~WebGLRenderingContextBase() { destruction_in_progress_ = true; DestroyContext(); RestoreEvictedContext(this); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
WebGLRenderingContextBase::~WebGLRenderingContextBase() { destruction_in_progress_ = true; clearProgramCompletionQueries(); DestroyContext(); RestoreEvictedContext(this); }
172,538
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 ps_files_valid_key(const char *key) { size_t len; const char *p; char c; int ret = 1; for (p = key; (c = *p); p++) { /* valid characters are a..z,A..Z,0..9 */ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ',' || c == '-')) { ret = 0; break; } } len = p - key; /* Somewhat arbitrary length limit here, but should be way more than anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */ if (len == 0 || len > 128) { ret = 0; } return ret; } Commit Message: CWE ID: CWE-264
static int ps_files_valid_key(const char *key)
164,871
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: NodeIterator::~NodeIterator() { root()->document().detachNodeIterator(this); } Commit Message: Fix detached Attr nodes interaction with NodeIterator - Don't register NodeIterator to document when attaching to Attr node. -- NodeIterator is registered to its document to receive updateForNodeRemoval notifications. -- However it wouldn't make sense on Attr nodes, as they never have children. BUG=572537 Review URL: https://codereview.chromium.org/1577213003 Cr-Commit-Position: refs/heads/master@{#369687} CWE ID:
NodeIterator::~NodeIterator() { if (!root()->isAttributeNode()) root()->document().detachNodeIterator(this); }
172,143
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 GestureProviderAura::OnTouchEventAck(bool event_consumed) { DCHECK(pending_gestures_.empty()); DCHECK(!handling_event_); base::AutoReset<bool> handling_event(&handling_event_, true); filtered_gesture_provider_.OnTouchEventAck(event_consumed); } Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GestureProviderAura::OnTouchEventAck(bool event_consumed) { DCHECK(pending_gestures_.empty()); DCHECK(!handling_event_); base::AutoReset<bool> handling_event(&handling_event_, true); filtered_gesture_provider_.OnTouchEventAck(event_consumed); last_touch_event_latency_info_.Clear(); }
171,206
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: CastCastView::CastCastView(CastConfigDelegate* cast_config_delegate) : cast_config_delegate_(cast_config_delegate) { set_background(views::Background::CreateSolidBackground(kBackgroundColor)); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal, kTrayPopupPaddingHorizontal, 0, kTrayPopupPaddingBetweenItems)); icon_ = new FixedSizedImageView(0, kTrayPopupItemHeight); icon_->SetImage( bundle.GetImageNamed(IDR_AURA_UBER_TRAY_CAST_ENABLED).ToImageSkia()); AddChildView(icon_); label_container_ = new views::View; label_container_->SetLayoutManager( new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); title_ = new views::Label; title_->SetHorizontalAlignment(gfx::ALIGN_LEFT); title_->SetFontList(bundle.GetFontList(ui::ResourceBundle::BoldFont)); label_container_->AddChildView(title_); details_ = new views::Label; details_->SetHorizontalAlignment(gfx::ALIGN_LEFT); details_->SetMultiLine(false); details_->SetEnabledColor(kHeaderTextColorNormal); label_container_->AddChildView(details_); AddChildView(label_container_); base::string16 stop_button_text = ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_ASH_STATUS_TRAY_CAST_STOP); stop_button_ = new TrayPopupLabelButton(this, stop_button_text); AddChildView(stop_button_); UpdateLabel(); } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} CWE ID: CWE-79
CastCastView::CastCastView(CastConfigDelegate* cast_config_delegate) : cast_config_delegate_(cast_config_delegate) { set_background(views::Background::CreateSolidBackground(kBackgroundColor)); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal, kTrayPopupPaddingHorizontal, 0, kTrayPopupPaddingBetweenItems)); icon_ = new FixedSizedImageView(0, kTrayPopupItemHeight); icon_->SetImage( bundle.GetImageNamed(IDR_AURA_UBER_TRAY_CAST_ENABLED).ToImageSkia()); AddChildView(icon_); label_container_ = new views::View; label_container_->SetLayoutManager( new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); title_ = new views::Label; title_->SetHorizontalAlignment(gfx::ALIGN_LEFT); title_->SetFontList(bundle.GetFontList(ui::ResourceBundle::BoldFont)); title_->SetText( bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_CAST_UNKNOWN_CAST_TYPE)); label_container_->AddChildView(title_); details_ = new views::Label; details_->SetHorizontalAlignment(gfx::ALIGN_LEFT); details_->SetMultiLine(false); details_->SetEnabledColor(kHeaderTextColorNormal); details_->SetText( bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_CAST_UNKNOWN_RECEIVER)); label_container_->AddChildView(details_); AddChildView(label_container_); base::string16 stop_button_text = ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_ASH_STATUS_TRAY_CAST_STOP); stop_button_ = new TrayPopupLabelButton(this, stop_button_text); AddChildView(stop_button_); UpdateLabel(); }
171,624
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 plist_t parse_string_node(const char **bnode, uint64_t size) { plist_data_t data = plist_new_plist_data(); data->type = PLIST_STRING; data->strval = (char *) malloc(sizeof(char) * (size + 1)); memcpy(data->strval, *bnode, size); data->strval[size] = '\0'; data->length = strlen(data->strval); return node_create(NULL, data); } Commit Message: bplist: Make sure to bail out if malloc() fails in parse_string_node() Credit to Wang Junjie <zhunkibatu@gmail.com> (#93) CWE ID: CWE-119
static plist_t parse_string_node(const char **bnode, uint64_t size) { plist_data_t data = plist_new_plist_data(); data->type = PLIST_STRING; data->strval = (char *) malloc(sizeof(char) * (size + 1)); if (!data->strval) { plist_free_data(data); PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(char) * (size + 1)); return NULL; } memcpy(data->strval, *bnode, size); data->strval[size] = '\0'; data->length = strlen(data->strval); return node_create(NULL, data); }
168,335
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 asn1_write_GeneralString(struct asn1_data *data, const char *s) { asn1_push_tag(data, ASN1_GENERAL_STRING); asn1_write_LDAPString(data, s); asn1_pop_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_GeneralString(struct asn1_data *data, const char *s) { if (!asn1_push_tag(data, ASN1_GENERAL_STRING)) return false; if (!asn1_write_LDAPString(data, s)) return false; return asn1_pop_tag(data); }
164,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: void RenderFrameImpl::OnSelectPopupMenuItems( bool canceled, const std::vector<int>& selected_indices) { if (!external_popup_menu_) return; blink::WebScopedUserGesture gesture(frame_); external_popup_menu_->DidSelectItems(canceled, selected_indices); external_popup_menu_.reset(); } Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s) ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl. We need to reset external_popup_menu_ before calling it. Bug: 912211 Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc Reviewed-on: https://chromium-review.googlesource.com/c/1381325 Commit-Queue: Kent Tamura <tkent@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#618026} CWE ID: CWE-416
void RenderFrameImpl::OnSelectPopupMenuItems( bool canceled, const std::vector<int>& selected_indices) { if (!external_popup_menu_) return; blink::WebScopedUserGesture gesture(frame_); // We need to reset |external_popup_menu_| before calling DidSelectItems(), // which might delete |this|. // See ExternalPopupMenuRemoveTest.RemoveFrameOnChange std::unique_ptr<ExternalPopupMenu> popup; popup.swap(external_popup_menu_); popup->DidSelectItems(canceled, selected_indices); }
173,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 PrintWebViewHelper::OnPrintForPrintPreview( const base::DictionaryValue& job_settings) { if (prep_frame_view_) return; if (!render_view()->GetWebView()) return; blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); if (!main_frame) return; blink::WebDocument document = main_frame->document(); blink::WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } blink::WebLocalFrame* plugin_frame = pdf_element.document().frame(); blink::WebElement plugin_element = pdf_element; if (pdf_element.hasHTMLTagName("iframe")) { plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element); plugin_element = delegate_->GetPdfElement(plugin_frame); if (plugin_element.isNull()) { NOTREACHED(); return; } } base::AutoReset<bool> set_printing_flag(&print_for_preview_, true); if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } PrintMsg_Print_Params& print_params = print_pages_params_->params; print_params.printable_area = gfx::Rect(print_params.page_size); if (!RenderPagesForPrint(plugin_frame, plugin_element)) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintForPrintPreview( const base::DictionaryValue& job_settings) { CHECK_LE(ipc_nesting_level_, 1); if (prep_frame_view_) return; if (!render_view()->GetWebView()) return; blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); if (!main_frame) return; blink::WebDocument document = main_frame->document(); blink::WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } blink::WebLocalFrame* plugin_frame = pdf_element.document().frame(); blink::WebElement plugin_element = pdf_element; if (pdf_element.hasHTMLTagName("iframe")) { plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element); plugin_element = delegate_->GetPdfElement(plugin_frame); if (plugin_element.isNull()) { NOTREACHED(); return; } } base::AutoReset<bool> set_printing_flag(&print_for_preview_, true); if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } PrintMsg_Print_Params& print_params = print_pages_params_->params; print_params.printable_area = gfx::Rect(print_params.page_size); if (!RenderPagesForPrint(plugin_frame, plugin_element)) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } }
171,873
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) { char obj_txt[128]; int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); BIO_write(bio, obj_txt, len); BIO_write(bio, "\n", 1); return 1; } Commit Message: Fix OOB read in TS_OBJ_print_bio(). TS_OBJ_print_bio() misuses OBJ_txt2obj: it should print the result as a null terminated buffer. The length value returned is the total length the complete text reprsentation would need not the amount of data written. CVE-2016-2180 Thanks to Shi Lei for reporting this bug. Reviewed-by: Matt Caswell <matt@openssl.org> CWE ID: CWE-125
int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) { char obj_txt[128]; OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); BIO_printf(bio, "%s\n", obj_txt); return 1; }
167,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: void TestAppInstancesHelper(const std::string& app_name) { LOG(INFO) << "Start of test."; extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser()->profile()); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII(app_name))); const Extension* extension = GetSingleLoadedExtension(); GURL base_url = GetTestBaseURL(app_name); ui_test_utils::NavigateToURLWithDisposition( browser(), base_url.Resolve("path1/empty.html"), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); LOG(INFO) << "Nav 1."; EXPECT_TRUE(process_map->Contains( browser()->tab_strip_model()->GetWebContentsAt(1)-> GetRenderProcessHost()->GetID())); EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(1)->GetWebUI()); content::WindowedNotificationObserver tab_added_observer( chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); chrome::NewTab(browser()); tab_added_observer.Wait(); LOG(INFO) << "New tab."; ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html")); LOG(INFO) << "Nav 2."; EXPECT_TRUE(process_map->Contains( browser()->tab_strip_model()->GetWebContentsAt(2)-> GetRenderProcessHost()->GetID())); EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(2)->GetWebUI()); ASSERT_EQ(3, browser()->tab_strip_model()->count()); WebContents* tab1 = browser()->tab_strip_model()->GetWebContentsAt(1); WebContents* tab2 = browser()->tab_strip_model()->GetWebContentsAt(2); EXPECT_NE(tab1->GetRenderProcessHost(), tab2->GetRenderProcessHost()); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); OpenWindow(tab1, base_url.Resolve("path1/empty.html"), true, NULL); LOG(INFO) << "WindowOpenHelper 1."; OpenWindow(tab2, base_url.Resolve("path2/empty.html"), true, NULL); LOG(INFO) << "End of test."; UnloadExtension(extension->id()); } Commit Message: [Extensions] Update navigations across hypothetical extension extents Update code to treat navigations across hypothetical extension extents (e.g. for nonexistent extensions) the same as we do for navigations crossing installed extension extents. Bug: 598265 Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b Reviewed-on: https://chromium-review.googlesource.com/617180 Commit-Queue: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Alex Moshchuk <alexmos@chromium.org> Reviewed-by: Nasko Oskov <nasko@chromium.org> Cr-Commit-Position: refs/heads/master@{#495779} CWE ID:
void TestAppInstancesHelper(const std::string& app_name) { LOG(INFO) << "Start of test."; extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser()->profile()); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII(app_name))); const Extension* extension = GetSingleLoadedExtension(); GURL base_url = GetTestBaseURL(app_name); ui_test_utils::NavigateToURLWithDisposition( browser(), base_url.Resolve("path1/empty.html"), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); LOG(INFO) << "Nav 1."; EXPECT_TRUE(process_map->Contains( browser()->tab_strip_model()->GetWebContentsAt(1)-> GetRenderProcessHost()->GetID())); EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(1)->GetWebUI()); content::WindowedNotificationObserver tab_added_observer( chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); chrome::NewTab(browser()); tab_added_observer.Wait(); LOG(INFO) << "New tab."; ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html")); LOG(INFO) << "Nav 2."; EXPECT_TRUE(process_map->Contains( browser()->tab_strip_model()->GetWebContentsAt(2)-> GetRenderProcessHost()->GetID())); EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(2)->GetWebUI()); ASSERT_EQ(3, browser()->tab_strip_model()->count()); WebContents* tab1 = browser()->tab_strip_model()->GetWebContentsAt(1); WebContents* tab2 = browser()->tab_strip_model()->GetWebContentsAt(2); EXPECT_NE(tab1->GetRenderProcessHost(), tab2->GetRenderProcessHost()); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); OpenWindow(tab1, base_url.Resolve("path1/empty.html"), true, true, NULL); LOG(INFO) << "WindowOpenHelper 1."; OpenWindow(tab2, base_url.Resolve("path2/empty.html"), true, true, NULL); LOG(INFO) << "End of test."; UnloadExtension(extension->id()); }
172,956
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 ForeignSessionHelper::SetInvalidationsForSessionsEnabled( JNIEnv* env, const JavaParamRef<jobject>& obj, jboolean enabled) { browser_sync::ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); if (!service) return; service->SetInvalidationsForSessionsEnabled(enabled); } Commit Message: Prefer SyncService over ProfileSyncService in foreign_session_helper SyncService is the interface, ProfileSyncService is the concrete implementation. Generally no clients should need to use the conrete implementation - for one, testing will be much easier once everyone uses the interface only. Bug: 924508 Change-Id: Ia210665f8f02512053d1a60d627dea0f22758387 Reviewed-on: https://chromium-review.googlesource.com/c/1461119 Auto-Submit: Marc Treib <treib@chromium.org> Commit-Queue: Yaron Friedman <yfriedman@chromium.org> Reviewed-by: Yaron Friedman <yfriedman@chromium.org> Cr-Commit-Position: refs/heads/master@{#630662} CWE ID: CWE-254
void ForeignSessionHelper::SetInvalidationsForSessionsEnabled( JNIEnv* env, const JavaParamRef<jobject>& obj, jboolean enabled) { syncer::SyncService* service = ProfileSyncServiceFactory::GetSyncServiceForProfile(profile_); if (!service) return; service->SetInvalidationsForSessionsEnabled(enabled); }
172,058
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: pkinit_check_kdc_pkid(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, unsigned char *pdid_buf, unsigned int pkid_len, int *valid_kdcPkId) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; PKCS7_ISSUER_AND_SERIAL *is = NULL; const unsigned char *p = pdid_buf; int status = 1; X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index); *valid_kdcPkId = 0; pkiDebug("found kdcPkId in AS REQ\n"); is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len); if (is == NULL) goto cleanup; status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer); if (!status) { status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial); if (!status) *valid_kdcPkId = 1; } retval = 0; cleanup: X509_NAME_free(is->issuer); ASN1_INTEGER_free(is->serial); free(is); return retval; } Commit Message: PKINIT null pointer deref [CVE-2013-1415] Don't dereference a null pointer when cleaning up. The KDC plugin for PKINIT can dereference a null pointer when a malformed packet causes processing to terminate early, leading to a crash of the KDC process. An attacker would need to have a valid PKINIT certificate or have observed a successful PKINIT authentication, or an unauthenticated attacker could execute the attack if anonymous PKINIT is enabled. CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:P/RL:O/RC:C This is a minimal commit for pullup; style fixes in a followup. [kaduk@mit.edu: reformat and edit commit message] (cherry picked from commit c773d3c775e9b2d88bcdff5f8a8ba88d7ec4e8ed) ticket: 7570 version_fixed: 1.11.1 status: resolved CWE ID:
pkinit_check_kdc_pkid(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, unsigned char *pdid_buf, unsigned int pkid_len, int *valid_kdcPkId) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; PKCS7_ISSUER_AND_SERIAL *is = NULL; const unsigned char *p = pdid_buf; int status = 1; X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index); *valid_kdcPkId = 0; pkiDebug("found kdcPkId in AS REQ\n"); is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len); if (is == NULL) return retval; status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer); if (!status) { status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial); if (!status) *valid_kdcPkId = 1; } retval = 0; X509_NAME_free(is->issuer); ASN1_INTEGER_free(is->serial); free(is); return retval; }
166,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: print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length) { int plenbytes; char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")]; if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 && is_ipv4_mapped_address(&prefix[1])) { struct in_addr addr; u_int plen; plen = prefix[0]-96; if (32 < plen) return -1; max_length -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN) return -3; memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen); plenbytes += 1 + IPV4_MAPPED_HEADING_LEN; } else { plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf)); } ND_PRINT((ndo, "%s", buf)); return plenbytes; } Commit Message: (for 4.9.3) CVE-2018-16228/HNCP: make buffer access safer print_prefix() has a buffer and does not initialize it. It may call decode_prefix6(), which also does not initialize the buffer on invalid input. When that happens, make sure to return from print_prefix() before trying to print the [still uninitialized] buffer. This fixes a buffer over-read discovered by Wang Junjie of 360 ESG Codesafe Team. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length) { int plenbytes; char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")]; if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 && is_ipv4_mapped_address(&prefix[1])) { struct in_addr addr; u_int plen; plen = prefix[0]-96; if (32 < plen) return -1; max_length -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN) return -3; memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen); plenbytes += 1 + IPV4_MAPPED_HEADING_LEN; } else { plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf)); if (plenbytes < 0) return plenbytes; } ND_PRINT((ndo, "%s", buf)); return plenbytes; }
169,820
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 addDataToStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().addDataToStream(blobRegistryContext->url, blobRegistryContext->streamData); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static void addDataToStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) { WebThreadSafeData webThreadSafeData(blobRegistryContext->streamData); registry->addDataToStream(blobRegistryContext->url, webThreadSafeData); } }
170,681
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 fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction) { FDrive *cur_drv = get_cur_drv(fdctrl); if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x80) { /* Command parameters done */ if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x40) { fdctrl->fifo[0] = fdctrl->fifo[1]; fdctrl->fifo[2] = 0; fdctrl->fifo[3] = 0; } } else if (fdctrl->data_len > 7) { /* ERROR */ fdctrl->fifo[0] = 0x80 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl); fdctrl_set_fifo(fdctrl, 1); } } Commit Message: CWE ID: CWE-119
static void fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction) { FDrive *cur_drv = get_cur_drv(fdctrl); uint32_t pos; pos = fdctrl->data_pos - 1; pos %= FD_SECTOR_LEN; if (fdctrl->fifo[pos] & 0x80) { /* Command parameters done */ if (fdctrl->fifo[pos] & 0x40) { fdctrl->fifo[0] = fdctrl->fifo[1]; fdctrl->fifo[2] = 0; fdctrl->fifo[3] = 0; } } else if (fdctrl->data_len > 7) { /* ERROR */ fdctrl->fifo[0] = 0x80 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl); fdctrl_set_fifo(fdctrl, 1); } }
164,706
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 PPB_URLLoader_Impl::RunCallback(int32_t result) { if (!pending_callback_.get()) { CHECK(main_document_loader_); return; } TrackedCallback::ClearAndRun(&pending_callback_, result); } Commit Message: Remove possibility of stale user_buffer_ member in PPB_URLLoader_Impl when FinishedLoading() is called. BUG=137778 Review URL: https://chromiumcodereview.appspot.com/10797037 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@147914 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void PPB_URLLoader_Impl::RunCallback(int32_t result) { if (!pending_callback_.get()) { CHECK(main_document_loader_); return; } // If |user_buffer_| was set as part of registering the callback, ensure // it got cleared since the callback is now free to delete it. DCHECK(!user_buffer_); TrackedCallback::ClearAndRun(&pending_callback_, result); }
170,901
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 PrintWebViewHelper::OnPrintForPrintPreview( const DictionaryValue& job_settings) { DCHECK(is_preview_); if (print_web_view_) return; if (!render_view()->webview()) return; WebFrame* main_frame = render_view()->webview()->mainFrame(); if (!main_frame) return; WebDocument document = main_frame->document(); WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } WebFrame* pdf_frame = pdf_element.document().frame(); scoped_ptr<PrepareFrameAndViewForPrint> prepare; if (!InitPrintSettingsAndPrepareFrame(pdf_frame, &pdf_element, &prepare)) { LOG(ERROR) << "Failed to initialize print page settings"; return; } if (!UpdatePrintSettings(job_settings, false)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } if (!RenderPagesForPrint(pdf_frame, &pdf_element, prepare.get())) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintWebViewHelper::OnPrintForPrintPreview( const DictionaryValue& job_settings) { DCHECK(is_preview_); if (print_web_view_) return; if (!render_view()->webview()) return; WebFrame* main_frame = render_view()->webview()->mainFrame(); if (!main_frame) return; WebDocument document = main_frame->document(); WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } if (!UpdatePrintSettings(job_settings, false)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } WebFrame* pdf_frame = pdf_element.document().frame(); scoped_ptr<PrepareFrameAndViewForPrint> prepare; prepare.reset(new PrepareFrameAndViewForPrint(print_pages_params_->params, pdf_frame, &pdf_element)); UpdatePrintableSizeInPrintParameters(pdf_frame, &pdf_element, prepare.get(), &print_pages_params_->params); if (!RenderPagesForPrint(pdf_frame, &pdf_element, prepare.get())) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } }
170,261
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 udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to) { struct pathComponent *pc; int elen = 0; unsigned char *p = to; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: p = to; *p++ = '/'; break; case 3: memcpy(p, "../", 3); p += 3; break; case 4: memcpy(p, "./", 2); p += 2; /* that would be . - just ignore */ break; case 5: p += udf_get_filename(sb, pc->componentIdent, p, pc->lengthComponentIdent); *p++ = '/'; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: stable@vger.kernel.org Reported-by: Carl Henrik Lunde <chlunde@ping.uio.no> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-17
static void udf_pc_to_char(struct super_block *sb, unsigned char *from, static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; return 0; }
166,757
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 ExtensionTtsPlatformImplChromeOs::IsSpeaking() { if (chromeos::CrosLibrary::Get()->EnsureLoaded()) { return chromeos::CrosLibrary::Get()->GetSpeechSynthesisLibrary()-> IsSpeaking(); } set_error(kCrosLibraryNotLoadedError); return false; } 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 ExtensionTtsPlatformImplChromeOs::IsSpeaking() { bool ExtensionTtsPlatformImplChromeOs::SendsEvent(TtsEventType event_type) { return (event_type == TTS_EVENT_START || event_type == TTS_EVENT_END || event_type == TTS_EVENT_ERROR); } void ExtensionTtsPlatformImplChromeOs::PollUntilSpeechFinishes( int utterance_id) { if (utterance_id != utterance_id_) { // This utterance must have been interrupted or cancelled. return; } chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get(); ExtensionTtsController* controller = ExtensionTtsController::GetInstance(); if (!cros_library->EnsureLoaded()) { controller->OnTtsEvent( utterance_id_, TTS_EVENT_ERROR, 0, kCrosLibraryNotLoadedError); return; } if (!cros_library->GetSpeechSynthesisLibrary()->IsSpeaking()) { controller->OnTtsEvent( utterance_id_, TTS_EVENT_END, utterance_length_, std::string()); return; } MessageLoop::current()->PostDelayedTask( FROM_HERE, method_factory_.NewRunnableMethod( &ExtensionTtsPlatformImplChromeOs::PollUntilSpeechFinishes, utterance_id), kSpeechCheckDelayIntervalMs); }
170,398
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: hash_foreach_mangle_dict_of_strings (gpointer key, gpointer val, gpointer user_data) { GHashTable *out = (GHashTable*) user_data; GHashTable *in_dict = (GHashTable *) val; HashAndString *data = g_new0 (HashAndString, 1); data->string = (gchar*) key; data->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); g_hash_table_foreach (in_dict, hash_foreach_prepend_string, data); g_hash_table_insert(out, g_strdup ((gchar*) key), data->hash); } Commit Message: CWE ID: CWE-264
hash_foreach_mangle_dict_of_strings (gpointer key, gpointer val, gpointer user_data)
165,085
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: QuicConnectionHelperTest() : framer_(QuicDecrypter::Create(kNULL), QuicEncrypter::Create(kNULL)), creator_(guid_, &framer_), net_log_(BoundNetLog()), scheduler_(new MockScheduler()), socket_(&empty_data_, net_log_.net_log()), runner_(new TestTaskRunner(&clock_)), helper_(new TestConnectionHelper(runner_.get(), &clock_, &socket_)), connection_(guid_, IPEndPoint(), helper_), frame1_(1, false, 0, data1) { connection_.set_visitor(&visitor_); connection_.SetScheduler(scheduler_); } Commit Message: Fix uninitialized access in QuicConnectionHelperTest BUG=159928 Review URL: https://chromiumcodereview.appspot.com/11360153 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@166708 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
QuicConnectionHelperTest() : guid_(0), framer_(QuicDecrypter::Create(kNULL), QuicEncrypter::Create(kNULL)), creator_(guid_, &framer_), net_log_(BoundNetLog()), scheduler_(new MockScheduler()), socket_(&empty_data_, net_log_.net_log()), runner_(new TestTaskRunner(&clock_)), helper_(new TestConnectionHelper(runner_.get(), &clock_, &socket_)), connection_(guid_, IPEndPoint(), helper_), frame1_(1, false, 0, data1) { connection_.set_visitor(&visitor_); connection_.SetScheduler(scheduler_); }
171,411
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 BackendImpl::OnEntryDestroyEnd() { DecreaseNumRefs(); if (data_->header.num_bytes > max_size_ && !read_only_ && (up_ticks_ > kTrimDelay || user_flags_ & kNoRandom)) eviction_.TrimCache(false); } Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <mmenke@chromium.org> Commit-Queue: Maks Orlovich <morlovich@chromium.org> Cr-Commit-Position: refs/heads/master@{#547103} CWE ID: CWE-20
void BackendImpl::OnEntryDestroyEnd() { DecreaseNumRefs(); consider_evicting_at_op_end_ = true; } void BackendImpl::OnSyncBackendOpComplete() { if (consider_evicting_at_op_end_) { if (data_->header.num_bytes > max_size_ && !read_only_ && (up_ticks_ > kTrimDelay || user_flags_ & kNoRandom)) eviction_.TrimCache(false); consider_evicting_at_op_end_ = false; } }
172,698
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, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "sr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "pr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); }
165,067
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: GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager, GpuWatchdog* watchdog, gfx::GLShareGroup* share_group, int client_id, bool software) : gpu_channel_manager_(gpu_channel_manager), client_id_(client_id), renderer_process_(base::kNullProcessHandle), renderer_pid_(base::kNullProcessId), share_group_(share_group ? share_group : new gfx::GLShareGroup), watchdog_(watchdog), software_(software), handle_messages_scheduled_(false), processed_get_state_fast_(false), num_contexts_preferring_discrete_gpu_(0), weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { DCHECK(gpu_channel_manager); DCHECK(client_id); channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu"); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); disallowed_features_.multisampling = command_line->HasSwitch(switches::kDisableGLMultisampling); disallowed_features_.driver_bug_workarounds = command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager, GpuWatchdog* watchdog, gfx::GLShareGroup* share_group, int client_id, bool software) : gpu_channel_manager_(gpu_channel_manager), client_id_(client_id), share_group_(share_group ? share_group : new gfx::GLShareGroup), watchdog_(watchdog), software_(software), handle_messages_scheduled_(false), processed_get_state_fast_(false), num_contexts_preferring_discrete_gpu_(0), weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { DCHECK(gpu_channel_manager); DCHECK(client_id); channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu"); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); disallowed_features_.multisampling = command_line->HasSwitch(switches::kDisableGLMultisampling); disallowed_features_.driver_bug_workarounds = command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds); }
170,931
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: main(void) { fprintf(stderr, "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n", PNG_ZLIB_VERNUM); return 77; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
main(void) { fprintf(stderr, "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n", ZLIB_VERNUM); return 77; }
173,734
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 CuePoint::GetTimeCode() const { return m_timecode; } 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 CuePoint::GetTimeCode() const long long CuePoint::GetTime(const Segment* pSegment) const { assert(pSegment); assert(m_timecode >= 0); const SegmentInfo* const pInfo = pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long time = scale * m_timecode; return time; }
174,367
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 SetupConnectedStreams() { CallbackRunLoop run_loop(runner()); ASSERT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished()); ASSERT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished()); client_peer_->CreateStreamWithDelegate(); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); base::RepeatingCallback<void()> callback = run_loop.CreateCallback(); QuicPeerForTest* server_peer_ptr = server_peer_.get(); MockP2PQuicStreamDelegate* stream_delegate = new MockP2PQuicStreamDelegate(); P2PQuicStream* server_stream; EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnStream(_)) .WillOnce(Invoke([&callback, &server_stream, &stream_delegate](P2PQuicStream* stream) { stream->SetDelegate(stream_delegate); server_stream = stream; callback.Run(); })); client_peer_->stream()->WriteOrBufferData(kTriggerRemoteStreamPhrase, /*fin=*/false, nullptr); run_loop.RunUntilCallbacksFired(); server_peer_ptr->SetStreamAndDelegate( static_cast<P2PQuicStreamImpl*>(server_stream), std::unique_ptr<MockP2PQuicStreamDelegate>(stream_delegate)); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <shampson@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void SetupConnectedStreams() { CallbackRunLoop run_loop(runner()); ASSERT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished()); ASSERT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished()); client_peer_->CreateStreamWithDelegate(); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); base::RepeatingCallback<void()> callback = run_loop.CreateCallback(); QuicPeerForTest* server_peer_ptr = server_peer_.get(); MockP2PQuicStreamDelegate* stream_delegate = new MockP2PQuicStreamDelegate(); P2PQuicStream* server_stream; EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnStream(_)) .WillOnce(Invoke([&callback, &server_stream, &stream_delegate](P2PQuicStream* stream) { stream->SetDelegate(stream_delegate); server_stream = stream; callback.Run(); })); client_peer_->stream()->WriteData( std::vector<uint8_t>(kTriggerRemoteStreamPhrase.begin(), kTriggerRemoteStreamPhrase.end()), /*fin=*/false); run_loop.RunUntilCallbacksFired(); server_peer_ptr->SetStreamAndDelegate( static_cast<P2PQuicStreamImpl*>(server_stream), std::unique_ptr<MockP2PQuicStreamDelegate>(stream_delegate)); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); }
172,268
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 tokenadd(struct jv_parser* p, char c) { assert(p->tokenpos <= p->tokenlen); if (p->tokenpos == p->tokenlen) { p->tokenlen = p->tokenlen*2 + 256; p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen); } assert(p->tokenpos < p->tokenlen); p->tokenbuf[p->tokenpos++] = c; } Commit Message: Heap buffer overflow in tokenadd() (fix #105) This was an off-by one: the NUL terminator byte was not allocated on resize. This was triggered by JSON-encoded numbers longer than 256 bytes. CWE ID: CWE-119
static void tokenadd(struct jv_parser* p, char c) { assert(p->tokenpos <= p->tokenlen); if (p->tokenpos >= (p->tokenlen - 1)) { p->tokenlen = p->tokenlen*2 + 256; p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen); } assert(p->tokenpos < p->tokenlen); p->tokenbuf[p->tokenpos++] = c; }
167,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 cJSON_InitHooks(cJSON_Hooks* hooks) { if ( ! hooks ) { /* Reset hooks. */ cJSON_malloc = malloc; cJSON_free = free; return; } cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc; cJSON_free = (hooks->free_fn) ? hooks->free_fn : free; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
void cJSON_InitHooks(cJSON_Hooks* hooks) static char* cJSON_strdup(const char* str) {
167,290
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 FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, Blob* blob) { m_urlForReading = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin()); if (m_urlForReading.isEmpty()) { failed(FileError::SECURITY_ERR); return; } ThreadableBlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), m_urlForReading, blob->url()); ResourceRequest request(m_urlForReading); request.setHTTPMethod("GET"); if (m_hasRange) request.setHTTPHeaderField("Range", String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd)); ThreadableLoaderOptions options; options.sendLoadCallbacks = SendCallbacks; options.sniffContent = DoNotSniffContent; options.preflightPolicy = ConsiderPreflight; options.allowCredentials = AllowStoredCredentials; options.crossOriginRequestPolicy = DenyCrossOriginRequests; options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy; if (m_client) m_loader = ThreadableLoader::create(scriptExecutionContext, this, request, options); else ThreadableLoader::loadResourceSynchronously(scriptExecutionContext, request, *this, options); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, Blob* blob) { m_urlForReading = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin()); if (m_urlForReading.isEmpty()) { failed(FileError::SECURITY_ERR); return; } BlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), m_urlForReading, blob->url()); ResourceRequest request(m_urlForReading); request.setHTTPMethod("GET"); if (m_hasRange) request.setHTTPHeaderField("Range", String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd)); ThreadableLoaderOptions options; options.sendLoadCallbacks = SendCallbacks; options.sniffContent = DoNotSniffContent; options.preflightPolicy = ConsiderPreflight; options.allowCredentials = AllowStoredCredentials; options.crossOriginRequestPolicy = DenyCrossOriginRequests; options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy; if (m_client) m_loader = ThreadableLoader::create(scriptExecutionContext, this, request, options); else ThreadableLoader::loadResourceSynchronously(scriptExecutionContext, request, *this, options); }
170,692
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 BrowserLauncherItemController::TabDetachedAt(TabContents* contents, int index) { launcher_controller()->UpdateAppState( contents->web_contents(), ChromeLauncherController::APP_STATE_REMOVED); } 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 BrowserLauncherItemController::TabDetachedAt(TabContents* contents, void BrowserLauncherItemController::TabDetachedAt( content::WebContents* contents, int index) { launcher_controller()->UpdateAppState( contents, ChromeLauncherController::APP_STATE_REMOVED); }
171,506
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 AcceleratedStaticBitmapImage::EnsureMailbox(MailboxSyncMode mode, GLenum filter) { if (!texture_holder_->IsMailboxTextureHolder()) { TRACE_EVENT0("blink", "AcceleratedStaticBitmapImage::EnsureMailbox"); if (!original_skia_image_) { RetainOriginalSkImage(); } texture_holder_ = std::make_unique<MailboxTextureHolder>( std::move(texture_holder_), filter); } texture_holder_->Sync(mode); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void AcceleratedStaticBitmapImage::EnsureMailbox(MailboxSyncMode mode, GLenum filter) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!texture_holder_->IsMailboxTextureHolder()) { TRACE_EVENT0("blink", "AcceleratedStaticBitmapImage::EnsureMailbox"); if (!original_skia_image_) { RetainOriginalSkImage(); } texture_holder_ = std::make_unique<MailboxTextureHolder>( std::move(texture_holder_), filter); } texture_holder_->Sync(mode); }
172,595
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 __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { unsigned long quirks = (unsigned long)hid_get_drvdata(hdev); unsigned int i; if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX)) return rdesc; for (i = 0; i < *rsize - 4; i++) if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) { rdesc[i] = 0x19; rdesc[i + 2] = 0x29; swap(rdesc[i + 3], rdesc[i + 1]); } return rdesc; } Commit Message: HID: hid-cypress: validate length of report Make sure we have enough of a report structure to validate before looking at it. Reported-by: Benoit Camredon <benoit.camredon@airbus.com> Tested-by: Benoit Camredon <benoit.camredon@airbus.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID:
static __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { unsigned long quirks = (unsigned long)hid_get_drvdata(hdev); unsigned int i; if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX)) return rdesc; if (*rsize < 4) return rdesc; for (i = 0; i < *rsize - 4; i++) if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) { rdesc[i] = 0x19; rdesc[i + 2] = 0x29; swap(rdesc[i + 3], rdesc[i + 1]); } return rdesc; }
168,288
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 AutofillManager::OnLoadedAutofillHeuristics( const std::string& heuristic_xml) { UploadRequired upload_required; FormStructure::ParseQueryResponse(heuristic_xml, form_structures_.get(), &upload_required, *metric_logger_); } Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses BUG=84693 TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest Review URL: http://codereview.chromium.org/6969090 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutofillManager::OnLoadedAutofillHeuristics( const std::string& heuristic_xml) { FormStructure::ParseQueryResponse(heuristic_xml, form_structures_.get(), *metric_logger_); }
170,447
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 BufferQueueConsumer::dump(String8& result, const char* prefix) const { mCore->dump(result, prefix); } Commit Message: BQ: Add permission check to BufferQueueConsumer::dump Bug 27046057 Change-Id: Id7bd8cf95045b497943ea39dde49e877aa6f5c4e CWE ID: CWE-264
void BufferQueueConsumer::dump(String8& result, const char* prefix) const { const IPCThreadState* ipc = IPCThreadState::self(); const pid_t pid = ipc->getCallingPid(); const uid_t uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(String16( "android.permission.DUMP"), pid, uid)) { result.appendFormat("Permission Denial: can't dump BufferQueueConsumer " "from pid=%d, uid=%d\n", pid, uid); } else { mCore->dump(result, prefix); } }
174,232
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 SharedWorkerDevToolsAgentHost::WorkerDestroyed() { DCHECK_NE(WORKER_TERMINATED, state_); DCHECK(worker_host_); state_ = WORKER_TERMINATED; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); for (DevToolsSession* session : sessions()) session->SetRenderer(nullptr, nullptr); worker_host_ = nullptr; agent_ptr_.reset(); } 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 SharedWorkerDevToolsAgentHost::WorkerDestroyed() { DCHECK_NE(WORKER_TERMINATED, state_); DCHECK(worker_host_); state_ = WORKER_TERMINATED; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); for (DevToolsSession* session : sessions()) session->SetRenderer(-1, nullptr); worker_host_ = nullptr; agent_ptr_.reset(); }
172,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: BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const { return original_context_.get(); } Commit Message: CWE ID: CWE-20
BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const { BrowserContext* OTRBrowserContextImpl::GetOriginalContext() { return original_context_; }
165,414
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: XGetDeviceButtonMapping( register Display *dpy, XDevice *device, unsigned char map[], unsigned int nmap) { int status = 0; unsigned char mapping[256]; /* known fixed size */ XExtDisplayInfo *info = XInput_find_display(dpy); register xGetDeviceButtonMappingReq *req; xGetDeviceButtonMappingReply rep; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return (NoSuchExtension); GetReq(GetDeviceButtonMapping, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetDeviceButtonMapping; req->deviceid = device->device_id; status = _XReply(dpy, (xReply *) & rep, 0, xFalse); if (status == 1) { if (rep.length <= (sizeof(mapping) >> 2)) { unsigned long nbytes = rep.length << 2; _XRead(dpy, (char *)mapping, nbytes); if (rep.nElts) memcpy(map, mapping, MIN((int)rep.nElts, nmap)); status = rep.nElts; } else { _XEatDataWords(dpy, rep.length); status = 0; } } else status = 0; UnlockDisplay(dpy); SyncHandle(); return (status); } Commit Message: CWE ID: CWE-284
XGetDeviceButtonMapping( register Display *dpy, XDevice *device, unsigned char map[], unsigned int nmap) { int status = 0; unsigned char mapping[256]; /* known fixed size */ XExtDisplayInfo *info = XInput_find_display(dpy); register xGetDeviceButtonMappingReq *req; xGetDeviceButtonMappingReply rep; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return (NoSuchExtension); GetReq(GetDeviceButtonMapping, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetDeviceButtonMapping; req->deviceid = device->device_id; status = _XReply(dpy, (xReply *) & rep, 0, xFalse); if (status == 1) { if (rep.length <= (sizeof(mapping) >> 2) && rep.nElts <= (rep.length << 2)) { unsigned long nbytes = rep.length << 2; _XRead(dpy, (char *)mapping, nbytes); if (rep.nElts) memcpy(map, mapping, MIN((int)rep.nElts, nmap)); status = rep.nElts; } else { _XEatDataWords(dpy, rep.length); status = 0; } } else status = 0; UnlockDisplay(dpy); SyncHandle(); return (status); }
164,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: bool ChangeInputMethodViaIBus(const std::string& input_method_id) { if (!initialized_successfully_) return false; std::string input_method_id_to_switch = input_method_id; if (!InputMethodIsActivated(input_method_id)) { scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); DCHECK(!input_methods->empty()); if (!input_methods->empty()) { input_method_id_to_switch = input_methods->at(0).id; LOG(INFO) << "Can't change the current input method to " << input_method_id << " since the engine is not preloaded. " << "Switch to " << input_method_id_to_switch << " instead."; } } if (chromeos::ChangeInputMethod(input_method_status_connection_, input_method_id_to_switch.c_str())) { return true; } LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch; return false; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChangeInputMethodViaIBus(const std::string& input_method_id) { if (!initialized_successfully_) return false; std::string input_method_id_to_switch = input_method_id; if (!InputMethodIsActivated(input_method_id)) { scoped_ptr<input_method::InputMethodDescriptors> input_methods( GetActiveInputMethods()); DCHECK(!input_methods->empty()); if (!input_methods->empty()) { input_method_id_to_switch = input_methods->at(0).id; LOG(INFO) << "Can't change the current input method to " << input_method_id << " since the engine is not preloaded. " << "Switch to " << input_method_id_to_switch << " instead."; } } if (ibus_controller_->ChangeInputMethod(input_method_id_to_switch)) { return true; } LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch; return false; }
170,481
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: ip_printroute(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int ptr; register u_int len; if (length < 3) { ND_PRINT((ndo, " [bad length %u]", length)); return; } if ((length + 1) & 3) ND_PRINT((ndo, " [bad length %u]", length)); ptr = cp[2] - 1; if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1) ND_PRINT((ndo, " [bad ptr %u]", cp[2])); for (len = 3; len < length; len += 4) { ND_PRINT((ndo, " %s", ipaddr_string(ndo, &cp[len]))); if (ptr > len) ND_PRINT((ndo, ",")); } } Commit Message: CVE-2017-13022/IP: Add bounds checks to ip_printroute(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
ip_printroute(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int ptr; register u_int len; if (length < 3) { ND_PRINT((ndo, " [bad length %u]", length)); return (0); } if ((length + 1) & 3) ND_PRINT((ndo, " [bad length %u]", length)); ND_TCHECK(cp[2]); ptr = cp[2] - 1; if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1) ND_PRINT((ndo, " [bad ptr %u]", cp[2])); for (len = 3; len < length; len += 4) { ND_TCHECK2(cp[len], 4); ND_PRINT((ndo, " %s", ipaddr_string(ndo, &cp[len]))); if (ptr > len) ND_PRINT((ndo, ",")); } return (0); trunc: return (-1); }
167,870
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 *cJSON_Print( cJSON *item ) { return print_value( item, 0, 1 ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
char *cJSON_Print( cJSON *item )
167,293
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 mkvparser::UnserializeString( IMkvReader* pReader, long long pos, long long size_, char*& str) { delete[] str; str = NULL; if (size_ >= LONG_MAX) //we need (size+1) chars return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); str = new (std::nothrow) char[size+1]; if (str == NULL) return -1; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[size] = '\0'; return 0; //success } 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 mkvparser::UnserializeString( if (status) { delete[] str; str = NULL; return status; } str[size] = '\0'; return 0; // success }
174,449
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: ScopedRequest(PepperDeviceEnumerationHostHelper* owner, const Delegate::EnumerateDevicesCallback& callback) : owner_(owner), callback_(callback), requested_(false), request_id_(0), sync_call_(false) { if (!owner_->document_url_.is_valid()) return; requested_ = true; sync_call_ = true; request_id_ = owner_->delegate_->EnumerateDevices( owner_->device_type_, owner_->document_url_, base::Bind(&ScopedRequest::EnumerateDevicesCallbackBody, AsWeakPtr())); sync_call_ = false; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
ScopedRequest(PepperDeviceEnumerationHostHelper* owner, const Delegate::EnumerateDevicesCallback& callback) : owner_(owner), callback_(callback), requested_(false), request_id_(0), sync_call_(false) { if (!owner_->document_url_.is_valid()) return; requested_ = true; sync_call_ = true; DCHECK(owner_->delegate_); request_id_ = owner_->delegate_->EnumerateDevices( owner_->device_type_, owner_->document_url_, base::Bind(&ScopedRequest::EnumerateDevicesCallbackBody, AsWeakPtr())); sync_call_ = false; }
171,605