instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void snd_pcm_period_elapsed(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime; unsigned long flags; if (PCM_RUNTIME_CHECK(substream)) return; runtime = substream->runtime; snd_pcm_stream_lock_irqsave(substream, flags); if (!snd_pcm_running(substream) || snd_pcm_update_hw_ptr0(substream, 1) < 0) goto _end; #ifdef CONFIG_SND_PCM_TIMER if (substream->timer_running) snd_timer_interrupt(substream->timer, 1); #endif _end: snd_pcm_stream_unlock_irqrestore(substream, flags); kill_fasync(&runtime->fasync, SIGIO, POLL_IN); } Commit Message: ALSA: pcm : Call kill_fasync() in stream lock Currently kill_fasync() is called outside the stream lock in snd_pcm_period_elapsed(). This is potentially racy, since the stream may get released even during the irq handler is running. Although snd_pcm_release_substream() calls snd_pcm_drop(), this doesn't guarantee that the irq handler finishes, thus the kill_fasync() call outside the stream spin lock may be invoked after the substream is detached, as recently reported by KASAN. As a quick workaround, move kill_fasync() call inside the stream lock. The fasync is rarely used interface, so this shouldn't have a big impact from the performance POV. Ideally, we should implement some sync mechanism for the proper finish of stream and irq handler. But this oneliner should suffice for most cases, so far. Reported-by: Baozeng Ding <sploving1@gmail.com> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID: CWE-416
void snd_pcm_period_elapsed(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime; unsigned long flags; if (PCM_RUNTIME_CHECK(substream)) return; runtime = substream->runtime; snd_pcm_stream_lock_irqsave(substream, flags); if (!snd_pcm_running(substream) || snd_pcm_update_hw_ptr0(substream, 1) < 0) goto _end; #ifdef CONFIG_SND_PCM_TIMER if (substream->timer_running) snd_timer_interrupt(substream->timer, 1); #endif _end: kill_fasync(&runtime->fasync, SIGIO, POLL_IN); snd_pcm_stream_unlock_irqrestore(substream, flags); }
166,845
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 PresentationConnectionProxy::OnClose() { DCHECK(target_connection_ptr_); source_connection_->didChangeState( blink::WebPresentationConnectionState::Closed); target_connection_ptr_->DidChangeState( content::PRESENTATION_CONNECTION_STATE_CLOSED); } Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures Add layout test. 1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead. BUG=697719 Review-Url: https://codereview.chromium.org/2730123003 Cr-Commit-Position: refs/heads/master@{#455225} CWE ID:
void PresentationConnectionProxy::OnClose() { DCHECK(target_connection_ptr_); source_connection_->didClose(); target_connection_ptr_->DidChangeState( content::PRESENTATION_CONNECTION_STATE_CLOSED); }
172,045
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 RenderViewHostImpl::CreateNewWindow( int route_id, const ViewHostMsg_CreateWindow_Params& params, SessionStorageNamespace* session_storage_namespace) { ViewHostMsg_CreateWindow_Params validated_params(params); ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); delegate_->CreateNewWindow(route_id, validated_params, session_storage_namespace); } Commit Message: Filter more incoming URLs in the CreateWindow path. BUG=170532 Review URL: https://chromiumcodereview.appspot.com/12036002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderViewHostImpl::CreateNewWindow( int route_id, const ViewHostMsg_CreateWindow_Params& params, SessionStorageNamespace* session_storage_namespace) { ViewHostMsg_CreateWindow_Params validated_params(params); ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); FilterURL(policy, GetProcess(), false, &validated_params.opener_url); FilterURL(policy, GetProcess(), true, &validated_params.opener_security_origin); delegate_->CreateNewWindow(route_id, validated_params, session_storage_namespace); }
171,498
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string PrintPreviewUI::GetPrintPreviewUIAddress() const { char preview_ui_addr[2 + (2 * sizeof(this)) + 1]; base::snprintf(preview_ui_addr, sizeof(preview_ui_addr), "%p", this); return preview_ui_addr; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
std::string PrintPreviewUI::GetPrintPreviewUIAddress() const { int32 PrintPreviewUI::GetIDForPrintPreviewUI() const { return id_; }
170,835
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: GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); value[i] = v; i++; } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; } Commit Message: fix buffer overrun in gf_bin128_parse closes #1204 closes #1205 CWE ID: CWE-119
GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); value[i] = v; i++; if (i > 15) { // force error check below i++; break; } } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; }
169,708
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 put_chars(u32 vtermno, const char *buf, int count) { struct port *port; struct scatterlist sg[1]; if (unlikely(early_put_chars)) return early_put_chars(vtermno, buf, count); port = find_port_by_vtermno(vtermno); if (!port) return -EPIPE; sg_init_one(sg, buf, count); return __send_to_port(port, sg, 1, count, (void *)buf, false); } Commit Message: virtio-console: avoid DMA from stack put_chars() stuffs the buffer it gets into an sg, but that buffer may be on the stack. This breaks with CONFIG_VMAP_STACK=y (for me, it manifested as printks getting turned into NUL bytes). Signed-off-by: Omar Sandoval <osandov@fb.com> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Amit Shah <amit.shah@redhat.com> CWE ID: CWE-119
static int put_chars(u32 vtermno, const char *buf, int count) { struct port *port; struct scatterlist sg[1]; void *data; int ret; if (unlikely(early_put_chars)) return early_put_chars(vtermno, buf, count); port = find_port_by_vtermno(vtermno); if (!port) return -EPIPE; data = kmemdup(buf, count, GFP_ATOMIC); if (!data) return -ENOMEM; sg_init_one(sg, data, count); ret = __send_to_port(port, sg, 1, count, data, false); kfree(data); return ret; }
168,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: http_DissectRequest(struct sess *sp) { struct http_conn *htc; struct http *hp; uint16_t retval; CHECK_OBJ_NOTNULL(sp, SESS_MAGIC); htc = sp->htc; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); hp = sp->http; CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); hp->logtag = HTTP_Rx; retval = http_splitline(sp->wrk, sp->fd, hp, htc, HTTP_HDR_REQ, HTTP_HDR_URL, HTTP_HDR_PROTO); if (retval != 0) { WSPR(sp, SLT_HttpGarbage, htc->rxbuf); return (retval); } http_ProtoVer(hp); retval = htc_request_check_host_hdr(hp); if (retval != 0) { WSP(sp, SLT_Error, "Duplicated Host header"); return (retval); } return (retval); } Commit Message: Check for duplicate Content-Length headers in requests If a duplicate CL header is in the request, we fail the request with a 400 (Bad Request) Fix a test case that was sending duplicate CL by misstake and would not fail because of that. CWE ID:
http_DissectRequest(struct sess *sp) { struct http_conn *htc; struct http *hp; uint16_t retval; CHECK_OBJ_NOTNULL(sp, SESS_MAGIC); htc = sp->htc; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); hp = sp->http; CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); hp->logtag = HTTP_Rx; retval = http_splitline(sp->wrk, sp->fd, hp, htc, HTTP_HDR_REQ, HTTP_HDR_URL, HTTP_HDR_PROTO); if (retval != 0) { WSPR(sp, SLT_HttpGarbage, htc->rxbuf); return (retval); } http_ProtoVer(hp); retval = htc_request_check_hdrs(sp, hp); return (retval); }
167,479
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 4; fwd_txfm_ref = fdct4x4_ref; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 4; fwd_txfm_ref = fdct4x4_ref; bit_depth_ = GET_PARAM(3); mask_ = (1 << bit_depth_) - 1; }
174,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: int mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); if (!lua_checkstack(L, nargs)) return luaL_argerror(L, 0, "Too many arguments for MessagePack pack."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; } Commit Message: Security: more cmsgpack fixes by @soloestoy. @soloestoy sent me this additional fixes, after searching for similar problems to the one reported in mp_pack(). I'm committing the changes because it was not possible during to make a public PR to protect Redis users and give Redis providers some time to patch their systems. CWE ID: CWE-119
int mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); if (!lua_checkstack(L, nargs)) return luaL_argerror(L, 0, "Too many arguments for MessagePack pack."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ luaL_checkstack(L, 1, "in function mp_check"); lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; }
169,241
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 udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; } Commit Message: udf: avoid info leak on export For type 0x51 the udf.parent_partref member in struct fid gets copied uninitialized to userland. Fix this by initializing it to 0. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-200
static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.parent_partref = 0; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; }
166,178
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::FinishLoading(int32_t done_status) { done_status_ = done_status; if (TrackedCallback::IsPending(pending_callback_)) RunCallback(done_status_); } 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::FinishLoading(int32_t done_status) { done_status_ = done_status; user_buffer_ = NULL; user_buffer_size_ = 0; if (TrackedCallback::IsPending(pending_callback_)) RunCallback(done_status_); }
170,900
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 ServerWrapper::OnHttpRequest(int connection_id, const net::HttpServerRequestInfo& info) { server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools); if (base::StartsWith(info.path, "/json", base::CompareCase::SENSITIVE)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnJsonRequest, handler_, connection_id, info)); return; } if (info.path.empty() || info.path == "/") { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnDiscoveryPageRequest, handler_, connection_id)); return; } if (!base::StartsWith(info.path, "/devtools/", base::CompareCase::SENSITIVE)) { server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation); return; } std::string filename = PathWithoutParams(info.path.substr(10)); std::string mime_type = GetMimeType(filename); if (!debug_frontend_dir_.empty()) { base::FilePath path = debug_frontend_dir_.AppendASCII(filename); std::string data; base::ReadFileToString(path, &data); server_->Send200(connection_id, data, mime_type, kDevtoolsHttpHandlerTrafficAnnotation); return; } if (bundles_resources_) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnFrontendResourceRequest, handler_, connection_id, filename)); return; } server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation); } Commit Message: DevTools: check Host header for being IP or localhost when connecting over RDP. Bug: 813540 Change-Id: I9338aa2475c15090b8a60729be25502eb866efb7 Reviewed-on: https://chromium-review.googlesource.com/952522 Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Pavel Feldman <pfeldman@chromium.org> Cr-Commit-Position: refs/heads/master@{#541547} CWE ID: CWE-20
void ServerWrapper::OnHttpRequest(int connection_id, const net::HttpServerRequestInfo& info) { if (!RequestIsSafeToServe(info)) { Send500(connection_id, "Host header is specified and is not an IP address or localhost."); return; } server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools); if (base::StartsWith(info.path, "/json", base::CompareCase::SENSITIVE)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnJsonRequest, handler_, connection_id, info)); return; } if (info.path.empty() || info.path == "/") { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnDiscoveryPageRequest, handler_, connection_id)); return; } if (!base::StartsWith(info.path, "/devtools/", base::CompareCase::SENSITIVE)) { server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation); return; } std::string filename = PathWithoutParams(info.path.substr(10)); std::string mime_type = GetMimeType(filename); if (!debug_frontend_dir_.empty()) { base::FilePath path = debug_frontend_dir_.AppendASCII(filename); std::string data; base::ReadFileToString(path, &data); server_->Send200(connection_id, data, mime_type, kDevtoolsHttpHandlerTrafficAnnotation); return; } if (bundles_resources_) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnFrontendResourceRequest, handler_, connection_id, filename)); return; } server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation); }
172,732
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: xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur); } ret = inputPush(ctxt, input); if (ctxt->instate == XML_PARSER_EOF) return(-1); GROW; return(ret); } Commit Message: Detect infinite recursion in parameter entities When expanding a parameter entity in a DTD, infinite recursion could lead to an infinite loop or memory exhaustion. Thanks to Wei Lei for the first of many reports. Fixes bug 759579. CWE ID: CWE-835
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur); } if (((ctxt->inputNr > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->inputNr > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); while (ctxt->inputNr > 1) xmlFreeInputStream(inputPop(ctxt)); return(-1); } ret = inputPush(ctxt, input); if (ctxt->instate == XML_PARSER_EOF) return(-1); GROW; return(ret); }
167,666
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: mark_context_stack(mrb_state *mrb, struct mrb_context *c) { size_t i; size_t e; if (c->stack == NULL) return; e = c->stack - c->stbase; if (c->ci) e += c->ci->nregs; if (c->stbase + e > c->stend) e = c->stend - c->stbase; for (i=0; i<e; i++) { mrb_value v = c->stbase[i]; if (!mrb_immediate_p(v)) { if (mrb_basic_ptr(v)->tt == MRB_TT_FREE) { c->stbase[i] = mrb_nil_value(); } else { mrb_gc_mark(mrb, mrb_basic_ptr(v)); } } } } Commit Message: Clear unused stack region that may refer freed objects; fix #3596 CWE ID: CWE-416
mark_context_stack(mrb_state *mrb, struct mrb_context *c) { size_t i; size_t e; mrb_value nil; if (c->stack == NULL) return; e = c->stack - c->stbase; if (c->ci) e += c->ci->nregs; if (c->stbase + e > c->stend) e = c->stend - c->stbase; for (i=0; i<e; i++) { mrb_value v = c->stbase[i]; if (!mrb_immediate_p(v)) { mrb_gc_mark(mrb, mrb_basic_ptr(v)); } } e = c->stend - c->stbase; nil = mrb_nil_value(); for (; i<e; i++) { c->stbase[i] = nil; } }
168,094
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 re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } Commit Message: re_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c CWE ID: CWE-476
int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); }
168,485
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: xmlParse3986Port(xmlURIPtr uri, const char **str) { const char *cur = *str; unsigned port = 0; /* unsigned for defined overflow behavior */ if (ISA_DIGIT(cur)) { while (ISA_DIGIT(cur)) { port = port * 10 + (*cur - '0'); cur++; } if (uri != NULL) uri->port = port & INT_MAX; /* port value modulo INT_MAX+1 */ *str = cur; return(0); } return(1); } Commit Message: DO NOT MERGE: Use correct limit for port values no upstream report yet, add it here when we have it issue found & patch by nmehta@ Bug: 36555370 Change-Id: Ibf1efea554b95f514e23e939363d608021de4614 (cherry picked from commit b62884fb49fe92081e414966d9b5fe58250ae53c) CWE ID: CWE-119
xmlParse3986Port(xmlURIPtr uri, const char **str) { const char *cur = *str; unsigned port = 0; /* unsigned for defined overflow behavior */ if (ISA_DIGIT(cur)) { while (ISA_DIGIT(cur)) { port = port * 10 + (*cur - '0'); cur++; } if (uri != NULL) uri->port = port & USHRT_MAX; /* port value modulo INT_MAX+1 */ *str = cur; return(0); } return(1); }
174,119
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: Chunk::Chunk( ContainerChunk* parent, RIFF_MetaHandler* handler, bool skip, ChunkType c ) { chunkType = c; // base class assumption this->parent = parent; this->oldSize = 0; this->hasChange = false; // [2414649] valid assumption at creation time XMP_IO* file = handler->parent->ioRef; this->oldPos = file->Offset(); this->id = XIO::ReadUns32_LE( file ); this->oldSize = XIO::ReadUns32_LE( file ) + 8; XMP_Int64 chunkEnd = this->oldPos + this->oldSize; if ( parent != 0 ) chunkLimit = parent->oldPos + parent->oldSize; if ( chunkEnd > chunkLimit ) { bool isUpdate = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenForUpdate ); bool repairFile = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenRepairFile ); if ( (! isUpdate) || (repairFile && (parent == 0)) ) { this->oldSize = chunkLimit - this->oldPos; } else { XMP_Throw ( "Bad RIFF chunk size", kXMPErr_BadFileFormat ); } } this->newSize = this->oldSize; this->needSizeFix = false; if ( skip ) file->Seek ( (this->oldSize - 8), kXMP_SeekFromCurrent ); if ( this->parent != NULL ) { this->parent->children.push_back( this ); if( this->chunkType == chunk_VALUE ) this->parent->childmap.insert( std::make_pair( this->id, (ValueChunk*) this ) ); } } Commit Message: CWE ID: CWE-190
Chunk::Chunk( ContainerChunk* parent, RIFF_MetaHandler* handler, bool skip, ChunkType c ) { chunkType = c; // base class assumption this->parent = parent; this->oldSize = 0; this->hasChange = false; // [2414649] valid assumption at creation time XMP_IO* file = handler->parent->ioRef; this->oldPos = file->Offset(); this->id = XIO::ReadUns32_LE( file ); this->oldSize = XIO::ReadUns32_LE( file ); this->oldSize += 8; XMP_Int64 chunkEnd = this->oldPos + this->oldSize; if ( parent != 0 ) chunkLimit = parent->oldPos + parent->oldSize; if ( chunkEnd > chunkLimit ) { bool isUpdate = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenForUpdate ); bool repairFile = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenRepairFile ); if ( (! isUpdate) || (repairFile && (parent == 0)) ) { this->oldSize = chunkLimit - this->oldPos; } else { XMP_Throw ( "Bad RIFF chunk size", kXMPErr_BadFileFormat ); } } this->newSize = this->oldSize; this->needSizeFix = false; if ( skip ) file->Seek ( (this->oldSize - 8), kXMP_SeekFromCurrent ); if ( this->parent != NULL ) { this->parent->children.push_back( this ); if( this->chunkType == chunk_VALUE ) this->parent->childmap.insert( std::make_pair( this->id, (ValueChunk*) this ) ); } }
165,369
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: GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher( const GURL& url) { std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this); fetcher->SetRequestContext(helper_->request_context()); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); fetcher->SetAutomaticallyRetryOnNetworkChanges(1); return fetcher; } Commit Message: Add data usage tracking for chrome services Add data usage tracking for captive portal, web resource and signin services BUG=655749 Review-Url: https://codereview.chromium.org/2643013004 Cr-Commit-Position: refs/heads/master@{#445810} CWE ID: CWE-190
GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher( const GURL& url) { std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this); fetcher->SetRequestContext(helper_->request_context()); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); data_use_measurement::DataUseUserData::AttachToFetcher( fetcher.get(), data_use_measurement::DataUseUserData::SIGNIN); fetcher->SetAutomaticallyRetryOnNetworkChanges(1); return fetcher; }
172,019
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 init_nss_hash(struct crypto_instance *instance) { PK11SlotInfo* hash_slot = NULL; SECItem hash_param; if (!hash_to_nss[instance->crypto_hash_type]) { return 0; } hash_param.type = siBuffer; hash_param.data = 0; hash_param.len = 0; hash_slot = PK11_GetBestSlot(hash_to_nss[instance->crypto_hash_type], NULL); if (hash_slot == NULL) { log_printf(instance->log_level_security, "Unable to find security slot (err %d)", PR_GetError()); return -1; } instance->nss_sym_key_sign = PK11_ImportSymKey(hash_slot, hash_to_nss[instance->crypto_hash_type], PK11_OriginUnwrap, CKA_SIGN, &hash_param, NULL); if (instance->nss_sym_key_sign == NULL) { log_printf(instance->log_level_security, "Failure to import key into NSS (err %d)", PR_GetError()); return -1; } PK11_FreeSlot(hash_slot); return 0; } Commit Message: totemcrypto: fix hmac key initialization Signed-off-by: Fabio M. Di Nitto <fdinitto@redhat.com> Reviewed-by: Jan Friesse <jfriesse@redhat.com> CWE ID:
static int init_nss_hash(struct crypto_instance *instance) { PK11SlotInfo* hash_slot = NULL; SECItem hash_param; if (!hash_to_nss[instance->crypto_hash_type]) { return 0; } hash_param.type = siBuffer; hash_param.data = instance->private_key; hash_param.len = instance->private_key_len; hash_slot = PK11_GetBestSlot(hash_to_nss[instance->crypto_hash_type], NULL); if (hash_slot == NULL) { log_printf(instance->log_level_security, "Unable to find security slot (err %d)", PR_GetError()); return -1; } instance->nss_sym_key_sign = PK11_ImportSymKey(hash_slot, hash_to_nss[instance->crypto_hash_type], PK11_OriginUnwrap, CKA_SIGN, &hash_param, NULL); if (instance->nss_sym_key_sign == NULL) { log_printf(instance->log_level_security, "Failure to import key into NSS (err %d)", PR_GetError()); return -1; } PK11_FreeSlot(hash_slot); return 0; }
166,546
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 AwContents::ScrollContainerViewTo(gfx::Vector2d new_value) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return; Java_AwContents_scrollContainerViewTo( env, obj.obj(), new_value.x(), new_value.y()); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
void AwContents::ScrollContainerViewTo(gfx::Vector2d new_value) { void AwContents::ScrollContainerViewTo(const gfx::Vector2d& new_value) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return; Java_AwContents_scrollContainerViewTo( env, obj.obj(), new_value.x(), new_value.y()); }
171,617
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 UpdateProperty(IBusProperty* ibus_prop) { DLOG(INFO) << "UpdateProperty"; DCHECK(ibus_prop); ImePropertyList prop_list; // our representation. if (!FlattenProperty(ibus_prop, &prop_list)) { LOG(ERROR) << "Malformed properties are detected"; return; } if (!prop_list.empty()) { update_ime_property_(language_library_, prop_list); } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void UpdateProperty(IBusProperty* ibus_prop) { FOR_EACH_OBSERVER(Observer, observers_, OnRegisterImeProperties(prop_list)); }
170,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MountError PerformFakeMount(const std::string& source_path, const base::FilePath& mounted_path) { if (mounted_path.empty()) return MOUNT_ERROR_INVALID_ARGUMENT; if (!base::CreateDirectory(mounted_path)) { DLOG(ERROR) << "Failed to create directory at " << mounted_path.value(); return MOUNT_ERROR_DIRECTORY_CREATION_FAILED; } const base::FilePath dummy_file_path = mounted_path.Append("SUCCESSFULLY_PERFORMED_FAKE_MOUNT.txt"); const std::string dummy_file_content = "This is a dummy file."; const int write_result = base::WriteFile( dummy_file_path, dummy_file_content.data(), dummy_file_content.size()); if (write_result != static_cast<int>(dummy_file_content.size())) { DLOG(ERROR) << "Failed to put a dummy file at " << dummy_file_path.value(); return MOUNT_ERROR_MOUNT_PROGRAM_FAILED; } return MOUNT_ERROR_NONE; } Commit Message: Add a fake DriveFS launcher client. Using DriveFS requires building and deploying ChromeOS. Add a client for the fake DriveFS launcher to allow the use of a real DriveFS from a ChromeOS chroot to be used with a target_os="chromeos" build of chrome. This connects to the fake DriveFS launcher using mojo over a unix domain socket named by a command-line flag, using the launcher to create DriveFS instances. Bug: 848126 Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1 Reviewed-on: https://chromium-review.googlesource.com/1098434 Reviewed-by: Xiyuan Xia <xiyuan@chromium.org> Commit-Queue: Sam McNally <sammc@chromium.org> Cr-Commit-Position: refs/heads/master@{#567513} CWE ID:
MountError PerformFakeMount(const std::string& source_path, const base::FilePath& mounted_path, MountType type) { if (mounted_path.empty()) return MOUNT_ERROR_INVALID_ARGUMENT; if (!base::CreateDirectory(mounted_path)) { DLOG(ERROR) << "Failed to create directory at " << mounted_path.value(); return MOUNT_ERROR_DIRECTORY_CREATION_FAILED; } // Fake network mounts are responsible for populating their mount paths so // don't need a dummy file. if (type == MOUNT_TYPE_NETWORK_STORAGE) return MOUNT_ERROR_NONE; const base::FilePath dummy_file_path = mounted_path.Append("SUCCESSFULLY_PERFORMED_FAKE_MOUNT.txt"); const std::string dummy_file_content = "This is a dummy file."; const int write_result = base::WriteFile( dummy_file_path, dummy_file_content.data(), dummy_file_content.size()); if (write_result != static_cast<int>(dummy_file_content.size())) { DLOG(ERROR) << "Failed to put a dummy file at " << dummy_file_path.value(); return MOUNT_ERROR_MOUNT_PROGRAM_FAILED; } return MOUNT_ERROR_NONE; }
171,731
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 smp_process_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = (uint8_t*)p_data; uint8_t reason = SMP_INVALID_PARAMETERS; SMP_TRACE_DEBUG("%s", __func__); p_cb->status = *(uint8_t*)p_data; if (smp_command_has_invalid_parameters(p_cb)) { smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); return; } if (p != NULL) { STREAM_TO_UINT8(p_cb->peer_keypress_notification, p); } else { p_cb->peer_keypress_notification = BTM_SP_KEY_OUT_OF_RANGE; } p_cb->cb_evt = SMP_PEER_KEYPR_NOT_EVT; } Commit Message: DO NOT MERGE Fix OOB read before buffer length check Bug: 111936834 Test: manual Change-Id: Ib98528fb62db0d724ebd9112d071e367f78e369d (cherry picked from commit 4548f34c90803c6544f6bed03399f2eabeab2a8e) CWE ID: CWE-125
void smp_process_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = (uint8_t*)p_data; uint8_t reason = SMP_INVALID_PARAMETERS; SMP_TRACE_DEBUG("%s", __func__); if (smp_command_has_invalid_parameters(p_cb)) { if (p_cb->rcvd_cmd_len < 2) { // 1 (opcode) + 1 (Notif Type) bytes android_errorWriteLog(0x534e4554, "111936834"); } smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); return; } p_cb->status = *(uint8_t*)p_data; if (p != NULL) { STREAM_TO_UINT8(p_cb->peer_keypress_notification, p); } else { p_cb->peer_keypress_notification = BTM_SP_KEY_OUT_OF_RANGE; } p_cb->cb_evt = SMP_PEER_KEYPR_NOT_EVT; }
174,077
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 KeyMap::Press(const scoped_refptr<WindowProxy>& window, const ui::KeyboardCode key_code, const wchar_t& key) { if (key_code == ui::VKEY_SHIFT) { shift_ = !shift_; } else if (key_code == ui::VKEY_CONTROL) { control_ = !control_; } else if (key_code == ui::VKEY_MENU) { // ALT alt_ = !alt_; } else if (key_code == ui::VKEY_COMMAND) { command_ = !command_; } int modifiers = 0; if (shift_ || shifted_keys_.find(key) != shifted_keys_.end()) { modifiers = modifiers | ui::EF_SHIFT_DOWN; } if (control_) { modifiers = modifiers | ui::EF_CONTROL_DOWN; } if (alt_) { modifiers = modifiers | ui::EF_ALT_DOWN; } if (command_) { VLOG(1) << "Pressing command key on linux!!"; modifiers = modifiers | ui::EF_COMMAND_DOWN; } window->SimulateOSKeyPress(key_code, modifiers); return true; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool KeyMap::Press(const scoped_refptr<WindowProxy>& window, const ui::KeyboardCode key_code, const wchar_t& key) { if (key_code == ui::VKEY_SHIFT) { shift_ = !shift_; } else if (key_code == ui::VKEY_CONTROL) { control_ = !control_; } else if (key_code == ui::VKEY_MENU) { // ALT alt_ = !alt_; } else if (key_code == ui::VKEY_COMMAND) { command_ = !command_; } int modifiers = 0; if (shift_ || shifted_keys_.find(key) != shifted_keys_.end()) { modifiers = modifiers | ui::EF_SHIFT_DOWN; } if (control_) { modifiers = modifiers | ui::EF_CONTROL_DOWN; } if (alt_) { modifiers = modifiers | ui::EF_ALT_DOWN; } if (command_) { LOG(INFO) << "Pressing command key on linux!!"; modifiers = modifiers | ui::EF_COMMAND_DOWN; } window->SimulateOSKeyPress(key_code, modifiers); return true; }
170,459
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 svc_rdma_xdr_encode_reply_array(struct rpcrdma_write_array *ary, int chunks) { ary->wc_discrim = xdr_one; ary->wc_nchunks = cpu_to_be32(chunks); } 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
void svc_rdma_xdr_encode_reply_array(struct rpcrdma_write_array *ary,
168,161
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 svc_rdma_xdr_encode_array_chunk(struct rpcrdma_write_array *ary, int chunk_no, __be32 rs_handle, __be64 rs_offset, u32 write_len) { struct rpcrdma_segment *seg = &ary->wc_array[chunk_no].wc_target; seg->rs_handle = rs_handle; seg->rs_offset = rs_offset; seg->rs_length = cpu_to_be32(write_len); } 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
void svc_rdma_xdr_encode_array_chunk(struct rpcrdma_write_array *ary,
168,159
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 regulator_ena_gpio_free(struct regulator_dev *rdev) { struct regulator_enable_gpio *pin, *n; if (!rdev->ena_pin) return; /* Free the GPIO only in case of no use */ list_for_each_entry_safe(pin, n, &regulator_ena_gpio_list, list) { if (pin->gpiod == rdev->ena_pin->gpiod) { if (pin->request_count <= 1) { pin->request_count = 0; gpiod_put(pin->gpiod); list_del(&pin->list); kfree(pin); } else { pin->request_count--; } } } } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <sw0312.kim@samsung.com> Signed-off-by: Mark Brown <broonie@kernel.org> CWE ID: CWE-416
static void regulator_ena_gpio_free(struct regulator_dev *rdev) { struct regulator_enable_gpio *pin, *n; if (!rdev->ena_pin) return; /* Free the GPIO only in case of no use */ list_for_each_entry_safe(pin, n, &regulator_ena_gpio_list, list) { if (pin->gpiod == rdev->ena_pin->gpiod) { if (pin->request_count <= 1) { pin->request_count = 0; gpiod_put(pin->gpiod); list_del(&pin->list); kfree(pin); rdev->ena_pin = NULL; return; } else { pin->request_count--; } } } }
168,894
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 ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); Stream_Write_UINT32(s, header->MessageType); } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); Stream_Write_UINT32(s, header->MessageType); }
169,281
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 vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a, long offset,int ch, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); long i,j; int chptr=0; if (!v) return -1; for(i=offset;i<offset+n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim;j++){ a[chptr++][i]+=v[j]; if(chptr==ch){ chptr=0; i++; } } } } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
long vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a, long offset,int ch, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); long i,j; int chptr=0; if (!v) return -1; for(i=offset;i<offset+n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim && i < offset + n;j++){ a[chptr++][i]+=v[j]; if(chptr==ch){ chptr=0; i++; } } } } return 0; }
173,989
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: stub_charset () { locale = get_locale_var ("LC_CTYPE"); locale = get_locale_var ("LC_CTYPE"); if (locale == 0 || *locale == 0) return "ASCII"; s = strrchr (locale, '.'); if (s) { t = strchr (s, '@'); if (t) *t = 0; return ++s; } else if (STREQ (locale, "UTF-8")) return "UTF-8"; else return "ASCII"; } Commit Message: CWE ID: CWE-119
stub_charset () { locale = get_locale_var ("LC_CTYPE"); locale = get_locale_var ("LC_CTYPE"); if (locale == 0 || *locale == 0) { strcpy (charsetbuf, "ASCII"); return charsetbuf; } s = strrchr (locale, '.'); if (s) { strcpy (charsetbuf, s+1); t = strchr (charsetbuf, '@'); if (t) *t = 0; return charsetbuf; } strcpy (charsetbuf, locale); return charsetbuf; }
165,431
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PromoResourceService::PromoResourceStateChange() { web_resource_update_scheduled_ = false; content::NotificationService* service = content::NotificationService::current(); service->Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED, content::Source<WebResourceService>(this), content::NotificationService::NoDetails()); } Commit Message: Refresh promo notifications as they're fetched The "guard" existed for notification scheduling was preventing "turn-off a promo" and "update a promo" scenarios. Yet I do not believe it was adding any actual safety: if things on a server backend go wrong, the clients will be affected one way or the other, and it is better to have an option to shut the malformed promo down "as quickly as possible" (~in 12-24 hours). BUG= TEST= Review URL: https://chromiumcodereview.appspot.com/10696204 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void PromoResourceService::PromoResourceStateChange() { content::NotificationService* service = content::NotificationService::current(); service->Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED, content::Source<WebResourceService>(this), content::NotificationService::NoDetails()); }
170,783
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 fpga_reset(void) { if (!check_boco2()) { /* we do not have BOCO2, this is not really used */ return 0; } printf("PCIe reset through GPIO7: "); /* apply PCIe reset via GPIO */ kw_gpio_set_valid(KM_PEX_RST_GPIO_PIN, 1); kw_gpio_direction_output(KM_PEX_RST_GPIO_PIN, 1); kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 0); udelay(1000*10); kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 1); printf(" done\n"); return 0; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
int fpga_reset(void) { /* no dedicated reset pin for FPGA */ return 0; }
169,626
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ChromeDownloadManagerDelegate::IsDangerousFile( const DownloadItem& download, const FilePath& suggested_path, bool visited_referrer_before) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (download.GetTransitionType() & content::PAGE_TRANSITION_FROM_ADDRESS_BAR) return false; if (extensions::FeatureSwitch::easy_off_store_install()->IsEnabled() && download_crx_util::IsExtensionDownload(download) && !extensions::WebstoreInstaller::GetAssociatedApproval(download)) { return true; } if (ShouldOpenFileBasedOnExtension(suggested_path) && download.HasUserGesture()) return false; download_util::DownloadDangerLevel danger_level = download_util::GetFileDangerLevel(suggested_path.BaseName()); if (danger_level == download_util::AllowOnUserGesture) return !download.HasUserGesture() || !visited_referrer_before; return danger_level == download_util::Dangerous; } Commit Message: For "Dangerous" file type, no user gesture will bypass the download warning. BUG=170569 Review URL: https://codereview.chromium.org/12039015 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178072 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ChromeDownloadManagerDelegate::IsDangerousFile( const DownloadItem& download, const FilePath& suggested_path, bool visited_referrer_before) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (extensions::FeatureSwitch::easy_off_store_install()->IsEnabled() && download_crx_util::IsExtensionDownload(download) && !extensions::WebstoreInstaller::GetAssociatedApproval(download)) { return true; } if (ShouldOpenFileBasedOnExtension(suggested_path) && download.HasUserGesture()) return false; download_util::DownloadDangerLevel danger_level = download_util::GetFileDangerLevel(suggested_path.BaseName()); if (danger_level == download_util::AllowOnUserGesture) { if (download.GetTransitionType() & content::PAGE_TRANSITION_FROM_ADDRESS_BAR) { return false; } return !download.HasUserGesture() || !visited_referrer_before; } return danger_level == download_util::Dangerous; }
171,393
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: BluetoothAdapterChromeOS::BluetoothAdapterChromeOS() : weak_ptr_factory_(this) { DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this); std::vector<dbus::ObjectPath> object_paths = DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters(); if (!object_paths.empty()) { VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available."; SetAdapter(object_paths[0]); } } 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:
BluetoothAdapterChromeOS::BluetoothAdapterChromeOS() : weak_ptr_factory_(this) { DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this); std::vector<dbus::ObjectPath> object_paths = DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters(); if (!object_paths.empty()) { VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available."; SetAdapter(object_paths[0]); } // Register the pairing agent. dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus(); agent_.reset(BluetoothAgentServiceProvider::Create( system_bus, dbus::ObjectPath(kAgentPath), this)); DCHECK(agent_.get()); VLOG(1) << "Registering pairing agent"; DBusThreadManager::Get()->GetBluetoothAgentManagerClient()-> RegisterAgent( dbus::ObjectPath(kAgentPath), bluetooth_agent_manager::kKeyboardDisplayCapability, base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgent, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgentError, weak_ptr_factory_.GetWeakPtr())); }
171,214
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: METHODDEF(JDIMENSION) get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PPM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; } return 1; } Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP ... in which one or more of the color indices is out of range for the number of palette entries. Fix partly borrowed from jpeg-9c. This commit also adopts Guido's JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific JERR_PPM_TOOLARGE enum value. Fixes #258 CWE ID: CWE-125
METHODDEF(JDIMENSION) get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PPM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); *ptr++ = rescale[temp]; } return 1; }
169,839
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: FLACParser::FLACParser( const sp<DataSource> &dataSource, const sp<MetaData> &fileMetadata, const sp<MetaData> &trackMetadata) : mDataSource(dataSource), mFileMetadata(fileMetadata), mTrackMetadata(trackMetadata), mInitCheck(false), mMaxBufferSize(0), mGroup(NULL), mCopy(copyTrespass), mDecoder(NULL), mCurrentPos(0LL), mEOF(false), mStreamInfoValid(false), mWriteRequested(false), mWriteCompleted(false), mWriteBuffer(NULL), mErrorStatus((FLAC__StreamDecoderErrorStatus) -1) { ALOGV("FLACParser::FLACParser"); memset(&mStreamInfo, 0, sizeof(mStreamInfo)); memset(&mWriteHeader, 0, sizeof(mWriteHeader)); mInitCheck = init(); } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
FLACParser::FLACParser( const sp<DataSource> &dataSource, const sp<MetaData> &fileMetadata, const sp<MetaData> &trackMetadata) : mDataSource(dataSource), mFileMetadata(fileMetadata), mTrackMetadata(trackMetadata), mInitCheck(false), mMaxBufferSize(0), mGroup(NULL), mCopy(copyTrespass), mDecoder(NULL), mCurrentPos(0LL), mEOF(false), mStreamInfoValid(false), mWriteRequested(false), mWriteCompleted(false), mErrorStatus((FLAC__StreamDecoderErrorStatus) -1) { ALOGV("FLACParser::FLACParser"); memset(&mStreamInfo, 0, sizeof(mStreamInfo)); memset(&mWriteHeader, 0, sizeof(mWriteHeader)); mInitCheck = init(); }
174,014
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: Track::Track( Segment* pSegment, long long element_start, long long element_size) : m_pSegment(pSegment), m_element_start(element_start), m_element_size(element_size), content_encoding_entries_(NULL), content_encoding_entries_end_(NULL) { } 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
Track::Track( Track::Track(Segment* pSegment, long long element_start, long long element_size) : m_pSegment(pSegment), m_element_start(element_start), m_element_size(element_size), content_encoding_entries_(NULL), content_encoding_entries_end_(NULL) {} Track::~Track() { Info& info = const_cast<Info&>(m_info); info.Clear(); ContentEncoding** i = content_encoding_entries_; ContentEncoding** const j = content_encoding_entries_end_; while (i != j) { ContentEncoding* const encoding = *i++; delete encoding; } delete[] content_encoding_entries_; }
174,445
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 usage() { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, " by Willem van Schaik, 1999\n"); #ifdef __TURBOC__ fprintf (stderr, " for Turbo-C and Borland-C compilers\n"); #else fprintf (stderr, " for Linux (and Unix) compilers\n"); #endif fprintf (stderr, "Usage: png2pnm [options] <file>.png [<file>.pnm]\n"); fprintf (stderr, " or: ... | png2pnm [options]\n"); fprintf (stderr, "Options:\n"); fprintf (stderr, " -r[aw] write pnm-file in binary format (P4/P5/P6) (default)\n"); fprintf (stderr, " -n[oraw] write pnm-file in ascii format (P1/P2/P3)\n"); fprintf (stderr, " -a[lpha] <file>.pgm write PNG alpha channel as pgm-file\n"); fprintf (stderr, " -h | -? print this help-information\n"); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
void usage() { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, " by Willem van Schaik, 1999\n"); #ifdef __TURBOC__ fprintf (stderr, " for Turbo-C and Borland-C compilers\n"); #else fprintf (stderr, " for Linux (and Unix) compilers\n"); #endif fprintf (stderr, "Usage: png2pnm [options] <file>.png [<file>.pnm]\n"); fprintf (stderr, " or: ... | png2pnm [options]\n"); fprintf (stderr, "Options:\n"); fprintf (stderr, " -r[aw] write pnm-file in binary format (P4/P5/P6) (default)\n"); fprintf (stderr, " -n[oraw] write pnm-file in ascii format (P1/P2/P3)\n"); fprintf (stderr, " -a[lpha] <file>.pgm write PNG alpha channel as pgm-file\n"); fprintf (stderr, " -h | -? print this help-information\n"); }
173,724
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 DownloadCoreServiceImpl::SetDownloadManagerDelegateForTesting( std::unique_ptr<ChromeDownloadManagerDelegate> new_delegate) { manager_delegate_.swap(new_delegate); DownloadManager* dm = BrowserContext::GetDownloadManager(profile_); dm->SetDelegate(manager_delegate_.get()); manager_delegate_->SetDownloadManager(dm); if (new_delegate) new_delegate->Shutdown(); } Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate. DownloadManager has public SetDelegate method and tests and or other subsystems can install their own implementations of the delegate. Bug: 805905 Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8 TBR: tests updated to follow the API change. Reviewed-on: https://chromium-review.googlesource.com/894702 Reviewed-by: David Vallet <dvallet@chromium.org> Reviewed-by: Min Qin <qinmin@chromium.org> Cr-Commit-Position: refs/heads/master@{#533515} CWE ID: CWE-125
void DownloadCoreServiceImpl::SetDownloadManagerDelegateForTesting( std::unique_ptr<ChromeDownloadManagerDelegate> new_delegate) { manager_delegate_.swap(new_delegate); DownloadManager* dm = BrowserContext::GetDownloadManager(profile_); dm->SetDelegate(manager_delegate_.get()); if (manager_delegate_) manager_delegate_->SetDownloadManager(dm); download_manager_created_ = !!manager_delegate_; if (new_delegate) new_delegate->Shutdown(); }
173,169
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 char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc) { const char *it = s; const char *end = s + len; if (enc == ENCQUOTEDPRINTABLE) { struct Buffer buf = { 0 }; for (; it < end; ++it) { if (*it == '_') { mutt_buffer_addch(&buf, ' '); } else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) && (!(it[2] & ~127) && hexval(it[2]) != -1)) { mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2])); it += 2; } else { mutt_buffer_addch(&buf, *it); } } mutt_buffer_addch(&buf, '\0'); return buf.data; } else if (enc == ENCBASE64) { char *out = mutt_mem_malloc(3 * len / 4 + 1); int dlen = mutt_b64_decode(out, it); if (dlen == -1) { FREE(&out); return NULL; } out[dlen] = '\0'; return out; } assert(0); /* The enc parameter has an invalid value */ return NULL; } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119
static char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc) { const char *it = s; const char *end = s + len; if (enc == ENCQUOTEDPRINTABLE) { struct Buffer buf = { 0 }; for (; it < end; ++it) { if (*it == '_') { mutt_buffer_addch(&buf, ' '); } else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) && (!(it[2] & ~127) && hexval(it[2]) != -1)) { mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2])); it += 2; } else { mutt_buffer_addch(&buf, *it); } } mutt_buffer_addch(&buf, '\0'); return buf.data; } else if (enc == ENCBASE64) { const int olen = 3 * len / 4 + 1; char *out = mutt_mem_malloc(olen); int dlen = mutt_b64_decode(out, it, olen); if (dlen == -1) { FREE(&out); return NULL; } out[dlen] = '\0'; return out; } assert(0); /* The enc parameter has an invalid value */ return NULL; }
169,129
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 sig_server_connect_copy(SERVER_CONNECT_REC **dest, IRC_SERVER_CONNECT_REC *src) { IRC_SERVER_CONNECT_REC *rec; g_return_if_fail(dest != NULL); if (!IS_IRC_SERVER_CONNECT(src)) return; rec = g_new0(IRC_SERVER_CONNECT_REC, 1); rec->chat_type = IRC_PROTOCOL; rec->max_cmds_at_once = src->max_cmds_at_once; rec->cmd_queue_speed = src->cmd_queue_speed; rec->max_query_chans = src->max_query_chans; rec->max_kicks = src->max_kicks; rec->max_modes = src->max_modes; rec->max_msgs = src->max_msgs; rec->max_whois = src->max_whois; rec->usermode = g_strdup(src->usermode); rec->alternate_nick = g_strdup(src->alternate_nick); rec->sasl_mechanism = src->sasl_mechanism; rec->sasl_username = src->sasl_username; rec->sasl_password = src->sasl_password; *dest = (SERVER_CONNECT_REC *) rec; } Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect copy sasl username and password values CWE ID: CWE-416
static void sig_server_connect_copy(SERVER_CONNECT_REC **dest, IRC_SERVER_CONNECT_REC *src) { IRC_SERVER_CONNECT_REC *rec; g_return_if_fail(dest != NULL); if (!IS_IRC_SERVER_CONNECT(src)) return; rec = g_new0(IRC_SERVER_CONNECT_REC, 1); rec->chat_type = IRC_PROTOCOL; rec->max_cmds_at_once = src->max_cmds_at_once; rec->cmd_queue_speed = src->cmd_queue_speed; rec->max_query_chans = src->max_query_chans; rec->max_kicks = src->max_kicks; rec->max_modes = src->max_modes; rec->max_msgs = src->max_msgs; rec->max_whois = src->max_whois; rec->usermode = g_strdup(src->usermode); rec->alternate_nick = g_strdup(src->alternate_nick); rec->sasl_mechanism = src->sasl_mechanism; rec->sasl_username = g_strdup(src->sasl_username); rec->sasl_password = g_strdup(src->sasl_password); *dest = (SERVER_CONNECT_REC *) rec; }
169,643
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 GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased) { if (paintingDisabled()) return; if (numPoints <= 1) return; } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased) { if (paintingDisabled()) return; if (numPoints <= 1) return; notImplemented(); }
170,422
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: fgetwln(FILE *stream, size_t *lenp) { struct filewbuf *fb; wint_t wc; size_t wused = 0; /* Try to diminish the possibility of several fgetwln() calls being * used on different streams, by using a pool of buffers per file. */ fb = &fb_pool[fb_pool_cur]; if (fb->fp != stream && fb->fp != NULL) { fb_pool_cur++; fb_pool_cur %= FILEWBUF_POOL_ITEMS; fb = &fb_pool[fb_pool_cur]; } fb->fp = stream; while ((wc = fgetwc(stream)) != WEOF) { if (!fb->len || wused > fb->len) { wchar_t *wp; if (fb->len) fb->len *= 2; else fb->len = FILEWBUF_INIT_LEN; wp = reallocarray(fb->wbuf, fb->len, sizeof(wchar_t)); if (wp == NULL) { wused = 0; break; } fb->wbuf = wp; } fb->wbuf[wused++] = wc; if (wc == L'\n') break; } *lenp = wused; return wused ? fb->wbuf : NULL; } Commit Message: CWE ID: CWE-119
fgetwln(FILE *stream, size_t *lenp) { struct filewbuf *fb; wint_t wc; size_t wused = 0; /* Try to diminish the possibility of several fgetwln() calls being * used on different streams, by using a pool of buffers per file. */ fb = &fb_pool[fb_pool_cur]; if (fb->fp != stream && fb->fp != NULL) { fb_pool_cur++; fb_pool_cur %= FILEWBUF_POOL_ITEMS; fb = &fb_pool[fb_pool_cur]; } fb->fp = stream; while ((wc = fgetwc(stream)) != WEOF) { if (!fb->len || wused >= fb->len) { wchar_t *wp; if (fb->len) fb->len *= 2; else fb->len = FILEWBUF_INIT_LEN; wp = reallocarray(fb->wbuf, fb->len, sizeof(wchar_t)); if (wp == NULL) { wused = 0; break; } fb->wbuf = wp; } fb->wbuf[wused++] = wc; if (wc == L'\n') break; } *lenp = wused; return wused ? fb->wbuf : NULL; }
165,350
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: SeekHead::SeekHead( Segment* pSegment, long long start, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_entries(0), m_entry_count(0), m_void_elements(0), m_void_element_count(0) { } 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
SeekHead::SeekHead( // Outermost (level 0) segment object has been constructed, // and pos designates start of payload. We need to find the // inner (level 1) elements. const long long header_status = ParseHeaders(); if (header_status < 0) // error return static_cast<long>(header_status); if (header_status > 0) // underflow return E_BUFFER_NOT_FULL; assert(m_pInfo); assert(m_pTracks); for (;;) { const int status = LoadCluster(); if (status < 0) // error return status; if (status >= 1) // no more clusters return 0; } }
174,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int snd_compr_allocate_buffer(struct snd_compr_stream *stream, struct snd_compr_params *params) { unsigned int buffer_size; void *buffer; buffer_size = params->buffer.fragment_size * params->buffer.fragments; if (stream->ops->copy) { buffer = NULL; /* if copy is defined the driver will be required to copy * the data from core */ } else { buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) return -ENOMEM; } stream->runtime->fragment_size = params->buffer.fragment_size; stream->runtime->fragments = params->buffer.fragments; stream->runtime->buffer = buffer; stream->runtime->buffer_size = buffer_size; return 0; } Commit Message: ALSA: compress_core: integer overflow in snd_compr_allocate_buffer() These are 32 bit values that come from the user, we need to check for integer overflows or we could end up allocating a smaller buffer than expected. Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID:
static int snd_compr_allocate_buffer(struct snd_compr_stream *stream, struct snd_compr_params *params) { unsigned int buffer_size; void *buffer; if (params->buffer.fragment_size == 0 || params->buffer.fragments > SIZE_MAX / params->buffer.fragment_size) return -EINVAL; buffer_size = params->buffer.fragment_size * params->buffer.fragments; if (stream->ops->copy) { buffer = NULL; /* if copy is defined the driver will be required to copy * the data from core */ } else { buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) return -ENOMEM; } stream->runtime->fragment_size = params->buffer.fragment_size; stream->runtime->fragments = params->buffer.fragments; stream->runtime->buffer = buffer; stream->runtime->buffer_size = buffer_size; return 0; }
167,610
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 crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; if (!name) return ERR_PTR(-ENOENT); mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD); type &= mask; alg = crypto_alg_lookup(name, type, mask); if (!alg) { request_module("%s", name); if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask & CRYPTO_ALG_NEED_FALLBACK)) request_module("%s-all", name); alg = crypto_alg_lookup(name, type, mask); } if (alg) return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg; return crypto_larval_add(name, type, mask); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <keescook@chromium.org> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-264
struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; if (!name) return ERR_PTR(-ENOENT); mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD); type &= mask; alg = crypto_alg_lookup(name, type, mask); if (!alg) { request_module("crypto-%s", name); if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask & CRYPTO_ALG_NEED_FALLBACK)) request_module("crypto-%s-all", name); alg = crypto_alg_lookup(name, type, mask); } if (alg) return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg; return crypto_larval_add(name, type, mask); }
166,839
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key()
167,055
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 *ch_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 17 && rdesc[11] == 0x3c && rdesc[12] == 0x02) { hid_info(hdev, "fixing up Cherry Cymotion report descriptor\n"); rdesc[11] = rdesc[16] = 0xff; rdesc[12] = rdesc[17] = 0x03; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: stable@vger.kernel.org Reported-by: Ben Hawkes <hawkes@google.com> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-119
static __u8 *ch_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 18 && rdesc[11] == 0x3c && rdesc[12] == 0x02) { hid_info(hdev, "fixing up Cherry Cymotion report descriptor\n"); rdesc[11] = rdesc[16] = 0xff; rdesc[12] = rdesc[17] = 0x03; } return rdesc; }
166,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileObject, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval); } else { RETVAL_BOOL(!php_stream_eof(intern->u.file.stream)); } } /* }}} */ /* {{{ proto string SplFileObject::fgets() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval); } else { RETVAL_BOOL(!php_stream_eof(intern->u.file.stream)); } } /* }}} */ /* {{{ proto string SplFileObject::fgets()
167,053
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 update_rate_histogram(struct rate_hist *hist, const vpx_codec_enc_cfg_t *cfg, const vpx_codec_cx_pkt_t *pkt) { int i; int64_t then = 0; int64_t avg_bitrate = 0; int64_t sum_sz = 0; const int64_t now = pkt->data.frame.pts * 1000 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den; int idx = hist->frames++ % hist->samples; hist->pts[idx] = now; hist->sz[idx] = (int)pkt->data.frame.sz; if (now < cfg->rc_buf_initial_sz) return; then = now; /* Sum the size over the past rc_buf_sz ms */ for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) { const int i_idx = (i - 1) % hist->samples; then = hist->pts[i_idx]; if (now - then > cfg->rc_buf_sz) break; sum_sz += hist->sz[i_idx]; } if (now == then) return; avg_bitrate = sum_sz * 8 * 1000 / (now - then); idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000)); if (idx < 0) idx = 0; if (idx > RATE_BINS - 1) idx = RATE_BINS - 1; if (hist->bucket[idx].low > avg_bitrate) hist->bucket[idx].low = (int)avg_bitrate; if (hist->bucket[idx].high < avg_bitrate) hist->bucket[idx].high = (int)avg_bitrate; hist->bucket[idx].count++; hist->total++; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void update_rate_histogram(struct rate_hist *hist, const vpx_codec_enc_cfg_t *cfg, const vpx_codec_cx_pkt_t *pkt) { int i; int64_t then = 0; int64_t avg_bitrate = 0; int64_t sum_sz = 0; const int64_t now = pkt->data.frame.pts * 1000 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den; int idx = hist->frames++ % hist->samples; hist->pts[idx] = now; hist->sz[idx] = (int)pkt->data.frame.sz; if (now < cfg->rc_buf_initial_sz) return; if (!cfg->rc_target_bitrate) return; then = now; /* Sum the size over the past rc_buf_sz ms */ for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) { const int i_idx = (i - 1) % hist->samples; then = hist->pts[i_idx]; if (now - then > cfg->rc_buf_sz) break; sum_sz += hist->sz[i_idx]; } if (now == then) return; avg_bitrate = sum_sz * 8 * 1000 / (now - then); idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000)); if (idx < 0) idx = 0; if (idx > RATE_BINS - 1) idx = RATE_BINS - 1; if (hist->bucket[idx].low > avg_bitrate) hist->bucket[idx].low = (int)avg_bitrate; if (hist->bucket[idx].high < avg_bitrate) hist->bucket[idx].high = (int)avg_bitrate; hist->bucket[idx].count++; hist->total++; }
174,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string SanitizeRemoteFrontendURL(const std::string& value) { GURL url(net::UnescapeURLComponent(value, net::UnescapeRule::SPACES | net::UnescapeRule::PATH_SEPARATORS | net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS | net::UnescapeRule::REPLACE_PLUS_WITH_SPACE)); std::string path = url.path(); std::vector<std::string> parts = base::SplitString( path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); std::string revision = parts.size() > 2 ? parts[2] : ""; revision = SanitizeRevision(revision); std::string filename = parts.size() ? parts[parts.size() - 1] : ""; if (filename != "devtools.html") filename = "inspector.html"; path = base::StringPrintf("/serve_rev/%s/%s", revision.c_str(), filename.c_str()); std::string sanitized = SanitizeFrontendURL(url, url::kHttpsScheme, kRemoteFrontendDomain, path, true).spec(); return net::EscapeQueryParamValue(sanitized, false); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeRemoteFrontendURL(const std::string& value) {
172,463
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 add_probe(const char *name) { struct module_entry *m; m = get_or_add_modentry(name); if (!(option_mask32 & (OPT_REMOVE | OPT_SHOW_DEPS)) && (m->flags & MODULE_FLAG_LOADED) && strncmp(m->modname, "symbol:", 7) == 0 ) { G.need_symbols = 1; } } Commit Message: CWE ID: CWE-20
static void add_probe(const char *name) { struct module_entry *m; /* * get_or_add_modentry() strips path from name and works * on remaining basename. * This would make "rmmod dir/name" and "modprobe dir/name" * to work like "rmmod name" and "modprobe name", * which is wrong, and can be abused via implicit modprobing: * "ifconfig /usbserial up" tries to modprobe netdev-/usbserial. */ if (strchr(name, '/')) bb_error_msg_and_die("malformed module name '%s'", name); m = get_or_add_modentry(name); if (!(option_mask32 & (OPT_REMOVE | OPT_SHOW_DEPS)) && (m->flags & MODULE_FLAG_LOADED) && strncmp(m->modname, "symbol:", 7) == 0 ) { G.need_symbols = 1; } }
165,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: MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) { assert(memory_info != (MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); if (memory_info->blob != (void *) NULL) switch (memory_info->type) { case AlignedVirtualMemory: { memory_info->blob=RelinquishAlignedMemory(memory_info->blob); RelinquishMagickResource(MemoryResource,memory_info->length); break; } case MapVirtualMemory: { (void) UnmapBlob(memory_info->blob,memory_info->length); memory_info->blob=NULL; RelinquishMagickResource(MapResource,memory_info->length); if (*memory_info->filename != '\0') (void) RelinquishUniqueFileResource(memory_info->filename); break; } case UnalignedVirtualMemory: default: { memory_info->blob=RelinquishMagickMemory(memory_info->blob); break; } } memory_info->signature=(~MagickSignature); memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info); return(memory_info); } Commit Message: CWE ID: CWE-189
MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) { assert(memory_info != (MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); if (memory_info->blob != (void *) NULL) switch (memory_info->type) { case AlignedVirtualMemory: { memory_info->blob=RelinquishAlignedMemory(memory_info->blob); RelinquishMagickResource(MemoryResource,memory_info->length); break; } case MapVirtualMemory: { (void) UnmapBlob(memory_info->blob,memory_info->length); memory_info->blob=NULL; RelinquishMagickResource(MapResource,memory_info->length); if (*memory_info->filename != '\0') { (void) RelinquishUniqueFileResource(memory_info->filename); RelinquishMagickResource(DiskResource,memory_info->length); } break; } case UnalignedVirtualMemory: default: { memory_info->blob=RelinquishMagickMemory(memory_info->blob); break; } } memory_info->signature=(~MagickSignature); memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info); return(memory_info); }
168,860
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 cJSON *create_reference( cJSON *item ) { cJSON *ref; if ( ! ( ref = cJSON_New_Item() ) ) return 0; memcpy( ref, item, sizeof(cJSON) ); ref->string = 0; ref->type |= cJSON_IsReference; ref->next = ref->prev = 0; return ref; } 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
static cJSON *create_reference( cJSON *item )
167,299
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 OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event, bool in_drag) { const ui::OSExchangeData& data = event.data(); if (data.HasURL()) { GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) { string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec()))); SetUserText(text); if (url.spec().length() == text.length()) model()->AcceptInput(CURRENT_TAB, true); return CopyOrLinkDragOperation(event.source_operations()); } } else if (data.HasString()) { int string_drop_position = drop_highlight_position(); string16 text; if ((string_drop_position != -1 || !in_drag) && data.GetString(&text)) { DCHECK(string_drop_position == -1 || ((string_drop_position >= 0) && (string_drop_position <= GetTextLength()))); if (in_drag) { if (event.source_operations()== ui::DragDropTypes::DRAG_MOVE) MoveSelectedText(string_drop_position); else InsertText(string_drop_position, text); } else { PasteAndGo(CollapseWhitespace(text, true)); } return CopyOrLinkDragOperation(event.source_operations()); } } return ui::DragDropTypes::DRAG_NONE; } Commit Message: Change omnibox behavior when stripping javascript schema to navigate after stripping the schema on drag drop. BUG=109245 TEST=N/A Review URL: http://codereview.chromium.org/9116016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116692 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
int OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event, bool in_drag) { const ui::OSExchangeData& data = event.data(); if (data.HasURL()) { GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) { string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec()))); SetUserText(text); model()->AcceptInput(CURRENT_TAB, true); return CopyOrLinkDragOperation(event.source_operations()); } } else if (data.HasString()) { int string_drop_position = drop_highlight_position(); string16 text; if ((string_drop_position != -1 || !in_drag) && data.GetString(&text)) { DCHECK(string_drop_position == -1 || ((string_drop_position >= 0) && (string_drop_position <= GetTextLength()))); if (in_drag) { if (event.source_operations()== ui::DragDropTypes::DRAG_MOVE) MoveSelectedText(string_drop_position); else InsertText(string_drop_position, text); } else { PasteAndGo(CollapseWhitespace(text, true)); } return CopyOrLinkDragOperation(event.source_operations()); } } return ui::DragDropTypes::DRAG_NONE; }
170,973
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: standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type, int bit_depth, unsigned int npalette, int interlace_type, png_uint_32 w, png_uint_32 h, int do_interlace) { pos = safecat(buffer, bufsize, pos, colour_types[colour_type]); if (npalette > 0) { pos = safecat(buffer, bufsize, pos, "["); pos = safecatn(buffer, bufsize, pos, npalette); pos = safecat(buffer, bufsize, pos, "]"); } pos = safecat(buffer, bufsize, pos, " "); pos = safecatn(buffer, bufsize, pos, bit_depth); pos = safecat(buffer, bufsize, pos, " bit"); if (interlace_type != PNG_INTERLACE_NONE) { pos = safecat(buffer, bufsize, pos, " interlaced"); if (do_interlace) pos = safecat(buffer, bufsize, pos, "(pngvalid)"); else pos = safecat(buffer, bufsize, pos, "(libpng)"); } if (w > 0 || h > 0) { pos = safecat(buffer, bufsize, pos, " "); pos = safecatn(buffer, bufsize, pos, w); pos = safecat(buffer, bufsize, pos, "x"); pos = safecatn(buffer, bufsize, pos, h); } 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:
standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type, int bit_depth, unsigned int npalette, int interlace_type, png_uint_32 w, png_uint_32 h, int do_interlace) { pos = safecat(buffer, bufsize, pos, colour_types[colour_type]); if (colour_type == 3) /* must have a palette */ { pos = safecat(buffer, bufsize, pos, "["); pos = safecatn(buffer, bufsize, pos, npalette); pos = safecat(buffer, bufsize, pos, "]"); } else if (npalette != 0) pos = safecat(buffer, bufsize, pos, "+tRNS"); pos = safecat(buffer, bufsize, pos, " "); pos = safecatn(buffer, bufsize, pos, bit_depth); pos = safecat(buffer, bufsize, pos, " bit"); if (interlace_type != PNG_INTERLACE_NONE) { pos = safecat(buffer, bufsize, pos, " interlaced"); if (do_interlace) pos = safecat(buffer, bufsize, pos, "(pngvalid)"); else pos = safecat(buffer, bufsize, pos, "(libpng)"); } if (w > 0 || h > 0) { pos = safecat(buffer, bufsize, pos, " "); pos = safecatn(buffer, bufsize, pos, w); pos = safecat(buffer, bufsize, pos, "x"); pos = safecatn(buffer, bufsize, pos, h); } return pos; }
173,700
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 store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Error: invalid .Xauthority file\n"); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); if (chown(dest, getuid(), getgid()) == -1) errExit("fchown"); if (chmod(dest, 0600) == -1) errExit("fchmod"); return 1; // file copied } return 0; } Commit Message: security fix CWE ID: CWE-269
static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; // create an empty file as root, and change ownership to user FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Warning: invalid .Xauthority file\n"); return 0; } copy_file_as_user(src, dest, getuid(), getgid(), 0600); // regular user fs_logger2("clone", dest); return 1; // file copied } return 0; }
170,100
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::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() { return &shutdown_event_; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() {
170,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: static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long datalen; datalen = parse_iv2((*p) + 2, p); (*p) += 2; if (datalen < 0 || (*p) + datalen >= max) { zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p))); return 0; } if (ce->unserialize == NULL) { zend_error(E_WARNING, "Class %s has no unserializer", ce->name); object_init_ex(*rval, ce); } else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) { return 0; } (*p) += datalen; return finish_nested_data(UNSERIALIZE_PASSTHRU); } Commit Message: CWE ID: CWE-189
static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long datalen; datalen = parse_iv2((*p) + 2, p); (*p) += 2; if (datalen < 0 || (max - (*p)) <= datalen) { zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p))); return 0; } if (ce->unserialize == NULL) { zend_error(E_WARNING, "Class %s has no unserializer", ce->name); object_init_ex(*rval, ce); } else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) { return 0; } (*p) += datalen; return finish_nested_data(UNSERIALIZE_PASSTHRU); }
165,149
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 TranslateInfoBarDelegate::IsTranslatableLanguageByPrefs() { Profile* profile = Profile::FromBrowserContext(GetWebContents()->GetBrowserContext()); Profile* original_profile = profile->GetOriginalProfile(); scoped_ptr<TranslatePrefs> translate_prefs( TranslateTabHelper::CreateTranslatePrefs(original_profile->GetPrefs())); TranslateAcceptLanguages* accept_languages = TranslateTabHelper::GetTranslateAcceptLanguages(original_profile); return translate_prefs->CanTranslateLanguage(accept_languages, original_language_code()); } Commit Message: Remove dependency of TranslateInfobarDelegate on profile This CL uses TranslateTabHelper instead of Profile and also cleans up some unused code and irrelevant dependencies. BUG=371845 Review URL: https://codereview.chromium.org/286973003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@270758 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
bool TranslateInfoBarDelegate::IsTranslatableLanguageByPrefs() { TranslateTabHelper* translate_tab_helper = TranslateTabHelper::FromWebContents(GetWebContents()); scoped_ptr<TranslatePrefs> translate_prefs( TranslateTabHelper::CreateTranslatePrefs( translate_tab_helper->GetPrefs())); TranslateAcceptLanguages* accept_languages = translate_tab_helper->GetTranslateAcceptLanguages(); return translate_prefs->CanTranslateLanguage(accept_languages, original_language_code()); }
171,174
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { SEPARATE_ZVAL(var2); convert_to_double(*var2); matrix[i][j] = (float)Z_DVAL_PP(var2); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189
PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { if (Z_TYPE_PP(var2) != IS_DOUBLE) { zval dval; dval = **var; zval_copy_ctor(&dval); convert_to_double(&dval); matrix[i][j] = (float)Z_DVAL(dval); } else { matrix[i][j] = (float)Z_DVAL_PP(var2); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } }
166,426
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 char *string_of_NPPVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPPVpluginNameString); _(NPPVpluginDescriptionString); _(NPPVpluginWindowBool); _(NPPVpluginTransparentBool); _(NPPVjavaClass); _(NPPVpluginWindowSize); _(NPPVpluginTimerInterval); _(NPPVpluginScriptableInstance); _(NPPVpluginScriptableIID); _(NPPVjavascriptPushCallerBool); _(NPPVpluginKeepLibraryInMemory); _(NPPVpluginNeedsXEmbed); _(NPPVpluginScriptableNPObject); _(NPPVformValue); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPPVpluginScriptableInstance); #undef _ default: str = "<unknown variable>"; break; } break; } return str; } Commit Message: Support all the new variables added CWE ID: CWE-264
const char *string_of_NPPVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPPVpluginNameString); _(NPPVpluginDescriptionString); _(NPPVpluginWindowBool); _(NPPVpluginTransparentBool); _(NPPVjavaClass); _(NPPVpluginWindowSize); _(NPPVpluginTimerInterval); _(NPPVpluginScriptableInstance); _(NPPVpluginScriptableIID); _(NPPVjavascriptPushCallerBool); _(NPPVpluginKeepLibraryInMemory); _(NPPVpluginNeedsXEmbed); _(NPPVpluginScriptableNPObject); _(NPPVformValue); _(NPPVpluginUrlRequestsDisplayedBool); _(NPPVpluginWantsAllNetworkStreams); _(NPPVpluginNativeAccessibleAtkPlugId); _(NPPVpluginCancelSrcStream); _(NPPVSupportsAdvancedKeyHandling); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPPVpluginScriptableInstance); #undef _ default: str = "<unknown variable>"; break; } break; } return str; }
165,866
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 BnCrypto::readVector(const Parcel &data, Vector<uint8_t> &vector) const { uint32_t size = data.readInt32(); vector.insertAt((size_t)0, size); data.read(vector.editArray(), size); } Commit Message: Fix information disclosure in mediadrmserver Test:POC provided in bug Bug:79218474 Change-Id: Iba12c07a5e615f8ed234b01ac53e3559ba9ac12e (cherry picked from commit c1bf68a8d1321d7cdf7da6933f0b89b171d251c6) CWE ID: CWE-200
void BnCrypto::readVector(const Parcel &data, Vector<uint8_t> &vector) const { uint32_t size = data.readInt32(); if (vector.insertAt((size_t)0, size) < 0) { vector.clear(); } if (data.read(vector.editArray(), size) != NO_ERROR) { vector.clear(); android_errorWriteWithInfoLog(0x534e4554, "62872384", -1, NULL, 0); } }
174,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int vfs_open(const struct path *path, struct file *file, const struct cred *cred) { struct dentry *dentry = path->dentry; struct inode *inode = dentry->d_inode; file->f_path = *path; if (dentry->d_flags & DCACHE_OP_SELECT_INODE) { inode = dentry->d_op->d_select_inode(dentry, file->f_flags); if (IS_ERR(inode)) return PTR_ERR(inode); } return do_dentry_open(file, inode, NULL, cred); } Commit Message: vfs: add vfs_select_inode() helper Signed-off-by: Miklos Szeredi <mszeredi@redhat.com> Cc: <stable@vger.kernel.org> # v4.2+ CWE ID: CWE-284
int vfs_open(const struct path *path, struct file *file, const struct cred *cred) { struct inode *inode = vfs_select_inode(path->dentry, file->f_flags); if (IS_ERR(inode)) return PTR_ERR(inode); file->f_path = *path; return do_dentry_open(file, inode, NULL, cred); }
169,943
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 parse_video_info(AVIOContext *pb, AVStream *st) { uint16_t size_asf; // ASF-specific Format Data size uint32_t size_bmp; // BMP_HEADER-specific Format Data size unsigned int tag; st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); avio_skip(pb, 1); // skip reserved flags size_asf = avio_rl16(pb); tag = ff_get_bmp_header(pb, st, &size_bmp); st->codecpar->codec_tag = tag; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag); size_bmp = FFMAX(size_asf, size_bmp); if (size_bmp > BMP_HEADER_SIZE) { int ret; st->codecpar->extradata_size = size_bmp - BMP_HEADER_SIZE; if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE))) { st->codecpar->extradata_size = 0; return AVERROR(ENOMEM); } memset(st->codecpar->extradata + st->codecpar->extradata_size , 0, AV_INPUT_BUFFER_PADDING_SIZE); if ((ret = avio_read(pb, st->codecpar->extradata, st->codecpar->extradata_size)) < 0) return ret; } return 0; } Commit Message: avformat/asfdec_o: Check size_bmp more fully Fixes: integer overflow and out of array access Fixes: asfo-crash-46080c4341572a7137a162331af77f6ded45cbd7 Found-by: Paul Ch <paulcher@icloud.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static int parse_video_info(AVIOContext *pb, AVStream *st) { uint16_t size_asf; // ASF-specific Format Data size uint32_t size_bmp; // BMP_HEADER-specific Format Data size unsigned int tag; st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); avio_skip(pb, 1); // skip reserved flags size_asf = avio_rl16(pb); tag = ff_get_bmp_header(pb, st, &size_bmp); st->codecpar->codec_tag = tag; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag); size_bmp = FFMAX(size_asf, size_bmp); if (size_bmp > BMP_HEADER_SIZE && size_bmp < INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) { int ret; st->codecpar->extradata_size = size_bmp - BMP_HEADER_SIZE; if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE))) { st->codecpar->extradata_size = 0; return AVERROR(ENOMEM); } memset(st->codecpar->extradata + st->codecpar->extradata_size , 0, AV_INPUT_BUFFER_PADDING_SIZE); if ((ret = avio_read(pb, st->codecpar->extradata, st->codecpar->extradata_size)) < 0) return ret; } return 0; }
168,926
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void SetUp() { vp9_worker_init(&worker_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { vpx_get_worker_interface()->init(&worker_); }
174,599
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 WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host, const base::string16& message, const base::string16& default_prompt, const GURL& frame_url, JavaScriptDialogType dialog_type, IPC::Message* reply_msg) { bool suppress_this_message = ShowingInterstitialPage() || !delegate_ || delegate_->ShouldSuppressDialogs(this) || !delegate_->GetJavaScriptDialogManager(this); if (!suppress_this_message) { is_showing_javascript_dialog_ = true; dialog_manager_ = delegate_->GetJavaScriptDialogManager(this); dialog_manager_->RunJavaScriptDialog( this, frame_url, dialog_type, message, default_prompt, base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, false), &suppress_this_message); } if (suppress_this_message) { OnDialogClosed(render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, true, false, base::string16()); } } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20
void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host, const base::string16& message, const base::string16& default_prompt, const GURL& frame_url, JavaScriptDialogType dialog_type, IPC::Message* reply_msg) { // Running a dialog causes an exit to webpage-initiated fullscreen. // http://crbug.com/728276 if (IsFullscreenForCurrentTab()) ExitFullscreen(true); bool suppress_this_message = ShowingInterstitialPage() || !delegate_ || delegate_->ShouldSuppressDialogs(this) || !delegate_->GetJavaScriptDialogManager(this); if (!suppress_this_message) { is_showing_javascript_dialog_ = true; dialog_manager_ = delegate_->GetJavaScriptDialogManager(this); dialog_manager_->RunJavaScriptDialog( this, frame_url, dialog_type, message, default_prompt, base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, false), &suppress_this_message); } if (suppress_this_message) { OnDialogClosed(render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, true, false, base::string16()); } }
172,316
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 LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) { clock_for_test_ = std::move(clock); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <sdefresne@chromium.org> Reviewed-by: Marc Treib <treib@chromium.org> Commit-Queue: Chris Pickel <sfiera@chromium.org> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) {
171,959
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: exit_ext2_xattr(void) { mb_cache_destroy(ext2_xattr_cache); } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
exit_ext2_xattr(void) void ext2_xattr_destroy_cache(struct mb2_cache *cache) { if (cache) mb2_cache_destroy(cache); }
169,976
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 MaybeRestoreConnections() { if (IBusConnectionsAreAlive()) { return; } MaybeCreateIBus(); MaybeRestoreIBusConfig(); if (IBusConnectionsAreAlive()) { ConnectPanelServiceSignals(); if (connection_change_handler_) { LOG(INFO) << "Notifying Chrome that IBus is ready."; connection_change_handler_(language_library_, true); } } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MaybeRestoreConnections() { if (IBusConnectionsAreAlive()) { return; } MaybeCreateIBus(); MaybeRestoreIBusConfig(); if (IBusConnectionsAreAlive()) { ConnectPanelServiceSignals(); VLOG(1) << "Notifying Chrome that IBus is ready."; FOR_EACH_OBSERVER(Observer, observers_, OnConnectionChange(true)); } }
170,542
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 vp8_decoder_remove_threads(VP8D_COMP *pbi) { /* shutdown MB Decoding thread; */ if (pbi->b_multithreaded_rd) { int i; pbi->b_multithreaded_rd = 0; /* allow all threads to exit */ for (i = 0; i < pbi->allocated_decoding_thread_count; i++) { sem_post(&pbi->h_event_start_decoding[i]); pthread_join(pbi->h_decoding_thread[i], NULL); } for (i = 0; i < pbi->allocated_decoding_thread_count; i++) { sem_destroy(&pbi->h_event_start_decoding[i]); } sem_destroy(&pbi->h_event_end_decoding); vpx_free(pbi->h_decoding_thread); pbi->h_decoding_thread = NULL; vpx_free(pbi->h_event_start_decoding); pbi->h_event_start_decoding = NULL; vpx_free(pbi->mb_row_di); pbi->mb_row_di = NULL ; vpx_free(pbi->de_thread_data); pbi->de_thread_data = NULL; } } Commit Message: vp8:fix threading issues 1 - stops de allocating before threads are closed. 2 - limits threads to mb_rows when mb_rows < partitions BUG=webm:851 Bug: 30436808 Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b (cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e) CWE ID:
void vp8_decoder_remove_threads(VP8D_COMP *pbi) void vp8_decoder_remove_threads(VP8D_COMP *pbi) { /* shutdown MB Decoding thread; */ if (pbi->b_multithreaded_rd) { int i; pbi->b_multithreaded_rd = 0; /* allow all threads to exit */ for (i = 0; i < pbi->allocated_decoding_thread_count; ++i) { sem_post(&pbi->h_event_start_decoding[i]); pthread_join(pbi->h_decoding_thread[i], NULL); } for (i = 0; i < pbi->allocated_decoding_thread_count; ++i) { sem_destroy(&pbi->h_event_start_decoding[i]); } sem_destroy(&pbi->h_event_end_decoding); vpx_free(pbi->h_decoding_thread); pbi->h_decoding_thread = NULL; vpx_free(pbi->h_event_start_decoding); pbi->h_event_start_decoding = NULL; vpx_free(pbi->mb_row_di); pbi->mb_row_di = NULL; vpx_free(pbi->de_thread_data); pbi->de_thread_data = NULL; vp8mt_de_alloc_temp_buffers(pbi, pbi->common.mb_rows); } }
174,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: void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) { cached_width_ = width; cached_height_ = height; gl_->ResizeCHROMIUM(width, height); #ifdef FLIP_FRAMEBUFFER_VERTICALLY scanline_.reset(new uint8[width * 4]); #endif // FLIP_FRAMEBUFFER_VERTICALLY } Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip. BUG=116637 TEST=manual test from bug report with ASAN Review URL: https://chromiumcodereview.appspot.com/9617038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) { cached_width_ = width; cached_height_ = height; gl_->ResizeCHROMIUM(width, height); }
171,064
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 SandboxIPCHandler::HandleLocaltime( int fd, base::PickleIterator iter, const std::vector<base::ScopedFD>& fds) { std::string time_string; if (!iter.ReadString(&time_string) || time_string.size() != sizeof(time_t)) return; time_t time; memcpy(&time, time_string.data(), sizeof(time)); const struct tm* expanded_time = localtime(&time); std::string result_string; const char* time_zone_string = ""; if (expanded_time) { result_string = std::string(reinterpret_cast<const char*>(expanded_time), sizeof(struct tm)); time_zone_string = expanded_time->tm_zone; } base::Pickle reply; reply.WriteString(result_string); reply.WriteString(time_zone_string); SendRendererReply(fds, reply, -1); } Commit Message: Serialize struct tm in a safe way. BUG=765512 Change-Id: If235b8677eb527be2ac0fe621fc210e4116a7566 Reviewed-on: https://chromium-review.googlesource.com/679441 Commit-Queue: Chris Palmer <palmer@chromium.org> Reviewed-by: Julien Tinnes <jln@chromium.org> Cr-Commit-Position: refs/heads/master@{#503948} CWE ID: CWE-119
void SandboxIPCHandler::HandleLocaltime( int fd, base::PickleIterator iter, const std::vector<base::ScopedFD>& fds) { // The other side of this call is in |ProxyLocaltimeCallToBrowser|, in // zygote_main_linux.cc. std::string time_string; if (!iter.ReadString(&time_string) || time_string.size() != sizeof(time_t)) return; time_t time; memcpy(&time, time_string.data(), sizeof(time)); // We use |localtime| here because we need the |tm_zone| field to be filled const struct tm* expanded_time = localtime(&time); base::Pickle reply; if (expanded_time) { WriteTimeStruct(&reply, expanded_time); } else { // The {} constructor ensures the struct is 0-initialized. struct tm zeroed_time = {}; WriteTimeStruct(&reply, &zeroed_time); } SendRendererReply(fds, reply, -1); }
172,925
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 __f2fs_set_acl(struct inode *inode, int type, struct posix_acl *acl, struct page *ipage) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; set_acl_inode(inode, inode->i_mode); if (error == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = f2fs_acl_to_disk(acl, &size); if (IS_ERR(value)) { clear_inode_flag(inode, FI_ACL_MODE); return (int)PTR_ERR(value); } } error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); clear_inode_flag(inode, FI_ACL_MODE); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
static int __f2fs_set_acl(struct inode *inode, int type, struct posix_acl *acl, struct page *ipage) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; set_acl_inode(inode, inode->i_mode); } break; case ACL_TYPE_DEFAULT: name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = f2fs_acl_to_disk(acl, &size); if (IS_ERR(value)) { clear_inode_flag(inode, FI_ACL_MODE); return (int)PTR_ERR(value); } } error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); clear_inode_flag(inode, FI_ACL_MODE); return error; }
166,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: base::WeakPtr<OTRBrowserContextImpl> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } Commit Message: CWE ID: CWE-20
base::WeakPtr<OTRBrowserContextImpl> GetWeakPtr() {
165,415
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 toggle_os_keylockstates(int fd, int changedlockstates) { BTIF_TRACE_EVENT("%s: fd = %d, changedlockstates = 0x%x", __FUNCTION__, fd, changedlockstates); UINT8 hidreport[9]; int reportIndex; memset(hidreport,0,9); hidreport[0]=1; reportIndex=4; if (changedlockstates & BTIF_HH_KEYSTATE_MASK_CAPSLOCK) { BTIF_TRACE_DEBUG("%s Setting CAPSLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8)HID_REPORT_CAPSLOCK; } if (changedlockstates & BTIF_HH_KEYSTATE_MASK_NUMLOCK) { BTIF_TRACE_DEBUG("%s Setting NUMLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8)HID_REPORT_NUMLOCK; } if (changedlockstates & BTIF_HH_KEYSTATE_MASK_SCROLLLOCK) { BTIF_TRACE_DEBUG("%s Setting SCROLLLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8) HID_REPORT_SCROLLLOCK; } BTIF_TRACE_DEBUG("Writing hidreport #1 to os: "\ "%s: %x %x %x", __FUNCTION__, hidreport[0], hidreport[1], hidreport[2]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[3], hidreport[4], hidreport[5]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[6], hidreport[7], hidreport[8]); bta_hh_co_write(fd , hidreport, sizeof(hidreport)); usleep(200000); memset(hidreport,0,9); hidreport[0]=1; BTIF_TRACE_DEBUG("Writing hidreport #2 to os: "\ "%s: %x %x %x", __FUNCTION__, hidreport[0], hidreport[1], hidreport[2]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[3], hidreport[4], hidreport[5]); BTIF_TRACE_DEBUG("%s: %x %x %x ", __FUNCTION__, hidreport[6], hidreport[7], hidreport[8]); bta_hh_co_write(fd , hidreport, sizeof(hidreport)); } 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 toggle_os_keylockstates(int fd, int changedlockstates) { BTIF_TRACE_EVENT("%s: fd = %d, changedlockstates = 0x%x", __FUNCTION__, fd, changedlockstates); UINT8 hidreport[9]; int reportIndex; memset(hidreport,0,9); hidreport[0]=1; reportIndex=4; if (changedlockstates & BTIF_HH_KEYSTATE_MASK_CAPSLOCK) { BTIF_TRACE_DEBUG("%s Setting CAPSLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8)HID_REPORT_CAPSLOCK; } if (changedlockstates & BTIF_HH_KEYSTATE_MASK_NUMLOCK) { BTIF_TRACE_DEBUG("%s Setting NUMLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8)HID_REPORT_NUMLOCK; } if (changedlockstates & BTIF_HH_KEYSTATE_MASK_SCROLLLOCK) { BTIF_TRACE_DEBUG("%s Setting SCROLLLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8) HID_REPORT_SCROLLLOCK; } BTIF_TRACE_DEBUG("Writing hidreport #1 to os: "\ "%s: %x %x %x", __FUNCTION__, hidreport[0], hidreport[1], hidreport[2]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[3], hidreport[4], hidreport[5]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[6], hidreport[7], hidreport[8]); bta_hh_co_write(fd , hidreport, sizeof(hidreport)); TEMP_FAILURE_RETRY(usleep(200000)); memset(hidreport,0,9); hidreport[0]=1; BTIF_TRACE_DEBUG("Writing hidreport #2 to os: "\ "%s: %x %x %x", __FUNCTION__, hidreport[0], hidreport[1], hidreport[2]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[3], hidreport[4], hidreport[5]); BTIF_TRACE_DEBUG("%s: %x %x %x ", __FUNCTION__, hidreport[6], hidreport[7], hidreport[8]); bta_hh_co_write(fd , hidreport, sizeof(hidreport)); }
173,438
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 btif_av_event_free_data(btif_sm_event_t event, void* p_data) { switch (event) { case BTA_AV_META_MSG_EVT: { tBTA_AV* av = (tBTA_AV*)p_data; osi_free_and_reset((void**)&av->meta_msg.p_data); if (av->meta_msg.p_msg) { if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) { osi_free(av->meta_msg.p_msg->vendor.p_vendor_data); } osi_free_and_reset((void**)&av->meta_msg.p_msg); } } break; default: break; } } Commit Message: DO NOT MERGE AVRC: Copy browse.p_browse_data in btif_av_event_deep_copy p_msg_src->browse.p_browse_data is not copied, but used after the original pointer is freed Bug: 109699112 Test: manual Change-Id: I1d014eb9a8911da6913173a9b11218bf1c89e16e (cherry picked from commit 1d9a58768e6573899c7e80c2b3f52e22f2d8f58b) CWE ID: CWE-416
static void btif_av_event_free_data(btif_sm_event_t event, void* p_data) { switch (event) { case BTA_AV_META_MSG_EVT: { tBTA_AV* av = (tBTA_AV*)p_data; osi_free_and_reset((void**)&av->meta_msg.p_data); if (av->meta_msg.p_msg) { if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) { osi_free(av->meta_msg.p_msg->vendor.p_vendor_data); } if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_BROWSE) { osi_free(av->meta_msg.p_msg->browse.p_browse_data); } osi_free_and_reset((void**)&av->meta_msg.p_msg); } } break; default: break; } }
174,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); content::SetContentClient(old_client_); }
171,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void SocketStreamDispatcherHost::OnSSLCertificateError( net::SocketStream* socket, const net::SSLInfo& ssl_info, bool fatal) { int socket_id = SocketStreamHost::SocketIdFromSocketStream(socket); DVLOG(1) << "SocketStreamDispatcherHost::OnSSLCertificateError socket_id=" << socket_id; if (socket_id == content::kNoSocketId) { LOG(ERROR) << "NoSocketId in OnSSLCertificateError"; return; } SocketStreamHost* socket_stream_host = hosts_.Lookup(socket_id); DCHECK(socket_stream_host); content::GlobalRequestID request_id(-1, socket_id); SSLManager::OnSSLCertificateError(ssl_delegate_weak_factory_.GetWeakPtr(), request_id, ResourceType::SUB_RESOURCE, socket->url(), render_process_id_, socket_stream_host->render_view_id(), ssl_info, fatal); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void SocketStreamDispatcherHost::OnSSLCertificateError( net::SocketStream* socket, const net::SSLInfo& ssl_info, bool fatal) { int socket_id = SocketStreamHost::SocketIdFromSocketStream(socket); DVLOG(1) << "SocketStreamDispatcherHost::OnSSLCertificateError socket_id=" << socket_id; if (socket_id == content::kNoSocketId) { LOG(ERROR) << "NoSocketId in OnSSLCertificateError"; return; } SocketStreamHost* socket_stream_host = hosts_.Lookup(socket_id); DCHECK(socket_stream_host); content::GlobalRequestID request_id(-1, socket_id); SSLManager::OnSSLCertificateError( AsWeakPtr(), request_id, ResourceType::SUB_RESOURCE, socket->url(), render_process_id_, socket_stream_host->render_view_id(), ssl_info, fatal); }
170,992
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 TabGroupHeader::OnPaint(gfx::Canvas* canvas) { constexpr SkColor kPlaceholderColor = SkColorSetRGB(0xAA, 0xBB, 0xCC); gfx::Rect fill_bounds(GetLocalBounds()); fill_bounds.Inset(TabStyle::GetTabOverlap(), 0); canvas->FillRect(fill_bounds, kPlaceholderColor); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
void TabGroupHeader::OnPaint(gfx::Canvas* canvas) { gfx::Rect fill_bounds(GetLocalBounds()); fill_bounds.Inset(TabStyle::GetTabOverlap(), 0); const SkColor color = GetGroupData()->color(); canvas->FillRect(fill_bounds, color); title_label_->SetBackgroundColor(color); } const TabGroupData* TabGroupHeader::GetGroupData() { return controller_->GetDataForGroup(group_); }
172,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: ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { ULONG tcpipDataAt; tTcpIpPacketParsingResult res = _res; tcpipDataAt = ipHeaderSize + sizeof(TCPHeader); res.xxpStatus = ppresXxpIncomplete; res.TcpUdp = ppresIsTCP; if (len >= tcpipDataAt) { TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); res.xxpStatus = ppresXxpKnown; tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader); res.XxpIpHeaderSize = tcpipDataAt; } else { DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt)); } return res; } Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <yhindin@rehat.com> CWE ID: CWE-20
ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { ULONG tcpipDataAt; tTcpIpPacketParsingResult res = _res; tcpipDataAt = ipHeaderSize + sizeof(TCPHeader); res.TcpUdp = ppresIsTCP; if (len >= tcpipDataAt) { TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); res.xxpStatus = ppresXxpKnown; res.xxpFull = TRUE; tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader); res.XxpIpHeaderSize = tcpipDataAt; } else { DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt)); res.xxpFull = FALSE; res.xxpStatus = ppresXxpIncomplete; } return res; }
168,889
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 initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder) { RELEASE_ASSERT(!holder.IsEmpty()); RELEASE_ASSERT(holder->IsObject()); v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder); v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Context> context = scriptState->context(); auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate); if (privateIsInitialized.hasValue(context, holderObject)) return; // Already initialized. v8::TryCatch block(isolate); v8::Local<v8::Value> initializeFunction; if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) { v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(initializeFunction), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) { fprintf(stderr, "Private script error: Object constructor threw an exception.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } } if (classObject->GetPrototype() != holderObject->GetPrototype()) { if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) { fprintf(stderr, "Private script error: SetPrototype failed.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } } if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) { fprintf(stderr, "Private script error: SetPrototype failed.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate)); } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79
static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder) { RELEASE_ASSERT(!holder.IsEmpty()); RELEASE_ASSERT(holder->IsObject()); v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder); v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Context> context = scriptState->context(); auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate); if (privateIsInitialized.hasValue(context, holderObject)) return; // Already initialized. v8::TryCatch block(isolate); v8::Local<v8::Value> initializeFunction; if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) { v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(initializeFunction), holder, 0, 0, isolate).ToLocal(&result)) { fprintf(stderr, "Private script error: Object constructor threw an exception.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } } if (classObject->GetPrototype() != holderObject->GetPrototype()) { if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) { fprintf(stderr, "Private script error: SetPrototype failed.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } } if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) { fprintf(stderr, "Private script error: SetPrototype failed.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate)); }
172,074
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 ShowExtensionInstallDialogImpl( ExtensionInstallPromptShowParams* show_params, ExtensionInstallPrompt::Delegate* delegate, scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ExtensionInstallDialogView* dialog = new ExtensionInstallDialogView(show_params->profile(), show_params->GetParentWebContents(), delegate, prompt); constrained_window::CreateBrowserModalDialogViews( dialog, show_params->GetParentWindow())->Show(); } Commit Message: Make the webstore inline install dialog be tab-modal Also clean up a few minor lint errors while I'm in here. BUG=550047 Review URL: https://codereview.chromium.org/1496033003 Cr-Commit-Position: refs/heads/master@{#363925} CWE ID: CWE-17
void ShowExtensionInstallDialogImpl( ExtensionInstallPromptShowParams* show_params, ExtensionInstallPrompt::Delegate* delegate, scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ExtensionInstallDialogView* dialog = new ExtensionInstallDialogView(show_params->profile(), show_params->GetParentWebContents(), delegate, prompt); if (prompt->ShouldUseTabModalDialog()) { content::WebContents* parent_web_contents = show_params->GetParentWebContents(); if (parent_web_contents) constrained_window::ShowWebModalDialogViews(dialog, parent_web_contents); } else { constrained_window::CreateBrowserModalDialogViews( dialog, show_params->GetParentWindow()) ->Show(); } }
172,208
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 test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119
void test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded, sizeof(buffer)); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } }
169,130
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 NuMediaExtractor::getTotalBitrate(int64_t *bitrate) const { if (mTotalBitrate >= 0) { *bitrate = mTotalBitrate; return true; } off64_t size; if (mDurationUs >= 0 && mDataSource->getSize(&size) == OK) { *bitrate = size * 8000000ll / mDurationUs; // in bits/sec return true; } return false; } Commit Message: Fix integer overflow and divide-by-zero Bug: 35763994 Test: ran CTS with and without fix Change-Id: If835e97ce578d4fa567e33e349e48fb7b2559e0e (cherry picked from commit 8538a603ef992e75f29336499cb783f3ec19f18c) CWE ID: CWE-190
bool NuMediaExtractor::getTotalBitrate(int64_t *bitrate) const { if (mTotalBitrate >= 0) { *bitrate = mTotalBitrate; return true; } off64_t size; if (mDurationUs > 0 && mDataSource->getSize(&size) == OK) { *bitrate = size * 8000000ll / mDurationUs; // in bits/sec return true; } return false; }
174,003
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::OnInitiatePrintPreview(bool selection_only) { blink::WebLocalFrame* frame = NULL; GetPrintFrame(&frame); DCHECK(frame); auto plugin = delegate_->GetPdfElement(frame); if (!plugin.isNull()) { PrintNode(plugin); return; } print_preview_context_.InitWithFrame(frame); RequestPrintPreview(selection_only ? PRINT_PREVIEW_USER_INITIATED_SELECTION : PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME); } 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::OnInitiatePrintPreview(bool selection_only) { CHECK_LE(ipc_nesting_level_, 1); blink::WebLocalFrame* frame = NULL; GetPrintFrame(&frame); DCHECK(frame); auto plugin = delegate_->GetPdfElement(frame); if (!plugin.isNull()) { PrintNode(plugin); return; } print_preview_context_.InitWithFrame(frame); RequestPrintPreview(selection_only ? PRINT_PREVIEW_USER_INITIATED_SELECTION : PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME); }
171,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: static double pcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* Percentage error permitted in the linear values. Note that the specified * value is a percentage but this routine returns a simple number. */ if (pm->assume_16_bit_calculations || (pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxpc16 * .01; else return pm->maxpc8 * .01; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double pcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double pcerr(const png_modifier *pm, int in_depth, int out_depth) { /* Percentage error permitted in the linear values. Note that the specified * value is a percentage but this routine returns a simple number. */ if (pm->assume_16_bit_calculations || (pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxpc16 * .01; else return pm->maxpc8 * .01; }
173,677
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string TestFlashMessageLoop::TestRunWithoutQuit() { message_loop_ = new pp::flash::MessageLoop(instance_); pp::CompletionCallback callback = callback_factory_.NewCallback( &TestFlashMessageLoop::DestroyMessageLoopResourceTask); pp::Module::Get()->core()->CallOnMainThread(0, callback); int32_t result = message_loop_->Run(); if (message_loop_) { delete message_loop_; message_loop_ = NULL; ASSERT_TRUE(false); } ASSERT_EQ(PP_ERROR_ABORTED, result); PASS(); } Commit Message: Fix PPB_Flash_MessageLoop. This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop. BUG=569496 Review URL: https://codereview.chromium.org/1559113002 Cr-Commit-Position: refs/heads/master@{#374529} CWE ID: CWE-264
std::string TestFlashMessageLoop::TestRunWithoutQuit() { message_loop_ = new pp::flash::MessageLoop(instance_); pp::CompletionCallback callback = callback_factory_.NewCallback( &TestFlashMessageLoop::DestroyMessageLoopResourceTask); pp::Module::Get()->core()->CallOnMainThread(0, callback); int32_t result = message_loop_->Run(); if (message_loop_) { delete message_loop_; message_loop_ = nullptr; ASSERT_TRUE(false); } ASSERT_EQ(PP_ERROR_ABORTED, result); PASS(); }
172,128
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: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = (x >> 56) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { psf->header.ptr [psf->header.indx++] = (x >> 56) ; psf->header.ptr [psf->header.indx++] = (x >> 48) ; psf->header.ptr [psf->header.indx++] = (x >> 40) ; psf->header.ptr [psf->header.indx++] = (x >> 32) ; psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_8byte */
170,050
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 xfrm6_tunnel_rcv(struct sk_buff *skb) { struct ipv6hdr *iph = ipv6_hdr(skb); __be32 spi; spi = xfrm6_tunnel_spi_lookup((xfrm_address_t *)&iph->saddr); return xfrm6_rcv_spi(skb, spi); } Commit Message: [IPV6]: Fix slab corruption running ip6sic From: Eric Sesterhenn <snakebyte@gmx.de> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static int xfrm6_tunnel_rcv(struct sk_buff *skb) { struct ipv6hdr *iph = ipv6_hdr(skb); __be32 spi; spi = xfrm6_tunnel_spi_lookup((xfrm_address_t *)&iph->saddr); return xfrm6_rcv_spi(skb, spi) > 0 ? : 0; }
165,622
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 ASessionDescription::getFormatType( size_t index, unsigned long *PT, AString *desc, AString *params) const { AString format; getFormat(index, &format); const char *lastSpacePos = strrchr(format.c_str(), ' '); CHECK(lastSpacePos != NULL); char *end; unsigned long x = strtoul(lastSpacePos + 1, &end, 10); CHECK_GT(end, lastSpacePos + 1); CHECK_EQ(*end, '\0'); *PT = x; char key[20]; sprintf(key, "a=rtpmap:%lu", x); CHECK(findAttribute(index, key, desc)); sprintf(key, "a=fmtp:%lu", x); if (!findAttribute(index, key, params)) { params->clear(); } } Commit Message: Fix corruption via buffer overflow in mediaserver change unbound sprintf() to snprintf() so network-provided values can't overflow the buffers. Applicable to all K/L/M/N branches. Bug: 25747670 Change-Id: Id6a5120c2d08a6fbbd47deffb680ecf82015f4f6 CWE ID: CWE-284
void ASessionDescription::getFormatType( size_t index, unsigned long *PT, AString *desc, AString *params) const { AString format; getFormat(index, &format); const char *lastSpacePos = strrchr(format.c_str(), ' '); CHECK(lastSpacePos != NULL); char *end; unsigned long x = strtoul(lastSpacePos + 1, &end, 10); CHECK_GT(end, lastSpacePos + 1); CHECK_EQ(*end, '\0'); *PT = x; char key[32]; snprintf(key, sizeof(key), "a=rtpmap:%lu", x); CHECK(findAttribute(index, key, desc)); snprintf(key, sizeof(key), "a=fmtp:%lu", x); if (!findAttribute(index, key, params)) { params->clear(); } }
173,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: static void __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; int newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (mode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(path, state, wait); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static void __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait) static void __nfs4_close(struct path *path, struct nfs4_state *state, fmode_t fmode, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; fmode_t newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (fmode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(path, state, wait); }
165,709
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::GetLast() const { if (m_cue_points == NULL) return NULL; if (m_count <= 0) return NULL; #if 0 LoadCuePoint(); //init cues const size_t count = m_count + m_preload_count; if (count == 0) //weird return NULL; const size_t index = count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); pCP->Load(m_pSegment->m_pReader); assert(pCP->GetTimeCode() >= 0); #else const long index = m_count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); assert(pCP->GetTimeCode() >= 0); #endif return pCP; } 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::GetLast() const if (m_count <= 0) return NULL; #if 0 LoadCuePoint(); //init cues const size_t count = m_count + m_preload_count; if (count == 0) //weird return NULL; const size_t index = count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); pCP->Load(m_pSegment->m_pReader); assert(pCP->GetTimeCode() >= 0); #else const long index = m_count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); assert(pCP->GetTimeCode() >= 0); #endif return pCP; }
174,339
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 __skb_complete_tx_timestamp(struct sk_buff *skb, struct sock *sk, int tstype) { struct sock_exterr_skb *serr; int err; serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING; serr->ee.ee_info = tstype; if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) { serr->ee.ee_data = skb_shinfo(skb)->tskey; if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) serr->ee.ee_data -= sk->sk_tskey; } err = sock_queue_err_skb(sk, skb); if (err) kfree_skb(skb); } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <zzoru007@gmail.com> Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Willem de Bruijn <willemb@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-125
static void __skb_complete_tx_timestamp(struct sk_buff *skb, struct sock *sk, int tstype, bool opt_stats) { struct sock_exterr_skb *serr; int err; BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb)); serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING; serr->ee.ee_info = tstype; serr->opt_stats = opt_stats; if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) { serr->ee.ee_data = skb_shinfo(skb)->tskey; if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) serr->ee.ee_data -= sk->sk_tskey; } err = sock_queue_err_skb(sk, skb); if (err) kfree_skb(skb); }
170,071
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 rndis_set_response(USBNetState *s, rndis_set_msg_type *buf, unsigned int length) { rndis_set_cmplt_type *resp = rndis_queue_response(s, sizeof(rndis_set_cmplt_type)); uint32_t bufoffs, buflen; int ret; if (!resp) return USB_RET_STALL; bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8; buflen = le32_to_cpu(buf->InformationBufferLength); if (bufoffs + buflen > length) return USB_RET_STALL; ret = ndis_set(s, le32_to_cpu(buf->OID), bufoffs + (uint8_t *) buf, buflen); resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type)); if (ret < 0) { /* OID not supported */ resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); return 0; } resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); return 0; } Commit Message: CWE ID: CWE-189
static int rndis_set_response(USBNetState *s, rndis_set_msg_type *buf, unsigned int length) { rndis_set_cmplt_type *resp = rndis_queue_response(s, sizeof(rndis_set_cmplt_type)); uint32_t bufoffs, buflen; int ret; if (!resp) return USB_RET_STALL; bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8; buflen = le32_to_cpu(buf->InformationBufferLength); if (buflen > length || bufoffs >= length || bufoffs + buflen > length) { return USB_RET_STALL; } ret = ndis_set(s, le32_to_cpu(buf->OID), bufoffs + (uint8_t *) buf, buflen); resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type)); if (ret < 0) { /* OID not supported */ resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); return 0; } resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); return 0; }
165,186
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: PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } Commit Message: * libtiff/tif_pixarlog.c: fix potential buffer write overrun in PixarLogDecode() on corrupted/unexpected images (reported by Mathias Svensson) CWE ID: CWE-787
PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); sp->tbuf_size = tbuf_size; if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } }
169,450
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: ContentEncoding::ContentCompression::ContentCompression() : algo(0), settings(NULL), settings_len(0) { } 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
ContentEncoding::ContentCompression::ContentCompression()
174,250
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 CrosLibrary::TestApi::SetBrightnessLibrary( BrightnessLibrary* library, bool own) { library_->brightness_lib_.SetImpl(library, own); } 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
void CrosLibrary::TestApi::SetBrightnessLibrary(
170,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows CWE ID: CWE-190
void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else if (pool->free_total < NW_BUF_POOL_MAX_SIZE) { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } else { free(buf); } }
169,015
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: WebContents* DevToolsWindow::OpenURLFromTab( WebContents* source, const content::OpenURLParams& params) { DCHECK(source == main_web_contents_); if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) { WebContents* inspected_web_contents = GetInspectedWebContents(); return inspected_web_contents ? inspected_web_contents->OpenURL(params) : NULL; } bindings_->Reload(); return main_web_contents_; } Commit Message: [DevTools] Use no-referrer for DevTools links Bug: 732751 Change-Id: I77753120e2424203dedcc7bc0847fb67f87fe2b2 Reviewed-on: https://chromium-review.googlesource.com/615021 Reviewed-by: Andrey Kosyakov <caseq@chromium.org> Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#494413} CWE ID: CWE-668
WebContents* DevToolsWindow::OpenURLFromTab( WebContents* source, const content::OpenURLParams& params) { DCHECK(source == main_web_contents_); if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) { WebContents* inspected_web_contents = GetInspectedWebContents(); if (!inspected_web_contents) return nullptr; content::OpenURLParams modified = params; modified.referrer = content::Referrer(); return inspected_web_contents->OpenURL(modified); } bindings_->Reload(); return main_web_contents_; }
172,960