instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void lockd_down_net(struct svc_serv *serv, struct net *net) { struct lockd_net *ln = net_generic(net, lockd_net_id); if (ln->nlmsvc_users) { if (--ln->nlmsvc_users == 0) { nlm_shutdown_hosts_net(net); cancel_delayed_work_sync(&ln->grace_period_end); locks_end_grace(&ln->lockd_manager); svc_shutdown_net(serv, net); dprintk("lockd_down_net: per-net data destroyed; net=%p\n", net); } } else { printk(KERN_ERR "lockd_down_net: no users! task=%p, net=%p\n", nlmsvc_task, net); BUG(); } } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static void lockd_down_net(struct svc_serv *serv, struct net *net) { struct lockd_net *ln = net_generic(net, lockd_net_id); if (ln->nlmsvc_users) { if (--ln->nlmsvc_users == 0) { nlm_shutdown_hosts_net(net); svc_shutdown_net(serv, net); dprintk("lockd_down_net: per-net data destroyed; net=%p\n", net); } } else { printk(KERN_ERR "lockd_down_net: no users! task=%p, net=%p\n", nlmsvc_task, net); BUG(); } }
168,135
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copy_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); if (rv) fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); unlink(src); } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static void copy_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); fs_logger2("clone", dest); unlink(src); }
170,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AudioOutputDevice::Stop() { { base::AutoLock auto_lock(audio_thread_lock_); audio_thread_->Stop(MessageLoop::current()); audio_thread_.reset(); } message_loop()->PostTask(FROM_HERE, base::Bind(&AudioOutputDevice::ShutDownOnIOThread, this)); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void AudioOutputDevice::Stop() { { base::AutoLock auto_lock(audio_thread_lock_); audio_thread_.Stop(MessageLoop::current()); } message_loop()->PostTask(FROM_HERE, base::Bind(&AudioOutputDevice::ShutDownOnIOThread, this)); }
170,707
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: error::Error GLES2DecoderImpl::HandleDrawElements( uint32 immediate_data_size, const gles2::DrawElements& c) { if (!bound_element_array_buffer_ || bound_element_array_buffer_->IsDeleted()) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: No element array buffer bound"); return error::kNoError; } GLenum mode = c.mode; GLsizei count = c.count; GLenum type = c.type; int32 offset = c.index_offset; if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: count < 0"); return error::kNoError; } if (offset < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: offset < 0"); return error::kNoError; } if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: mode GL_INVALID_ENUM"); return error::kNoError; } if (!validators_->index_type.IsValid(type)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: type GL_INVALID_ENUM"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawElements")) { return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed; if (!bound_element_array_buffer_->GetMaxValueForRange( offset, count, type, &max_vertex_accessed)) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: range out of bounds for buffer"); return error::kNoError; } if (IsDrawValid(max_vertex_accessed)) { bool simulated_attrib_0 = SimulateAttrib0(max_vertex_accessed); bool simulated_fixed_attribs = false; if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) { bool textures_set = SetBlackTextureForNonRenderableTextures(); ApplyDirtyState(); const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset); glDrawElements(mode, count, type, indices); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements."; return error::kLostContext; } } return error::kNoError; } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 TBR=apatrick@chromium.org Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
error::Error GLES2DecoderImpl::HandleDrawElements( uint32 immediate_data_size, const gles2::DrawElements& c) { if (!bound_element_array_buffer_ || bound_element_array_buffer_->IsDeleted()) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: No element array buffer bound"); return error::kNoError; } GLenum mode = c.mode; GLsizei count = c.count; GLenum type = c.type; int32 offset = c.index_offset; if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: count < 0"); return error::kNoError; } if (offset < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: offset < 0"); return error::kNoError; } if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: mode GL_INVALID_ENUM"); return error::kNoError; } if (!validators_->index_type.IsValid(type)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: type GL_INVALID_ENUM"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawElements")) { return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed; if (!bound_element_array_buffer_->GetMaxValueForRange( offset, count, type, &max_vertex_accessed)) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: range out of bounds for buffer"); return error::kNoError; } if (IsDrawValid(max_vertex_accessed)) { bool simulated_attrib_0 = false; if (!SimulateAttrib0(max_vertex_accessed, &simulated_attrib_0)) { return error::kNoError; } bool simulated_fixed_attribs = false; if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) { bool textures_set = SetBlackTextureForNonRenderableTextures(); ApplyDirtyState(); const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset); glDrawElements(mode, count, type, indices); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements."; return error::kLostContext; } } return error::kNoError; }
170,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: find_insert(png_const_charp what, png_charp param) { png_uint_32 chunk = 0; png_charp parameter_list[1024]; int i, nparams; /* Assemble the chunk name */ for (i=0; i<4; ++i) { char ch = what[i]; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) chunk = (chunk << 8) + what[i]; else break; } if (i < 4 || what[4] != 0) { fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what); exit(1); } /* Assemble the parameter list. */ nparams = find_parameters(what, param, parameter_list, 1024); # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d)) switch (chunk) { case CHUNK(105,67,67,80): /* iCCP */ if (nparams == 2) return make_insert(what, insert_iCCP, nparams, parameter_list); break; case CHUNK(116,69,88,116): /* tEXt */ if (nparams == 2) return make_insert(what, insert_tEXt, nparams, parameter_list); break; case CHUNK(122,84,88,116): /* zTXt */ if (nparams == 2) return make_insert(what, insert_zTXt, nparams, parameter_list); break; case CHUNK(105,84,88,116): /* iTXt */ if (nparams == 4) return make_insert(what, insert_iTXt, nparams, parameter_list); break; case CHUNK(104,73,83,84): /* hIST */ if (nparams <= 256) return make_insert(what, insert_hIST, nparams, parameter_list); break; #if 0 case CHUNK(115,80,76,84): /* sPLT */ return make_insert(what, insert_sPLT, nparams, parameter_list); #endif default: fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n", what); exit(1); } bad_parameter_count(what, nparams); return NULL; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
find_insert(png_const_charp what, png_charp param) { png_uint_32 chunk = 0; png_charp parameter_list[1024]; int i, nparams; /* Assemble the chunk name */ for (i=0; i<4; ++i) { char ch = what[i]; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) chunk = (chunk << 8) + what[i]; else break; } if (i < 4 || what[4] != 0) { fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what); exit(1); } /* Assemble the parameter list. */ nparams = find_parameters(what, param, parameter_list, 1024); # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d)) switch (chunk) { case CHUNK(105,67,67,80): /* iCCP */ if (nparams == 2) return make_insert(what, insert_iCCP, nparams, parameter_list); break; case CHUNK(116,69,88,116): /* tEXt */ if (nparams == 2) return make_insert(what, insert_tEXt, nparams, parameter_list); break; case CHUNK(122,84,88,116): /* zTXt */ if (nparams == 2) return make_insert(what, insert_zTXt, nparams, parameter_list); break; case CHUNK(105,84,88,116): /* iTXt */ if (nparams == 4) return make_insert(what, insert_iTXt, nparams, parameter_list); break; case CHUNK(104,73,83,84): /* hIST */ if (nparams <= 256) return make_insert(what, insert_hIST, nparams, parameter_list); break; case CHUNK(115,66,73,84): /* sBIT */ if (nparams <= 4) return make_insert(what, insert_sBIT, nparams, parameter_list); break; #if 0 case CHUNK(115,80,76,84): /* sPLT */ return make_insert(what, insert_sPLT, nparams, parameter_list); #endif default: fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n", what); exit(1); } bad_parameter_count(what, nparams); return NULL; }
173,578
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type) { /* XML 1.0 HTML 4.01 HTML 5 * 0x09..0x0A 0x09..0x0A 0x09..0x0A * 0x0D 0x0D 0x0C..0x0D * 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E * 0x00A0..0xD7FF 0x00A0..0xD7FF * 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF * 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*) * * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE) * * References: * XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets> * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html> * HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream> * * Not sure this is the relevant part for HTML 5, though. I opted to * disallow the characters that would result in a parse error when * preprocessing of the input stream. See also section 8.1.3. * * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to * XHTML 1.0 the same rules as for XML 1.0. * See <http://cmsmcq.com/2007/C1.xml>. */ switch (document_type) { case ENT_HTML_DOC_HTML401: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF); case ENT_HTML_DOC_HTML5: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */ (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF); default: return 1; } } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type) { /* XML 1.0 HTML 4.01 HTML 5 * 0x09..0x0A 0x09..0x0A 0x09..0x0A * 0x0D 0x0D 0x0C..0x0D * 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E * 0x00A0..0xD7FF 0x00A0..0xD7FF * 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF * 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*) * * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE) * * References: * XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets> * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html> * HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream> * * Not sure this is the relevant part for HTML 5, though. I opted to * disallow the characters that would result in a parse error when * preprocessing of the input stream. See also section 8.1.3. * * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to * XHTML 1.0 the same rules as for XML 1.0. * See <http://cmsmcq.com/2007/C1.xml>. */ switch (document_type) { case ENT_HTML_DOC_HTML401: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF); case ENT_HTML_DOC_HTML5: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */ (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF); default: return 1; } }
167,179
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GesturePoint::IsInClickTimeWindow() const { double duration = last_touch_time_ - first_touch_time_; return duration >= kMinimumTouchDownDurationInSecondsForClick && duration < kMaximumTouchDownDurationInSecondsForClick; } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool GesturePoint::IsInClickTimeWindow() const { double duration = last_touch_time_ - first_touch_time_; return duration >= GestureConfiguration::min_touch_down_duration_in_seconds_for_click() && duration < GestureConfiguration::max_touch_down_duration_in_seconds_for_click(); }
171,042
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: kex_input_newkeys(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; int r; debug("SSH2_MSG_NEWKEYS received"); ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error); if ((r = sshpkt_get_end(ssh)) != 0) return r; kex->done = 1; sshbuf_reset(kex->peer); /* sshbuf_reset(kex->my); */ kex->name = NULL; return 0; } Commit Message: CWE ID: CWE-476
kex_input_newkeys(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; int r; debug("SSH2_MSG_NEWKEYS received"); ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error); if ((r = sshpkt_get_end(ssh)) != 0) return r; if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0) return r; kex->done = 1; sshbuf_reset(kex->peer); /* sshbuf_reset(kex->my); */ kex->name = NULL; return 0; }
165,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SavePayload(size_t handle, uint32_t *payload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp && payload) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fwrite(payload, 1, mp4->metasizes[index], mp4->mediafp); } return; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
void SavePayload(size_t handle, uint32_t *payload, uint32_t index) void LongSeek(mp4object *mp4, int64_t offset) { if (mp4 && offset) { if (mp4->filepos + offset < mp4->filesize) { LONGSEEK(mp4->mediafp, offset, SEEK_CUR); mp4->filepos += offset; } else { mp4->filepos = mp4->filesize; } } }
169,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { int copy = output_size - count; if (avail < copy) copy = avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = "Buffer error in compressed datastream in %s chunk"; break; case Z_DATA_ERROR: msg = "Data error in compressed datastream in %s chunk"; break; default: msg = "Incomplete compressed datastream in %s chunk"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = "Damaged compressed datastream in chunk other than IDAT"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } } Commit Message: Pull follow-up tweak from upstream. BUG=116162 Review URL: http://codereview.chromium.org/9546033 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125311 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { png_size_t copy = output_size - count; if ((png_size_t) avail < copy) copy = (png_size_t) avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = "Buffer error in compressed datastream in %s chunk"; break; case Z_DATA_ERROR: msg = "Data error in compressed datastream in %s chunk"; break; default: msg = "Incomplete compressed datastream in %s chunk"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = "Damaged compressed datastream in chunk other than IDAT"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } }
171,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetImePropertyActivated(const std::string& key, bool activated) { if (!initialized_successfully_) return; DCHECK(!key.empty()); chromeos::SetImePropertyActivated( input_method_status_connection_, key.c_str(), activated); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual void SetImePropertyActivated(const std::string& key, bool activated) { if (!initialized_successfully_) return; DCHECK(!key.empty()); ibus_controller_->SetImePropertyActivated(key, activated); }
170,507
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeMockRenderThread::OnCheckForCancel( const std::string& preview_ui_addr, int preview_request_id, bool* cancel) { *cancel = (print_preview_pages_remaining_ == print_preview_cancel_page_number_); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnCheckForCancel( void ChromeMockRenderThread::OnCheckForCancel(int32 preview_ui_id, int preview_request_id, bool* cancel) { *cancel = (print_preview_pages_remaining_ == print_preview_cancel_page_number_); }
170,847
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleIterator::seekTo(uint32_t sampleIndex) { ALOGV("seekTo(%d)", sampleIndex); if (sampleIndex >= mTable->mNumSampleSizes) { return ERROR_END_OF_STREAM; } if (mTable->mSampleToChunkOffset < 0 || mTable->mChunkOffsetOffset < 0 || mTable->mSampleSizeOffset < 0 || mTable->mTimeToSampleCount == 0) { return ERROR_MALFORMED; } if (mInitialized && mCurrentSampleIndex == sampleIndex) { return OK; } if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) { reset(); } if (sampleIndex >= mStopChunkSampleIndex) { status_t err; if ((err = findChunkRange(sampleIndex)) != OK) { ALOGE("findChunkRange failed"); return err; } } CHECK(sampleIndex < mStopChunkSampleIndex); uint32_t chunk = (sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk + mFirstChunk; if (!mInitialized || chunk != mCurrentChunkIndex) { mCurrentChunkIndex = chunk; status_t err; if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) { ALOGE("getChunkOffset return error"); return err; } mCurrentChunkSampleSizes.clear(); uint32_t firstChunkSampleIndex = mFirstChunkSampleIndex + mSamplesPerChunk * (mCurrentChunkIndex - mFirstChunk); for (uint32_t i = 0; i < mSamplesPerChunk; ++i) { size_t sampleSize; if ((err = getSampleSizeDirect( firstChunkSampleIndex + i, &sampleSize)) != OK) { ALOGE("getSampleSizeDirect return error"); return err; } mCurrentChunkSampleSizes.push(sampleSize); } } uint32_t chunkRelativeSampleIndex = (sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk; mCurrentSampleOffset = mCurrentChunkOffset; for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) { mCurrentSampleOffset += mCurrentChunkSampleSizes[i]; } mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex]; if (sampleIndex < mTTSSampleIndex) { mTimeToSampleIndex = 0; mTTSSampleIndex = 0; mTTSSampleTime = 0; mTTSCount = 0; mTTSDuration = 0; } status_t err; if ((err = findSampleTimeAndDuration( sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) { ALOGE("findSampleTime return error"); return err; } mCurrentSampleIndex = sampleIndex; mInitialized = true; return OK; } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119
status_t SampleIterator::seekTo(uint32_t sampleIndex) { ALOGV("seekTo(%d)", sampleIndex); if (sampleIndex >= mTable->mNumSampleSizes) { return ERROR_END_OF_STREAM; } if (mTable->mSampleToChunkOffset < 0 || mTable->mChunkOffsetOffset < 0 || mTable->mSampleSizeOffset < 0 || mTable->mTimeToSampleCount == 0) { return ERROR_MALFORMED; } if (mInitialized && mCurrentSampleIndex == sampleIndex) { return OK; } if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) { reset(); } if (sampleIndex >= mStopChunkSampleIndex) { status_t err; if ((err = findChunkRange(sampleIndex)) != OK) { ALOGE("findChunkRange failed"); return err; } } CHECK(sampleIndex < mStopChunkSampleIndex); if (mSamplesPerChunk == 0) { ALOGE("b/22802344"); return ERROR_MALFORMED; } uint32_t chunk = (sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk + mFirstChunk; if (!mInitialized || chunk != mCurrentChunkIndex) { mCurrentChunkIndex = chunk; status_t err; if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) { ALOGE("getChunkOffset return error"); return err; } mCurrentChunkSampleSizes.clear(); uint32_t firstChunkSampleIndex = mFirstChunkSampleIndex + mSamplesPerChunk * (mCurrentChunkIndex - mFirstChunk); for (uint32_t i = 0; i < mSamplesPerChunk; ++i) { size_t sampleSize; if ((err = getSampleSizeDirect( firstChunkSampleIndex + i, &sampleSize)) != OK) { ALOGE("getSampleSizeDirect return error"); return err; } mCurrentChunkSampleSizes.push(sampleSize); } } uint32_t chunkRelativeSampleIndex = (sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk; mCurrentSampleOffset = mCurrentChunkOffset; for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) { mCurrentSampleOffset += mCurrentChunkSampleSizes[i]; } mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex]; if (sampleIndex < mTTSSampleIndex) { mTimeToSampleIndex = 0; mTTSSampleIndex = 0; mTTSSampleTime = 0; mTTSCount = 0; mTTSDuration = 0; } status_t err; if ((err = findSampleTimeAndDuration( sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) { ALOGE("findSampleTime return error"); return err; } mCurrentSampleIndex = sampleIndex; mInitialized = true; return OK; }
173,766
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gstd_accept(int fd, char **display_creds, char **export_name, char **mech) { gss_name_t client; gss_OID mech_oid; struct gstd_tok *tok; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc in, out; OM_uint32 maj, min; int ret; *display_creds = NULL; *export_name = NULL; out.length = 0; in.length = 0; read_packet(fd, &in, 60000, 1); again: while ((ret = read_packet(fd, &in, 60000, 0)) == -2) ; if (ret < 1) return NULL; maj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL, &in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL, NULL, NULL); if (out.length && write_packet(fd, &out)) { gss_release_buffer(&min, &out); return NULL; } GSTD_GSS_ERROR(maj, min, NULL, "gss_accept_sec_context"); if (maj & GSS_S_CONTINUE_NEEDED) goto again; *display_creds = gstd_get_display_name(client); *export_name = gstd_get_export_name(client); *mech = gstd_get_mech(mech_oid); gss_release_name(&min, &client); SETUP_GSTD_TOK(tok, ctx, fd, "gstd_accept"); return tok; } Commit Message: knc: fix a couple of memory leaks. One of these can be remotely triggered during the authentication phase which leads to a remote DoS possibility. Pointed out by: Imre Rad <radimre83@gmail.com> CWE ID: CWE-400
gstd_accept(int fd, char **display_creds, char **export_name, char **mech) { gss_name_t client; gss_OID mech_oid; struct gstd_tok *tok; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc in, out; OM_uint32 maj, min; int ret; *display_creds = NULL; *export_name = NULL; out.length = 0; in.length = 0; read_packet(fd, &in, 60000, 1); again: while ((ret = read_packet(fd, &in, 60000, 0)) == -2) ; if (ret < 1) return NULL; maj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL, &in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL, NULL, NULL); gss_release_buffer(&min, &in); if (out.length && write_packet(fd, &out)) { gss_release_buffer(&min, &out); return NULL; } gss_release_buffer(&min, &out); GSTD_GSS_ERROR(maj, min, NULL, "gss_accept_sec_context"); if (maj & GSS_S_CONTINUE_NEEDED) goto again; *display_creds = gstd_get_display_name(client); *export_name = gstd_get_export_name(client); *mech = gstd_get_mech(mech_oid); gss_release_name(&min, &client); SETUP_GSTD_TOK(tok, ctx, fd, "gstd_accept"); return tok; }
169,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ProfileSyncComponentsFactoryImpl::RegisterDataTypes( ProfileSyncService* pss) { if (!command_line_->HasSwitch(switches::kDisableSyncApps)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(syncable::APPS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAutofill)) { pss->RegisterDataTypeController( new AutofillDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncBookmarks)) { pss->RegisterDataTypeController( new BookmarkDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncExtensions)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(syncable::EXTENSIONS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncPasswords)) { pss->RegisterDataTypeController( new PasswordDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncPreferences)) { pss->RegisterDataTypeController( new UIDataTypeController(syncable::PREFERENCES, this, profile_, pss)); } #if defined(ENABLE_THEMES) if (!command_line_->HasSwitch(switches::kDisableSyncThemes)) { pss->RegisterDataTypeController( new ThemeDataTypeController(this, profile_, pss)); } #endif if (!profile_->GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled) && !command_line_->HasSwitch(switches::kDisableSyncTypedUrls)) { pss->RegisterDataTypeController( new TypedUrlDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncSearchEngines)) { pss->RegisterDataTypeController( new SearchEngineDataTypeController(this, profile_, pss)); } pss->RegisterDataTypeController( new SessionDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncExtensionSettings)) { pss->RegisterDataTypeController( new ExtensionSettingDataTypeController( syncable::EXTENSION_SETTINGS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAppSettings)) { pss->RegisterDataTypeController( new ExtensionSettingDataTypeController( syncable::APP_SETTINGS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAutofillProfile)) { pss->RegisterDataTypeController( new AutofillProfileDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAppNotifications)) { pss->RegisterDataTypeController( new AppNotificationDataTypeController(this, profile_, pss)); } } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void ProfileSyncComponentsFactoryImpl::RegisterDataTypes( ProfileSyncService* pss) { if (!command_line_->HasSwitch(switches::kDisableSyncApps)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(syncable::APPS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAutofill)) { pss->RegisterDataTypeController( new AutofillDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncBookmarks)) { pss->RegisterDataTypeController( new BookmarkDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncExtensions)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(syncable::EXTENSIONS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncPasswords)) { pss->RegisterDataTypeController( new PasswordDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncPreferences)) { pss->RegisterDataTypeController( new UIDataTypeController(syncable::PREFERENCES, this, profile_, pss)); } #if defined(ENABLE_THEMES) if (!command_line_->HasSwitch(switches::kDisableSyncThemes)) { pss->RegisterDataTypeController( new ThemeDataTypeController(this, profile_, pss)); } #endif if (!profile_->GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled) && !command_line_->HasSwitch(switches::kDisableSyncTypedUrls)) { pss->RegisterDataTypeController( new TypedUrlDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncSearchEngines)) { pss->RegisterDataTypeController( new SearchEngineDataTypeController(this, profile_, pss)); } pss->RegisterDataTypeController( new SessionDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncExtensionSettings)) { pss->RegisterDataTypeController( new ExtensionSettingDataTypeController( syncable::EXTENSION_SETTINGS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAppSettings)) { pss->RegisterDataTypeController( new ExtensionSettingDataTypeController( syncable::APP_SETTINGS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAutofillProfile)) { pss->RegisterDataTypeController( new AutofillProfileDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAppNotifications)) { pss->RegisterDataTypeController( new AppNotificationDataTypeController(this, profile_, pss)); } }
170,786
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: generate_palette(png_colorp palette, png_bytep trans, int bit_depth, png_const_bytep gamma_table, unsigned int *colors) { /* * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white * 2-bit: entry 0: transparent-green * entry 1: 40%-red * entry 2: 80%-blue * entry 3: opaque-white * 4-bit: the 16 combinations of the 2-bit case * 8-bit: the 256 combinations of the 4-bit case */ switch (colors[0]) { default: fprintf(stderr, "makepng: --colors=...: invalid count %u\n", colors[0]); exit(1); case 1: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255, gamma_table); return 1; case 2: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], colors[2], gamma_table); return 1; case 3: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255, gamma_table); return 1; case 4: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], colors[4], gamma_table); return 1; case 0: if (bit_depth == 1) { set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table); set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table); return 2; } else { unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */ unsigned int x, y, ip; for (x=0; x<size; ++x) for (y=0; y<size; ++y) { ip = x + (size * y); /* size is at most 16, so the scaled value below fits in 16 bits */ # define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2)) # define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\ (interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\ (size*size)) set_color(palette+ip, trans+ip, /* color: green, red,blue,white */ xyinterp(x, y, 0, 255, 0, 255), xyinterp(x, y, 255, 0, 0, 255), xyinterp(x, y, 0, 0, 255, 255), /* alpha: 0, 102, 204, 255) */ xyinterp(x, y, 0, 102, 204, 255), gamma_table); } return ip+1; } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
generate_palette(png_colorp palette, png_bytep trans, int bit_depth, png_const_bytep gamma_table, unsigned int *colors) { /* * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white * 2-bit: entry 0: transparent-green * entry 1: 40%-red * entry 2: 80%-blue * entry 3: opaque-white * 4-bit: the 16 combinations of the 2-bit case * 8-bit: the 256 combinations of the 4-bit case */ switch (colors[0]) { default: fprintf(stderr, "makepng: --colors=...: invalid count %u\n", colors[0]); exit(1); case 1: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255, gamma_table); return 1; case 2: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], colors[2], gamma_table); return 1; case 3: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255, gamma_table); return 1; case 4: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], colors[4], gamma_table); return 1; case 0: if (bit_depth == 1) { set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table); set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table); return 2; } else { unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */ unsigned int x, y; volatile unsigned int ip = 0; for (x=0; x<size; ++x) for (y=0; y<size; ++y) { ip = x + (size * y); /* size is at most 16, so the scaled value below fits in 16 bits */ # define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2)) # define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\ (interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\ (size*size)) set_color(palette+ip, trans+ip, /* color: green, red,blue,white */ xyinterp(x, y, 0, 255, 0, 255), xyinterp(x, y, 255, 0, 0, 255), xyinterp(x, y, 0, 0, 255, 255), /* alpha: 0, 102, 204, 255) */ xyinterp(x, y, 0, 102, 204, 255), gamma_table); } return ip+1; } } }
173,579
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::allocateBuffer( OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer, void **buffer_data) { Mutex::Autolock autoLock(mLock); BufferMeta *buffer_meta = new BufferMeta(size); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, size); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); *buffer_data = header->pBuffer; addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBuffer, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p", size, *buffer_data)); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::allocateBuffer( OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer, void **buffer_data) { Mutex::Autolock autoLock(mLock); BufferMeta *buffer_meta = new BufferMeta(size, portIndex); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, size); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); *buffer_data = header->pBuffer; addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBuffer, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p", size, *buffer_data)); return OK; }
173,524
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gint base64_len) { GstBuffer *img; guchar *img_data; gsize img_len; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; img_data = g_try_malloc0 (base64_len * 3 / 4); if (img_data == NULL) goto alloc_failed; img_len = g_base64_decode_step (img_data_base64, base64_len, img_data, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (img_data, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); g_free (img_data); return; /* ERRORS */ { GST_WARNING ("COVERART tag with too little base64-encoded data"); GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } alloc_failed: { GST_WARNING ("Couldn't allocate enough memory to decode COVERART tag"); return; } decode_failed: { GST_WARNING ("Couldn't decode bas64 image data from COVERART tag"); g_free (img_data); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); g_free (img_data); return; } } Commit Message: CWE ID: CWE-189
gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gst_vorbis_tag_add_coverart (GstTagList * tags, gchar * img_data_base64, gint base64_len) { GstBuffer *img; gsize img_len; guchar *out; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; /* img_data_base64 points to a temporary copy of the base64 encoded data, so * it's safe to do inpace decoding here * TODO: glib 2.20 and later provides g_base64_decode_inplace, so change this * to use glib's API instead once it's in wider use: * http://bugzilla.gnome.org/show_bug.cgi?id=564728 * http://svn.gnome.org/viewvc/glib?view=revision&revision=7807 */ out = (guchar *) img_data_base64; img_len = g_base64_decode_step (img_data_base64, base64_len, out, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (out, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); return; /* ERRORS */ { GST_WARNING ("COVERART tag with too little base64-encoded data"); GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } decode_failed: { GST_WARNING ("Couldn't decode base64 image data from COVERART tag"); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); return; } }
164,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MakeUsernameForAccount(const base::DictionaryValue* result, base::string16* gaia_id, wchar_t* username, DWORD username_length, wchar_t* domain, DWORD domain_length, wchar_t* sid, DWORD sid_length) { DCHECK(gaia_id); DCHECK(username); DCHECK(domain); DCHECK(sid); *gaia_id = GetDictString(result, kKeyId); HRESULT hr = GetSidFromId(*gaia_id, sid, sid_length); if (SUCCEEDED(hr)) { hr = OSUserManager::Get()->FindUserBySID(sid, username, username_length, domain, domain_length); if (SUCCEEDED(hr)) return; } LOGFN(INFO) << "No existing user found associated to gaia id:" << *gaia_id; wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str()); username[0] = 0; sid[0] = 0; base::string16 os_username = GetDictString(result, kKeyEmail); std::transform(os_username.begin(), os_username.end(), os_username.begin(), ::tolower); base::string16::size_type at = os_username.find(L"@gmail.com"); if (at == base::string16::npos) at = os_username.find(L"@googlemail.com"); if (at != base::string16::npos) { os_username.resize(at); } else { std::string username_utf8 = gaia::SanitizeEmail(base::UTF16ToUTF8(os_username)); size_t tld_length = net::registry_controlled_domains::GetCanonicalHostRegistryLength( gaia::ExtractDomainName(username_utf8), net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); if (tld_length > 0) { username_utf8.resize(username_utf8.length() - tld_length - 1); os_username = base::UTF8ToUTF16(username_utf8); } } if (os_username.size() > kWindowsUsernameBufferLength - 1) os_username.resize(kWindowsUsernameBufferLength - 1); for (auto& c : os_username) { if (wcschr(L"@\\[]:|<>+=;?*", c) != nullptr || c < 32) c = L'_'; } wcscpy_s(username, username_length, os_username.c_str()); } Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled. Unless the registry key "mdm_aca" is explicitly set to 1, always fail sign in of consumer accounts when mdm enrollment is enabled. Consumer accounts are defined as accounts with gmail.com or googlemail.com domain. Bug: 944049 Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903 Commit-Queue: Tien Mai <tienmai@chromium.org> Reviewed-by: Roger Tawa <rogerta@chromium.org> Cr-Commit-Position: refs/heads/master@{#646278} CWE ID: CWE-284
void MakeUsernameForAccount(const base::DictionaryValue* result, base::string16* gaia_id, wchar_t* username, DWORD username_length, wchar_t* domain, DWORD domain_length, wchar_t* sid, DWORD sid_length, bool* is_consumer_account) { DCHECK(gaia_id); DCHECK(username); DCHECK(domain); DCHECK(sid); DCHECK(is_consumer_account); // Determine if the email is a consumer domain (gmail.com or googlemail.com). base::string16 email = GetDictString(result, kKeyEmail); std::transform(email.begin(), email.end(), email.begin(), ::tolower); base::string16::size_type consumer_domain_pos = email.find(L"@gmail.com"); if (consumer_domain_pos == base::string16::npos) consumer_domain_pos = email.find(L"@googlemail.com"); *is_consumer_account = consumer_domain_pos != base::string16::npos; *gaia_id = GetDictString(result, kKeyId); HRESULT hr = GetSidFromId(*gaia_id, sid, sid_length); if (SUCCEEDED(hr)) { hr = OSUserManager::Get()->FindUserBySID(sid, username, username_length, domain, domain_length); if (SUCCEEDED(hr)) return; } LOGFN(INFO) << "No existing user found associated to gaia id:" << *gaia_id; wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str()); username[0] = 0; sid[0] = 0; base::string16 os_username = email; // If the email is a consumer domain, strip it. if (consumer_domain_pos != base::string16::npos) { os_username.resize(consumer_domain_pos); } else { std::string username_utf8 = gaia::SanitizeEmail(base::UTF16ToUTF8(os_username)); size_t tld_length = net::registry_controlled_domains::GetCanonicalHostRegistryLength( gaia::ExtractDomainName(username_utf8), net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); if (tld_length > 0) { username_utf8.resize(username_utf8.length() - tld_length - 1); os_username = base::UTF8ToUTF16(username_utf8); } } if (os_username.size() > kWindowsUsernameBufferLength - 1) os_username.resize(kWindowsUsernameBufferLength - 1); for (auto& c : os_username) { if (wcschr(L"@\\[]:|<>+=;?*", c) != nullptr || c < 32) c = L'_'; } wcscpy_s(username, username_length, os_username.c_str()); }
172,100
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FrameView::FrameView(LocalFrame* frame) : m_frame(frame) , m_canHaveScrollbars(true) , m_slowRepaintObjectCount(0) , m_hasPendingLayout(false) , m_layoutSubtreeRoot(0) , m_inSynchronousPostLayout(false) , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired) , m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired) , m_isTransparent(false) , m_baseBackgroundColor(Color::white) , m_mediaType("screen") , m_overflowStatusDirty(true) , m_viewportRenderer(0) , m_wasScrolledByUser(false) , m_inProgrammaticScroll(false) , m_safeToPropagateScrollToParent(true) , m_isTrackingPaintInvalidations(false) , m_scrollCorner(nullptr) , m_hasSoftwareFilters(false) , m_visibleContentScaleFactor(1) , m_inputEventsScaleFactorForEmulation(1) , m_layoutSizeFixedToFrameSize(true) , m_didScrollTimer(this, &FrameView::didScrollTimerFired) { ASSERT(m_frame); init(); if (!m_frame->isMainFrame()) return; ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed); ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 R=vollick@chromium.org Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416
FrameView::FrameView(LocalFrame* frame) : m_frame(frame) , m_canHaveScrollbars(true) , m_slowRepaintObjectCount(0) , m_hasPendingLayout(false) , m_layoutSubtreeRoot(0) , m_inSynchronousPostLayout(false) , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired) , m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired) , m_isTransparent(false) , m_baseBackgroundColor(Color::white) , m_mediaType("screen") , m_overflowStatusDirty(true) , m_viewportRenderer(0) , m_wasScrolledByUser(false) , m_inProgrammaticScroll(false) , m_safeToPropagateScrollToParent(true) , m_isTrackingPaintInvalidations(false) , m_scrollCorner(nullptr) , m_hasSoftwareFilters(false) , m_visibleContentScaleFactor(1) , m_inputEventsScaleFactorForEmulation(1) , m_layoutSizeFixedToFrameSize(true) , m_didScrollTimer(this, &FrameView::didScrollTimerFired) , m_needsUpdateWidgetPositions(false) { ASSERT(m_frame); init(); if (!m_frame->isMainFrame()) return; ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed); ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed); }
171,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: activate_desktop_file (ActivateParameters *parameters, NautilusFile *file) { ActivateParametersDesktop *parameters_desktop; char *primary, *secondary, *display_name; GtkWidget *dialog; GdkScreen *screen; char *uri; screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); if (!nautilus_file_is_trusted_link (file)) { /* copy the parts of parameters we are interested in as the orignal will be freed */ parameters_desktop = g_new0 (ActivateParametersDesktop, 1); if (parameters->parent_window) { parameters_desktop->parent_window = parameters->parent_window; g_object_add_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) &parameters_desktop->parent_window); } parameters_desktop->file = nautilus_file_ref (file); primary = _("Untrusted application launcher"); display_name = nautilus_file_get_display_name (file); secondary = g_strdup_printf (_("The application launcher “%s” has not been marked as trusted. " "If you do not know the source of this file, launching it may be unsafe." ), display_name); dialog = gtk_message_dialog_new (parameters->parent_window, 0, GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE, NULL); g_object_set (dialog, "text", primary, "secondary-text", secondary, NULL); gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Launch Anyway"), RESPONSE_RUN); if (nautilus_file_can_set_permissions (file)) { gtk_dialog_add_button (GTK_DIALOG (dialog), _("Mark as _Trusted"), RESPONSE_MARK_TRUSTED); } gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Cancel"), GTK_RESPONSE_CANCEL); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); g_signal_connect (dialog, "response", G_CALLBACK (untrusted_launcher_response_callback), parameters_desktop); gtk_widget_show (dialog); g_free (display_name); g_free (secondary); return; } uri = nautilus_file_get_uri (file); DEBUG ("Launching trusted launcher %s", uri); nautilus_launch_desktop_file (screen, uri, NULL, parameters->parent_window); g_free (uri); } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
activate_desktop_file (ActivateParameters *parameters, NautilusFile *file) { ActivateParametersDesktop *parameters_desktop; char *primary, *secondary, *display_name; GtkWidget *dialog; GdkScreen *screen; char *uri; screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); if (!nautilus_file_is_trusted_link (file)) { /* copy the parts of parameters we are interested in as the orignal will be freed */ parameters_desktop = g_new0 (ActivateParametersDesktop, 1); if (parameters->parent_window) { parameters_desktop->parent_window = parameters->parent_window; g_object_add_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) &parameters_desktop->parent_window); } parameters_desktop->file = nautilus_file_ref (file); primary = _("Untrusted application launcher"); display_name = nautilus_file_get_display_name (file); secondary = g_strdup_printf (_("The application launcher “%s” has not been marked as trusted. " "If you do not know the source of this file, launching it may be unsafe." ), display_name); dialog = gtk_message_dialog_new (parameters->parent_window, 0, GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE, NULL); g_object_set (dialog, "text", primary, "secondary-text", secondary, NULL); gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Cancel"), GTK_RESPONSE_CANCEL); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); if (nautilus_file_can_set_permissions (file)) { gtk_dialog_add_button (GTK_DIALOG (dialog), _("Trust and _Launch"), GTK_RESPONSE_OK); } g_signal_connect (dialog, "response", G_CALLBACK (untrusted_launcher_response_callback), parameters_desktop); gtk_widget_show (dialog); g_free (display_name); g_free (secondary); return; } uri = nautilus_file_get_uri (file); DEBUG ("Launching trusted launcher %s", uri); nautilus_launch_desktop_file (screen, uri, NULL, parameters->parent_window); g_free (uri); }
167,752
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaControlVolumeSliderElement::defaultEventHandler(Event* event) { if (event->isMouseEvent() && toMouseEvent(event)->button() != static_cast<short>(WebPointerProperties::Button::Left)) return; if (!isConnected() || !document().isActive()) return; MediaControlInputElement::defaultEventHandler(event); if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove) return; if (event->type() == EventTypeNames::mousedown) Platform::current()->recordAction( UserMetricsAction("Media.Controls.VolumeChangeBegin")); if (event->type() == EventTypeNames::mouseup) Platform::current()->recordAction( UserMetricsAction("Media.Controls.VolumeChangeEnd")); double volume = value().toDouble(); mediaElement().setVolume(volume); mediaElement().setMuted(false); } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} CWE ID: CWE-119
void MediaControlVolumeSliderElement::defaultEventHandler(Event* event) { if (!isConnected() || !document().isActive()) return; MediaControlInputElement::defaultEventHandler(event); if (event->type() == EventTypeNames::mousedown) Platform::current()->recordAction( UserMetricsAction("Media.Controls.VolumeChangeBegin")); if (event->type() == EventTypeNames::mouseup) Platform::current()->recordAction( UserMetricsAction("Media.Controls.VolumeChangeEnd")); if (event->type() == EventTypeNames::input) { double volume = value().toDouble(); mediaElement().setVolume(volume); mediaElement().setMuted(false); } }
171,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } Commit Message: * tools/tiffcp.c: fix uint32 underflow/overflow that can cause heap-based buffer overflow. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2610 CWE ID: CWE-190
DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int64 iskew = (int64)imagew - (int64)tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb > iskew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; }
168,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FileSystemOperation::GetUsageAndQuotaThenRunTask( const GURL& origin, FileSystemType type, const base::Closure& task, const base::Closure& error_callback) { quota::QuotaManagerProxy* quota_manager_proxy = file_system_context()->quota_manager_proxy(); if (!quota_manager_proxy || !file_system_context()->GetQuotaUtil(type)) { operation_context_.set_allowed_bytes_growth(kint64max); task.Run(); return; } TaskParamsForDidGetQuota params; params.origin = origin; params.type = type; params.task = task; params.error_callback = error_callback; DCHECK(quota_manager_proxy); DCHECK(quota_manager_proxy->quota_manager()); quota_manager_proxy->quota_manager()->GetUsageAndQuota( origin, FileSystemTypeToQuotaStorageType(type), base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask, base::Unretained(this), params)); } Commit Message: Crash fix in fileapi::FileSystemOperation::DidGetUsageAndQuotaAndRunTask https://chromiumcodereview.appspot.com/10008047 introduced delete-with-inflight-tasks in Write sequence but I failed to convert this callback to use WeakPtr(). BUG=128178 TEST=manual test Review URL: https://chromiumcodereview.appspot.com/10408006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137635 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void FileSystemOperation::GetUsageAndQuotaThenRunTask( const GURL& origin, FileSystemType type, const base::Closure& task, const base::Closure& error_callback) { quota::QuotaManagerProxy* quota_manager_proxy = file_system_context()->quota_manager_proxy(); if (!quota_manager_proxy || !file_system_context()->GetQuotaUtil(type)) { operation_context_.set_allowed_bytes_growth(kint64max); task.Run(); return; } TaskParamsForDidGetQuota params; params.origin = origin; params.type = type; params.task = task; params.error_callback = error_callback; DCHECK(quota_manager_proxy); DCHECK(quota_manager_proxy->quota_manager()); quota_manager_proxy->quota_manager()->GetUsageAndQuota( origin, FileSystemTypeToQuotaStorageType(type), base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask, weak_factory_.GetWeakPtr(), params)); }
170,762
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: size_t jsuGetFreeStack() { #ifdef ARM void *frame = __builtin_frame_address(0); size_t stackPos = (size_t)((char*)frame); size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! return stackPos - stackEnd; #elif defined(LINUX) char ptr; // this is on the stack extern void *STACK_BASE; uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); return 1000000 - count; // give it 1 megabyte of stack #else return 1000000; // no stack depth check on this platform #endif } Commit Message: Fix stack size detection on Linux (fix #1427) CWE ID: CWE-190
size_t jsuGetFreeStack() { #ifdef ARM void *frame = __builtin_frame_address(0); size_t stackPos = (size_t)((char*)frame); size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! return stackPos - stackEnd; #elif defined(LINUX) char ptr; // this is on the stack extern void *STACK_BASE; uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); const uint32_t max_stack = 1000000; // give it 1 megabyte of stack if (count>max_stack) return 0; return max_stack - count; #else return 1000000; // no stack depth check on this platform #endif }
169,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IsSiteMuted(const TabStripModel& tab_strip, const int index) { content::WebContents* web_contents = tab_strip.GetWebContentsAt(index); GURL url = web_contents->GetLastCommittedURL(); if (url.SchemeIs(content::kChromeUIScheme)) { return web_contents->IsAudioMuted() && GetTabAudioMutedReason(web_contents) == TabMutedReason::CONTENT_SETTING_CHROME; } Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); return settings->GetContentSetting(url, url, CONTENT_SETTINGS_TYPE_SOUND, std::string()) == CONTENT_SETTING_BLOCK; } Commit Message: Fix nullptr crash in IsSiteMuted This CL adds a nullptr check in IsSiteMuted to prevent a crash on Mac. Bug: 797647 Change-Id: Ic36f0fb39f2dbdf49d2bec9e548a4a6e339dc9a2 Reviewed-on: https://chromium-review.googlesource.com/848245 Reviewed-by: Mounir Lamouri <mlamouri@chromium.org> Reviewed-by: Yuri Wiitala <miu@chromium.org> Commit-Queue: Tommy Steimel <steimel@chromium.org> Cr-Commit-Position: refs/heads/master@{#526825} CWE ID:
bool IsSiteMuted(const TabStripModel& tab_strip, const int index) { content::WebContents* web_contents = tab_strip.GetWebContentsAt(index); // TODO(steimel): Why was this not a problem for AreAllTabsMuted? Is this // going to be a problem for SetSitesMuted? // Prevent crashes with null WebContents (https://crbug.com/797647). if (!web_contents) return false; GURL url = web_contents->GetLastCommittedURL(); if (url.SchemeIs(content::kChromeUIScheme)) { return web_contents->IsAudioMuted() && GetTabAudioMutedReason(web_contents) == TabMutedReason::CONTENT_SETTING_CHROME; } Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); return settings->GetContentSetting(url, url, CONTENT_SETTINGS_TYPE_SOUND, std::string()) == CONTENT_SETTING_BLOCK; }
171,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long media_device_enum_entities(struct media_device *mdev, struct media_entity_desc __user *uent) { struct media_entity *ent; struct media_entity_desc u_ent; if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id))) return -EFAULT; ent = find_entity(mdev, u_ent.id); if (ent == NULL) return -EINVAL; u_ent.id = ent->id; if (ent->name) { strncpy(u_ent.name, ent->name, sizeof(u_ent.name)); u_ent.name[sizeof(u_ent.name) - 1] = '\0'; } else { memset(u_ent.name, 0, sizeof(u_ent.name)); } u_ent.type = ent->type; u_ent.revision = ent->revision; u_ent.flags = ent->flags; u_ent.group_id = ent->group_id; u_ent.pads = ent->num_pads; u_ent.links = ent->num_links - ent->num_backlinks; memcpy(&u_ent.raw, &ent->info, sizeof(ent->info)); if (copy_to_user(uent, &u_ent, sizeof(u_ent))) return -EFAULT; return 0; } Commit Message: [media] media-device: fix infoleak in ioctl media_enum_entities() This fixes CVE-2014-1739. Signed-off-by: Salva Peiró <speiro@ai2.upv.es> Acked-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com> Cc: stable@vger.kernel.org Signed-off-by: Mauro Carvalho Chehab <m.chehab@samsung.com> CWE ID: CWE-200
static long media_device_enum_entities(struct media_device *mdev, struct media_entity_desc __user *uent) { struct media_entity *ent; struct media_entity_desc u_ent; memset(&u_ent, 0, sizeof(u_ent)); if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id))) return -EFAULT; ent = find_entity(mdev, u_ent.id); if (ent == NULL) return -EINVAL; u_ent.id = ent->id; if (ent->name) { strncpy(u_ent.name, ent->name, sizeof(u_ent.name)); u_ent.name[sizeof(u_ent.name) - 1] = '\0'; } else { memset(u_ent.name, 0, sizeof(u_ent.name)); } u_ent.type = ent->type; u_ent.revision = ent->revision; u_ent.flags = ent->flags; u_ent.group_id = ent->group_id; u_ent.pads = ent->num_pads; u_ent.links = ent->num_links - ent->num_backlinks; memcpy(&u_ent.raw, &ent->info, sizeof(ent->info)); if (copy_to_user(uent, &u_ent, sizeof(u_ent))) return -EFAULT; return 0; }
166,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void f2fs_put_super(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int i; f2fs_quota_off_umount(sb); /* prevent remaining shrinker jobs */ mutex_lock(&sbi->umount_mutex); /* * We don't need to do checkpoint when superblock is clean. * But, the previous checkpoint was not done by umount, it needs to do * clean checkpoint again. */ if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) || !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { struct cp_control cpc = { .reason = CP_UMOUNT, }; write_checkpoint(sbi, &cpc); } /* be sure to wait for any on-going discard commands */ f2fs_wait_discard_bios(sbi); if (f2fs_discard_en(sbi) && !sbi->discard_blks) { struct cp_control cpc = { .reason = CP_UMOUNT | CP_TRIMMED, }; write_checkpoint(sbi, &cpc); } /* write_checkpoint can update stat informaion */ f2fs_destroy_stats(sbi); /* * normally superblock is clean, so we need to release this. * In addition, EIO will skip do checkpoint, we need this as well. */ release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); mutex_unlock(&sbi->umount_mutex); /* our cp_error case, we can wait for any writeback page */ f2fs_flush_merged_writes(sbi); iput(sbi->node_inode); iput(sbi->meta_inode); /* destroy f2fs internal modules */ destroy_node_manager(sbi); destroy_segment_manager(sbi); kfree(sbi->ckpt); f2fs_unregister_sysfs(sbi); sb->s_fs_info = NULL; if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->raw_super); destroy_device_list(sbi); mempool_destroy(sbi->write_io_dummy); #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif destroy_percpu_info(sbi); for (i = 0; i < NR_PAGE_TYPE; i++) kfree(sbi->write_io[i]); kfree(sbi); } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <qkrwngud825@gmail.com> Signed-off-by: Chao Yu <yuchao0@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-20
static void f2fs_put_super(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int i; f2fs_quota_off_umount(sb); /* prevent remaining shrinker jobs */ mutex_lock(&sbi->umount_mutex); /* * We don't need to do checkpoint when superblock is clean. * But, the previous checkpoint was not done by umount, it needs to do * clean checkpoint again. */ if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) || !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { struct cp_control cpc = { .reason = CP_UMOUNT, }; write_checkpoint(sbi, &cpc); } /* be sure to wait for any on-going discard commands */ f2fs_wait_discard_bios(sbi, true); if (f2fs_discard_en(sbi) && !sbi->discard_blks) { struct cp_control cpc = { .reason = CP_UMOUNT | CP_TRIMMED, }; write_checkpoint(sbi, &cpc); } /* write_checkpoint can update stat informaion */ f2fs_destroy_stats(sbi); /* * normally superblock is clean, so we need to release this. * In addition, EIO will skip do checkpoint, we need this as well. */ release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); mutex_unlock(&sbi->umount_mutex); /* our cp_error case, we can wait for any writeback page */ f2fs_flush_merged_writes(sbi); iput(sbi->node_inode); iput(sbi->meta_inode); /* destroy f2fs internal modules */ destroy_node_manager(sbi); destroy_segment_manager(sbi); kfree(sbi->ckpt); f2fs_unregister_sysfs(sbi); sb->s_fs_info = NULL; if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->raw_super); destroy_device_list(sbi); mempool_destroy(sbi->write_io_dummy); #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif destroy_percpu_info(sbi); for (i = 0; i < NR_PAGE_TYPE; i++) kfree(sbi->write_io[i]); kfree(sbi); }
169,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintingMessageFilter::OnUpdatePrintSettings( int document_cookie, const DictionaryValue& job_settings, IPC::Message* reply_msg) { scoped_refptr<printing::PrinterQuery> printer_query; print_job_manager_->PopPrinterQuery(document_cookie, &printer_query); if (printer_query.get()) { CancelableTask* task = NewRunnableMethod( this, &PrintingMessageFilter::OnUpdatePrintSettingsReply, printer_query, reply_msg); printer_query->SetSettings(job_settings, task); } } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintingMessageFilter::OnUpdatePrintSettings( int document_cookie, const DictionaryValue& job_settings, IPC::Message* reply_msg) { scoped_refptr<printing::PrinterQuery> printer_query; if (!print_job_manager_->printing_enabled()) { // Reply with NULL query. OnUpdatePrintSettingsReply(printer_query, reply_msg); return; } print_job_manager_->PopPrinterQuery(document_cookie, &printer_query); if (!printer_query.get()) printer_query = new printing::PrinterQuery; CancelableTask* task = NewRunnableMethod( this, &PrintingMessageFilter::OnUpdatePrintSettingsReply, printer_query, reply_msg); printer_query->SetSettings(job_settings, task); }
170,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DefragReverseSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p3, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p1, NULL); if (reassembled == NULL) goto end; if (IPV4_GET_HLEN(reassembled) != 20) goto end; if (IPV4_GET_IPLEN(reassembled) != 39) goto end; /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragReverseSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(IPPROTO_ICMP, id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p3, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p1, NULL); if (reassembled == NULL) goto end; if (IPV4_GET_HLEN(reassembled) != 20) goto end; if (IPV4_GET_IPLEN(reassembled) != 39) goto end; /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; }
168,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::GetIndex() const { return m_index; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::GetIndex() const Cluster::Cluster(Segment* pSegment, long idx, long long element_start /* long long element_size */) : m_pSegment(pSegment), m_element_start(element_start), m_index(idx), m_pos(element_start), m_element_size(-1 /* element_size */), m_timecode(-1), m_entries(NULL), m_entries_size(0), m_entries_count(-1) // means "has not been parsed yet" {} Cluster::~Cluster() { if (m_entries_count <= 0) return; BlockEntry** i = m_entries; BlockEntry** const j = m_entries + m_entries_count; while (i != j) { BlockEntry* p = *i++; assert(p); delete p; } delete[] m_entries; }
174,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = (uint64_t)mTimeToSampleCount * 2 * sizeof(uint32_t); if (allocSize > UINT32_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new (std::nothrow) uint32_t[mTimeToSampleCount * 2]; if (!mTimeToSample) return ERROR_OUT_OF_RANGE; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (!mTimeToSample.empty() || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { // Choose this bound because // 1) 2 * sizeof(uint32_t) is the amount of memory needed for one // time-to-sample entry in the time-to-sample table. // 2) mTimeToSampleCount is the number of entries of the time-to-sample // table. // 3) We hope that the table size does not exceed UINT32_MAX. ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } // Note: At this point, we know that mTimeToSampleCount * 2 will not // overflow because of the above condition. if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } return OK; }
174,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UriSuite() { TEST_ADD(UriSuite::testDistinction) TEST_ADD(UriSuite::testIpFour) TEST_ADD(UriSuite::testIpSixPass) TEST_ADD(UriSuite::testIpSixFail) TEST_ADD(UriSuite::testUri) TEST_ADD(UriSuite::testUriUserInfoHostPort1) TEST_ADD(UriSuite::testUriUserInfoHostPort2) TEST_ADD(UriSuite::testUriUserInfoHostPort22_Bug1948038) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_1) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_2) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_3) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_4) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_1) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_12) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_2) TEST_ADD(UriSuite::testUriUserInfoHostPort3) TEST_ADD(UriSuite::testUriUserInfoHostPort4) TEST_ADD(UriSuite::testUriUserInfoHostPort5) TEST_ADD(UriSuite::testUriUserInfoHostPort6) TEST_ADD(UriSuite::testUriHostRegname) TEST_ADD(UriSuite::testUriHostIpFour1) TEST_ADD(UriSuite::testUriHostIpFour2) TEST_ADD(UriSuite::testUriHostIpSix1) TEST_ADD(UriSuite::testUriHostIpSix2) TEST_ADD(UriSuite::testUriHostIpFuture) TEST_ADD(UriSuite::testUriHostEmpty) TEST_ADD(UriSuite::testUriComponents) TEST_ADD(UriSuite::testUriComponents_Bug20070701) TEST_ADD(UriSuite::testEscaping) TEST_ADD(UriSuite::testUnescaping) TEST_ADD(UriSuite::testTrailingSlash) TEST_ADD(UriSuite::testAddBase) TEST_ADD(UriSuite::testToString) TEST_ADD(UriSuite::testToString_Bug1950126) TEST_ADD(UriSuite::testToStringCharsRequired) TEST_ADD(UriSuite::testToStringCharsRequired) TEST_ADD(UriSuite::testNormalizeSyntaxMaskRequired) TEST_ADD(UriSuite::testNormalizeSyntax) TEST_ADD(UriSuite::testNormalizeSyntaxComponents) TEST_ADD(UriSuite::testNormalizeCrash_Bug20080224) TEST_ADD(UriSuite::testFilenameUriConversion) TEST_ADD(UriSuite::testCrash_FreeUriMembers_Bug20080116) TEST_ADD(UriSuite::testCrash_Report2418192) TEST_ADD(UriSuite::testPervertedQueryString); TEST_ADD(UriSuite::testQueryStringEndingInEqualSign_NonBug32); TEST_ADD(UriSuite::testCrash_MakeOwner_Bug20080207) TEST_ADD(UriSuite::testQueryList) TEST_ADD(UriSuite::testQueryListPair) TEST_ADD(UriSuite::testQueryDissection_Bug3590761) TEST_ADD(UriSuite::testFreeCrash_Bug20080827) TEST_ADD(UriSuite::testParseInvalid_Bug16) TEST_ADD(UriSuite::testRangeComparison) TEST_ADD(UriSuite::testRangeComparison_RemoveBaseUri_Issue19) TEST_ADD(UriSuite::testEquals) TEST_ADD(UriSuite::testHostTextTermination_Issue15) } Commit Message: UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex Reported by Google Autofuzz team CWE ID: CWE-787
UriSuite() { TEST_ADD(UriSuite::testDistinction) TEST_ADD(UriSuite::testIpFour) TEST_ADD(UriSuite::testIpSixPass) TEST_ADD(UriSuite::testIpSixFail) TEST_ADD(UriSuite::testUri) TEST_ADD(UriSuite::testUriUserInfoHostPort1) TEST_ADD(UriSuite::testUriUserInfoHostPort2) TEST_ADD(UriSuite::testUriUserInfoHostPort22_Bug1948038) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_1) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_2) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_3) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_4) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_1) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_12) TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_2) TEST_ADD(UriSuite::testUriUserInfoHostPort3) TEST_ADD(UriSuite::testUriUserInfoHostPort4) TEST_ADD(UriSuite::testUriUserInfoHostPort5) TEST_ADD(UriSuite::testUriUserInfoHostPort6) TEST_ADD(UriSuite::testUriHostRegname) TEST_ADD(UriSuite::testUriHostIpFour1) TEST_ADD(UriSuite::testUriHostIpFour2) TEST_ADD(UriSuite::testUriHostIpSix1) TEST_ADD(UriSuite::testUriHostIpSix2) TEST_ADD(UriSuite::testUriHostIpFuture) TEST_ADD(UriSuite::testUriHostEmpty) TEST_ADD(UriSuite::testUriComponents) TEST_ADD(UriSuite::testUriComponents_Bug20070701) TEST_ADD(UriSuite::testEscaping) TEST_ADD(UriSuite::testUnescaping) TEST_ADD(UriSuite::testTrailingSlash) TEST_ADD(UriSuite::testAddBase) TEST_ADD(UriSuite::testToString) TEST_ADD(UriSuite::testToString_Bug1950126) TEST_ADD(UriSuite::testToStringCharsRequired) TEST_ADD(UriSuite::testToStringCharsRequired) TEST_ADD(UriSuite::testNormalizeSyntaxMaskRequired) TEST_ADD(UriSuite::testNormalizeSyntax) TEST_ADD(UriSuite::testNormalizeSyntaxComponents) TEST_ADD(UriSuite::testNormalizeCrash_Bug20080224) TEST_ADD(UriSuite::testFilenameUriConversion) TEST_ADD(UriSuite::testCrash_FreeUriMembers_Bug20080116) TEST_ADD(UriSuite::testCrash_Report2418192) TEST_ADD(UriSuite::testPervertedQueryString); TEST_ADD(UriSuite::testQueryStringEndingInEqualSign_NonBug32); TEST_ADD(UriSuite::testCrash_MakeOwner_Bug20080207) TEST_ADD(UriSuite::testQueryList) TEST_ADD(UriSuite::testQueryListPair) TEST_ADD(UriSuite::testQueryDissection_Bug3590761) TEST_ADD(UriSuite::testQueryCompositionMathWrite_GoogleAutofuzz113244572) TEST_ADD(UriSuite::testFreeCrash_Bug20080827) TEST_ADD(UriSuite::testParseInvalid_Bug16) TEST_ADD(UriSuite::testRangeComparison) TEST_ADD(UriSuite::testRangeComparison_RemoveBaseUri_Issue19) TEST_ADD(UriSuite::testEquals) TEST_ADD(UriSuite::testHostTextTermination_Issue15) }
168,977
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { ActionReply reply; reply.addData("mh_mountpoint", args["mh_mountpoint"]); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); command << args["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << args["mh_command"].toString(); command << args["mh_options"].toStringList(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool user_kill = false; QStringList command; #if defined(Q_OS_LINUX) command << args["mh_command"].toString(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); command << args["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << args["mh_command"].toString(); command << args["mh_options"].toStringList(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); { } if (HelperSupport::isStopped()) { proc.kill(); user_kill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!user_kill) { reply.setErrorCode(ActionReply::HelperError); reply.setErrorDescription(i18n("The mount process crashed.")); return reply; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData("mh_error_message", stdErr.trimmed()); } } Commit Message: CWE ID: CWE-20
ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { ActionReply reply; // // Get the mount executable // const QString mount = findMountExecutable(); // // Check the executable // if (mount != args["mh_command"].toString()) { // Something weird is going on, bail out. reply.setErrorCode(ActionReply::HelperError); reply.setErrorDescription(i18n("Wrong executable passed. Bailing out.")); return reply; } else { // Do nothing } reply.addData("mh_mountpoint", args["mh_mountpoint"]); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); command << args["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << args["mh_command"].toString(); command << args["mh_options"].toStringList(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool user_kill = false; QStringList command; #if defined(Q_OS_LINUX) command << mount; command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); command << args["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << mount; command << args["mh_options"].toStringList(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); { } if (HelperSupport::isStopped()) { proc.kill(); user_kill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!user_kill) { reply.setErrorCode(ActionReply::HelperError); reply.setErrorDescription(i18n("The mount process crashed.")); return reply; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData("mh_error_message", stdErr.trimmed()); } }
164,826
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s) { static const char module[] = "PredictorEncodeTile"; TIFFPredictorState *sp = PredictorState(tif); uint8 *working_copy; tmsize_t cc = cc0, rowsize; unsigned char* bp; int result_code; assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encodetile != NULL); /* * Do predictor manipulation in a working buffer to avoid altering * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965 */ working_copy = (uint8*) _TIFFmalloc(cc0); if( working_copy == NULL ) { TIFFErrorExt(tif->tif_clientdata, module, "Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.", cc0 ); return 0; } memcpy( working_copy, bp0, cc0 ); bp = working_copy; rowsize = sp->rowsize; assert(rowsize > 0); if((cc0%rowsize)!=0) { TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile", "%s", "(cc0%rowsize)!=0"); return 0; } while (cc > 0) { (*sp->encodepfunc)(tif, bp, rowsize); cc -= rowsize; bp += rowsize; } result_code = (*sp->encodetile)(tif, working_copy, cc0, s); _TIFFfree( working_copy ); return result_code; } Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in previous commit (fix for MSVR 35105) CWE ID: CWE-119
PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s) { static const char module[] = "PredictorEncodeTile"; TIFFPredictorState *sp = PredictorState(tif); uint8 *working_copy; tmsize_t cc = cc0, rowsize; unsigned char* bp; int result_code; assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encodetile != NULL); /* * Do predictor manipulation in a working buffer to avoid altering * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965 */ working_copy = (uint8*) _TIFFmalloc(cc0); if( working_copy == NULL ) { TIFFErrorExt(tif->tif_clientdata, module, "Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.", cc0 ); return 0; } memcpy( working_copy, bp0, cc0 ); bp = working_copy; rowsize = sp->rowsize; assert(rowsize > 0); if((cc0%rowsize)!=0) { TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile", "%s", "(cc0%rowsize)!=0"); _TIFFfree( working_copy ); return 0; } while (cc > 0) { (*sp->encodepfunc)(tif, bp, rowsize); cc -= rowsize; bp += rowsize; } result_code = (*sp->encodetile)(tif, working_copy, cc0, s); _TIFFfree( working_copy ); return result_code; }
169,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SeekHead::ParseEntry(IMkvReader* pReader, long long start, long long size_, Entry* pEntry) { if (size_ <= 0) return false; long long pos = start; const long long stop = start + size_; long len; const long long seekIdId = ReadUInt(pReader, pos, len); if (seekIdId != 0x13AB) // SeekID ID return false; if ((pos + len) > stop) return false; pos += len; // consume SeekID id const long long seekIdSize = ReadUInt(pReader, pos, len); if (seekIdSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size of field if ((pos + seekIdSize) > stop) return false; pEntry->id = ReadUInt(pReader, pos, len); // payload if (pEntry->id <= 0) return false; if (len != seekIdSize) return false; pos += seekIdSize; // consume SeekID payload const long long seekPosId = ReadUInt(pReader, pos, len); if (seekPosId != 0x13AC) // SeekPos ID return false; if ((pos + len) > stop) return false; pos += len; // consume id const long long seekPosSize = ReadUInt(pReader, pos, len); if (seekPosSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size if ((pos + seekPosSize) > stop) return false; pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); if (pEntry->pos < 0) return false; pos += seekPosSize; // consume payload if (pos != stop) return false; return true; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
bool SeekHead::ParseEntry(IMkvReader* pReader, long long start, long long size_, Entry* pEntry) { if (size_ <= 0) return false; long long pos = start; const long long stop = start + size_; long len; const long long seekIdId = ReadID(pReader, pos, len); if (seekIdId < 0) return false; if (seekIdId != 0x13AB) // SeekID ID return false; if ((pos + len) > stop) return false; pos += len; // consume SeekID id const long long seekIdSize = ReadUInt(pReader, pos, len); if (seekIdSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size of field if ((pos + seekIdSize) > stop) return false; pEntry->id = ReadUInt(pReader, pos, len); // payload if (pEntry->id <= 0) return false; if (len != seekIdSize) return false; pos += seekIdSize; // consume SeekID payload const long long seekPosId = ReadUInt(pReader, pos, len); if (seekPosId != 0x13AC) // SeekPos ID return false; if ((pos + len) > stop) return false; pos += len; // consume id const long long seekPosSize = ReadUInt(pReader, pos, len); if (seekPosSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size if ((pos + seekPosSize) > stop) return false; pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); if (pEntry->pos < 0) return false; pos += seekPosSize; // consume payload if (pos != stop) return false; return true; }
173,855
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickPixelPacket **AcquirePixelThreadSet(const Image *image) { MagickPixelPacket **pixels; register ssize_t i, j; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) GetMagickPixelPacket(image,&pixels[i][j]); } return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1586 CWE ID: CWE-119
static MagickPixelPacket **AcquirePixelThreadSet(const Image *image) static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); }
169,601
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int vol_prc_lib_release(effect_handle_t handle) { struct listnode *node, *temp_node_next; vol_listener_context_t *context = NULL; vol_listener_context_t *recv_contex = (vol_listener_context_t *)handle; int status = -1; bool recompute_flag = false; int active_stream_count = 0; ALOGV("%s context %p", __func__, handle); pthread_mutex_lock(&vol_listner_init_lock); list_for_each_safe(node, temp_node_next, &vol_effect_list) { context = node_to_item(node, struct vol_listener_context_s, effect_list_node); if ((memcmp(&(context->desc->uuid), &(recv_contex->desc->uuid), sizeof(effect_uuid_t)) == 0) && (context->session_id == recv_contex->session_id) && (context->stream_type == recv_contex->stream_type)) { ALOGV("--- Found something to remove ---"); list_remove(&context->effect_list_node); PRINT_STREAM_TYPE(context->stream_type); if (context->dev_id && AUDIO_DEVICE_OUT_SPEAKER) { recompute_flag = true; } free(context); status = 0; } else { ++active_stream_count; } } if (status != 0) { ALOGE("something wrong ... <<<--- Found NOTHING to remove ... ???? --->>>>>"); } if (active_stream_count == 0) { current_gain_dep_cal_level = -1; current_vol = 0.0; } if (recompute_flag) { check_and_set_gain_dep_cal(); } if (dumping_enabled) { dump_list_l(); } pthread_mutex_unlock(&vol_listner_init_lock); return status; } Commit Message: post proc : volume listener : fix effect release crash Fix access to deleted effect context in vol_prc_lib_release() Bug: 25753245. Change-Id: I64ca99e4d5d09667be4c8c605f66700b9ae67949 (cherry picked from commit 93ab6fdda7b7557ccb34372670c30fa6178f8426) CWE ID: CWE-119
static int vol_prc_lib_release(effect_handle_t handle) { struct listnode *node, *temp_node_next; vol_listener_context_t *context = NULL; vol_listener_context_t *recv_contex = (vol_listener_context_t *)handle; int status = -EINVAL; bool recompute_flag = false; int active_stream_count = 0; uint32_t session_id; uint32_t stream_type; effect_uuid_t uuid; ALOGV("%s context %p", __func__, handle); if (recv_contex == NULL) { return status; } pthread_mutex_lock(&vol_listner_init_lock); session_id = recv_contex->session_id; stream_type = recv_contex->stream_type; uuid = recv_contex->desc->uuid; list_for_each_safe(node, temp_node_next, &vol_effect_list) { context = node_to_item(node, struct vol_listener_context_s, effect_list_node); if ((memcmp(&(context->desc->uuid), &uuid, sizeof(effect_uuid_t)) == 0) && (context->session_id == session_id) && (context->stream_type == stream_type)) { ALOGV("--- Found something to remove ---"); list_remove(node); PRINT_STREAM_TYPE(context->stream_type); if (context->dev_id && AUDIO_DEVICE_OUT_SPEAKER) { recompute_flag = true; } free(context); status = 0; } else { ++active_stream_count; } } if (status != 0) { ALOGE("something wrong ... <<<--- Found NOTHING to remove ... ???? --->>>>>"); pthread_mutex_unlock(&vol_listner_init_lock); return status; } if (active_stream_count == 0) { current_gain_dep_cal_level = -1; current_vol = 0.0; } if (recompute_flag) { check_and_set_gain_dep_cal(); } if (dumping_enabled) { dump_list_l(); } pthread_mutex_unlock(&vol_listner_init_lock); return status; }
173,916
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UpdateContentLengthPrefs(int received_content_length, int original_content_length, bool via_data_reduction_proxy) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); if (!g_browser_process) return; PrefService* prefs = g_browser_process->local_state(); if (!prefs) return; #if defined(OS_ANDROID) bool with_data_reduction_proxy_enabled = g_browser_process->profile_manager()->GetDefaultProfile()-> GetPrefs()->GetBoolean(prefs::kSpdyProxyAuthEnabled); #else bool with_data_reduction_proxy_enabled = false; #endif chrome_browser_net::UpdateContentLengthPrefs( received_content_length, original_content_length, with_data_reduction_proxy_enabled, via_data_reduction_proxy, prefs); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void UpdateContentLengthPrefs(int received_content_length, void UpdateContentLengthPrefs( int received_content_length, int original_content_length, chrome_browser_net::DataReductionRequestType data_reduction_type) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); if (!g_browser_process) return; PrefService* prefs = g_browser_process->local_state(); if (!prefs) return; #if defined(OS_ANDROID) bool with_data_reduction_proxy_enabled = g_browser_process->profile_manager()->GetDefaultProfile()-> GetPrefs()->GetBoolean(prefs::kSpdyProxyAuthEnabled); #else bool with_data_reduction_proxy_enabled = false; #endif chrome_browser_net::UpdateContentLengthPrefs( received_content_length, original_content_length, with_data_reduction_proxy_enabled, data_reduction_type, prefs); }
171,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_tRNS_to_alpha_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* We don't know yet whether there will be a tRNS chunk, but we know that * this transformation should do nothing if there already is an alpha * channel. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_tRNS_to_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* We don't know yet whether there will be a tRNS chunk, but we know that * this transformation should do nothing if there already is an alpha * channel. In addition, after the bug fix in 1.7.0, there is no longer * any action on a palette image. */ return # if PNG_LIBPNG_VER >= 10700 colour_type != PNG_COLOR_TYPE_PALETTE && # endif (colour_type & PNG_COLOR_MASK_ALPHA) == 0; }
173,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(ctcptype); Q_UNUSED(target); if(!_ignoreListManager->ctcpMatch(prefix, network()->networkName())) { QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix); if(!param.isEmpty()) str.append(tr(" with arguments: %1").arg(param)); emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str); } } Commit Message: CWE ID: CWE-399
void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param, QString &reply) { Q_UNUSED(ctcptype); Q_UNUSED(target); Q_UNUSED(reply); QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix); if(!param.isEmpty()) str.append(tr(" with arguments: %1").arg(param)); emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str); }
164,876
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,"wb"); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MaxTextExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf("Detected:%s \n",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent); /* Read nested image */ /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickString(image2->filename,image->filename,MaxTextExtent); (void) CopyMagickString(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickString(image2->magick,image->magick,MaxTextExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); } Commit Message: ... CWE ID: CWE-189
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,"wb"); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MaxTextExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf("Detected:%s \n",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent-1); /* Read nested image */ /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickString(image2->filename,image->filename,MaxTextExtent); (void) CopyMagickString(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickString(image2->magick,image->magick,MaxTextExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); }
168,524
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IPC::PlatformFileForTransit ProxyChannelDelegate::ShareHandleWithRemote( base::PlatformFile handle, const IPC::SyncChannel& channel, bool should_close_source) { return content::BrokerGetFileHandleForProcess(handle, channel.peer_pid(), should_close_source); } 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
IPC::PlatformFileForTransit ProxyChannelDelegate::ShareHandleWithRemote(
170,738
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { RFlagsAtOffset *flags = NULL; RFlagsAtOffset key; key.off = off; if (dir >= 0) { flags = r_skiplist_get_geq (f->by_off, &key); } else { flags = r_skiplist_get_leq (f->by_off, &key); } if (dir == 0 && flags && flags->off != off) { return NULL; } return flags; } Commit Message: Fix crash in wasm disassembler CWE ID: CWE-125
static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { RFlagsAtOffset *flags = NULL; RFlagsAtOffset key; key.off = off; if (dir >= 0) { flags = r_skiplist_get_geq (f->by_off, &key); } else { flags = r_skiplist_get_leq (f->by_off, &key); } if (dir == 0 && flags && flags->off != off) { return NULL; } return flags; }
167,723
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info, size_t* gc_info_index_slot) { DCHECK(gc_info); DCHECK(gc_info_index_slot); DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, ()); MutexLocker locker(mutex); if (*gc_info_index_slot) return; int index = ++gc_info_index_; size_t gc_info_index = static_cast<size_t>(index); CHECK(gc_info_index < GCInfoTable::kMaxIndex); if (gc_info_index >= gc_info_table_size_) Resize(); g_gc_info_table[gc_info_index] = gc_info; ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <mlippautz@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info, size_t* gc_info_index_slot) { DCHECK(gc_info); DCHECK(gc_info_index_slot); // Ensuring a new index involves current index adjustment as well // as potentially resizing the table, both operations that require // a lock. MutexLocker locker(table_mutex_); if (*gc_info_index_slot) return; int index = ++current_index_; size_t gc_info_index = static_cast<size_t>(index); CHECK(gc_info_index < GCInfoTable::kMaxIndex); if (current_index_ >= limit_) Resize(); table_[gc_info_index] = gc_info; ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index); }
173,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void IndexedDBCursor::RemoveCursorFromTransaction() { if (transaction_) transaction_->UnregisterOpenCursor(this); } Commit Message: [IndexedDB] Fix Cursor UAF If the connection is closed before we return a cursor, it dies in IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on the correct thread, but we also need to makes sure to remove it from its transaction. To make things simpler, we have the cursor remove itself from its transaction on destruction. R: pwnall@chromium.org Bug: 728887 Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2 Reviewed-on: https://chromium-review.googlesource.com/526284 Commit-Queue: Daniel Murphy <dmurph@chromium.org> Reviewed-by: Victor Costan <pwnall@chromium.org> Cr-Commit-Position: refs/heads/master@{#477504} CWE ID: CWE-416
void IndexedDBCursor::RemoveCursorFromTransaction() {
172,307
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageBitmapFactories::ImageBitmapLoader::DidFinishLoading() { DOMArrayBuffer* array_buffer = loader_->ArrayBufferResult(); if (!array_buffer) { RejectPromise(kAllocationFailureImageBitmapRejectionReason); return; } ScheduleAsyncImageBitmapDecoding(array_buffer); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::ImageBitmapLoader::DidFinishLoading() { DOMArrayBuffer* array_buffer = loader_->ArrayBufferResult(); loader_.reset(); if (!array_buffer) { RejectPromise(kAllocationFailureImageBitmapRejectionReason); return; } ScheduleAsyncImageBitmapDecoding(array_buffer); }
173,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DrawingBuffer::DrawingBuffer( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, std::unique_ptr<Extensions3DUtil> extensions_util, Client* client, bool discard_framebuffer_supported, bool want_alpha_channel, bool premultiplied_alpha, PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, bool want_depth, bool want_stencil, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) : client_(client), preserve_drawing_buffer_(preserve), web_gl_version_(web_gl_version), context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper( std::move(context_provider)))), gl_(this->ContextProvider()->ContextGL()), extensions_util_(std::move(extensions_util)), discard_framebuffer_supported_(discard_framebuffer_supported), want_alpha_channel_(want_alpha_channel), premultiplied_alpha_(premultiplied_alpha), software_rendering_(this->ContextProvider()->IsSoftwareRendering()), want_depth_(want_depth), want_stencil_(want_stencil), color_space_(color_params.GetGfxColorSpace()), chromium_image_usage_(chromium_image_usage) { TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation", TRACE_EVENT_SCOPE_GLOBAL); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
DrawingBuffer::DrawingBuffer( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, std::unique_ptr<Extensions3DUtil> extensions_util, Client* client, bool discard_framebuffer_supported, bool want_alpha_channel, bool premultiplied_alpha, PreserveDrawingBuffer preserve, WebGLVersion webgl_version, bool want_depth, bool want_stencil, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) : client_(client), preserve_drawing_buffer_(preserve), webgl_version_(webgl_version), context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper( std::move(context_provider)))), gl_(this->ContextProvider()->ContextGL()), extensions_util_(std::move(extensions_util)), discard_framebuffer_supported_(discard_framebuffer_supported), want_alpha_channel_(want_alpha_channel), premultiplied_alpha_(premultiplied_alpha), software_rendering_(this->ContextProvider()->IsSoftwareRendering()), want_depth_(want_depth), want_stencil_(want_stencil), color_space_(color_params.GetGfxColorSpace()), chromium_image_usage_(chromium_image_usage) { TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation", TRACE_EVENT_SCOPE_GLOBAL); }
172,291
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ObserverOnLogoAvailable(LogoObserver* observer, bool from_cache, LogoCallbackReason type, const base::Optional<Logo>& logo) { switch (type) { case LogoCallbackReason::DISABLED: case LogoCallbackReason::CANCELED: case LogoCallbackReason::FAILED: break; case LogoCallbackReason::REVALIDATED: break; case LogoCallbackReason::DETERMINED: observer->OnLogoAvailable(logo ? &logo.value() : nullptr, from_cache); break; } if (!from_cache) { observer->OnObserverRemoved(); } } 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 ObserverOnLogoAvailable(LogoObserver* observer,
171,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LoginHtmlDialog::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type.value == NotificationType::LOAD_COMPLETED_MAIN_FRAME); if (bubble_frame_view_) bubble_frame_view_->StopThrobber(); } Commit Message: cros: The next 100 clang plugin errors. BUG=none TEST=none TBR=dpolukhin Review URL: http://codereview.chromium.org/7022008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85418 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void LoginHtmlDialog::Observe(NotificationType type,
170,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Maybe<bool> CollectValuesOrEntriesImpl( Isolate* isolate, Handle<JSObject> object, Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items, PropertyFilter filter) { int count = 0; KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES); Subclass::CollectElementIndicesImpl( object, handle(object->elements(), isolate), &accumulator); Handle<FixedArray> keys = accumulator.GetKeys(); for (int i = 0; i < keys->length(); ++i) { Handle<Object> key(keys->get(i), isolate); Handle<Object> value; uint32_t index; if (!key->ToUint32(&index)) continue; uint32_t entry = Subclass::GetEntryForIndexImpl( isolate, *object, object->elements(), index, filter); if (entry == kMaxUInt32) continue; PropertyDetails details = Subclass::GetDetailsImpl(*object, entry); if (details.kind() == kData) { value = Subclass::GetImpl(isolate, object->elements(), entry); } else { LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(&it), Nothing<bool>()); } if (get_entries) { value = MakeEntryPair(isolate, index, value); } values_or_entries->set(count++, *value); } *nof_items = count; return Just(true); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704
static Maybe<bool> CollectValuesOrEntriesImpl( Isolate* isolate, Handle<JSObject> object, Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items, PropertyFilter filter) { DCHECK_EQ(*nof_items, 0); KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES); Subclass::CollectElementIndicesImpl( object, handle(object->elements(), isolate), &accumulator); Handle<FixedArray> keys = accumulator.GetKeys(); int count = 0; int i = 0; Handle<Map> original_map(object->map(), isolate); for (; i < keys->length(); ++i) { Handle<Object> key(keys->get(i), isolate); uint32_t index; if (!key->ToUint32(&index)) continue; DCHECK_EQ(object->map(), *original_map); uint32_t entry = Subclass::GetEntryForIndexImpl( isolate, *object, object->elements(), index, filter); if (entry == kMaxUInt32) continue; PropertyDetails details = Subclass::GetDetailsImpl(*object, entry); Handle<Object> value; if (details.kind() == kData) { value = Subclass::GetImpl(isolate, object->elements(), entry); } else { // This might modify the elements and/or change the elements kind. LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(&it), Nothing<bool>()); } if (get_entries) value = MakeEntryPair(isolate, index, value); values_or_entries->set(count++, *value); if (object->map() != *original_map) break; } // Slow path caused by changes in elements kind during iteration. for (; i < keys->length(); i++) { Handle<Object> key(keys->get(i), isolate); uint32_t index; if (!key->ToUint32(&index)) continue; if (filter & ONLY_ENUMERABLE) { InternalElementsAccessor* accessor = reinterpret_cast<InternalElementsAccessor*>( object->GetElementsAccessor()); uint32_t entry = accessor->GetEntryForIndex(isolate, *object, object->elements(), index); if (entry == kMaxUInt32) continue; PropertyDetails details = accessor->GetDetails(*object, entry); if (!details.IsEnumerable()) continue; } Handle<Object> value; LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, value, Object::GetProperty(&it), Nothing<bool>()); if (get_entries) value = MakeEntryPair(isolate, index, value); values_or_entries->set(count++, *value); } *nof_items = count; return Just(true); }
174,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAMR::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 0) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (!isConfigured()) { amrParams->nBitRate = 0; amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused; } else { amrParams->nBitRate = 0; amrParams->eAMRBandMode = mMode == MODE_NARROW ? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->nChannels = 1; pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->nSamplingRate = (mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAMR::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(amrParams)) { return OMX_ErrorBadParameter; } if (amrParams->nPortIndex != 0) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (!isConfigured()) { amrParams->nBitRate = 0; amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused; } else { amrParams->nBitRate = 0; amrParams->eAMRBandMode = mMode == MODE_NARROW ? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->nChannels = 1; pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->nSamplingRate = (mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,192
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bittok2str_internal(register const struct tok *lp, register const char *fmt, register u_int v, const char *sep) { static char buf[256]; /* our stringbuffer */ int buflen=0; register u_int rotbit; /* this is the bit we rotate through all bitpositions */ register u_int tokval; const char * sepstr = ""; while (lp != NULL && lp->s != NULL) { tokval=lp->v; /* load our first value */ rotbit=1; while (rotbit != 0) { /* * lets AND the rotating bit with our token value * and see if we have got a match */ if (tokval == (v&rotbit)) { /* ok we have found something */ buflen+=snprintf(buf+buflen, sizeof(buf)-buflen, "%s%s", sepstr, lp->s); sepstr = sep; break; } rotbit=rotbit<<1; /* no match - lets shift and try again */ } lp++; } if (buflen == 0) /* bummer - lets print the "unknown" message as advised in the fmt string if we got one */ (void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%08x" : fmt, v); return (buf); } Commit Message: CVE-2017-13011/Properly check for buffer overflow in bittok2str_internal(). Also, make the buffer bigger. This fixes a buffer overflow discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-119
bittok2str_internal(register const struct tok *lp, register const char *fmt, register u_int v, const char *sep) { static char buf[1024+1]; /* our string buffer */ char *bufp = buf; size_t space_left = sizeof(buf), string_size; register u_int rotbit; /* this is the bit we rotate through all bitpositions */ register u_int tokval; const char * sepstr = ""; while (lp != NULL && lp->s != NULL) { tokval=lp->v; /* load our first value */ rotbit=1; while (rotbit != 0) { /* * lets AND the rotating bit with our token value * and see if we have got a match */ if (tokval == (v&rotbit)) { /* ok we have found something */ if (space_left <= 1) return (buf); /* only enough room left for NUL, if that */ string_size = strlcpy(bufp, sepstr, space_left); if (string_size >= space_left) return (buf); /* we ran out of room */ bufp += string_size; space_left -= string_size; if (space_left <= 1) return (buf); /* only enough room left for NUL, if that */ string_size = strlcpy(bufp, lp->s, space_left); if (string_size >= space_left) return (buf); /* we ran out of room */ bufp += string_size; space_left -= string_size; sepstr = sep; break; } rotbit=rotbit<<1; /* no match - lets shift and try again */ } lp++; } if (bufp == buf) /* bummer - lets print the "unknown" message as advised in the fmt string if we got one */ (void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%08x" : fmt, v); return (buf); }
167,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { struct dev_pagemap *pgmap = NULL; int nr_start = *nr, ret = 0; pte_t *ptep, *ptem; ptem = ptep = pte_offset_map(&pmd, addr); do { pte_t pte = gup_get_pte(ptep); struct page *head, *page; /* * Similar to the PMD case below, NUMA hinting must take slow * path using the pte_protnone check. */ if (pte_protnone(pte)) goto pte_unmap; if (!pte_access_permitted(pte, write)) goto pte_unmap; if (pte_devmap(pte)) { pgmap = get_dev_pagemap(pte_pfn(pte), pgmap); if (unlikely(!pgmap)) { undo_dev_pagemap(nr, nr_start, pages); goto pte_unmap; } } else if (pte_special(pte)) goto pte_unmap; VM_BUG_ON(!pfn_valid(pte_pfn(pte))); page = pte_page(pte); head = compound_head(page); if (!page_cache_get_speculative(head)) goto pte_unmap; if (unlikely(pte_val(pte) != pte_val(*ptep))) { put_page(head); goto pte_unmap; } VM_BUG_ON_PAGE(compound_head(page) != head, page); SetPageReferenced(page); pages[*nr] = page; (*nr)++; } while (ptep++, addr += PAGE_SIZE, addr != end); ret = 1; pte_unmap: if (pgmap) put_dev_pagemap(pgmap); pte_unmap(ptem); return ret; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { struct dev_pagemap *pgmap = NULL; int nr_start = *nr, ret = 0; pte_t *ptep, *ptem; ptem = ptep = pte_offset_map(&pmd, addr); do { pte_t pte = gup_get_pte(ptep); struct page *head, *page; /* * Similar to the PMD case below, NUMA hinting must take slow * path using the pte_protnone check. */ if (pte_protnone(pte)) goto pte_unmap; if (!pte_access_permitted(pte, write)) goto pte_unmap; if (pte_devmap(pte)) { pgmap = get_dev_pagemap(pte_pfn(pte), pgmap); if (unlikely(!pgmap)) { undo_dev_pagemap(nr, nr_start, pages); goto pte_unmap; } } else if (pte_special(pte)) goto pte_unmap; VM_BUG_ON(!pfn_valid(pte_pfn(pte))); page = pte_page(pte); head = try_get_compound_head(page, 1); if (!head) goto pte_unmap; if (unlikely(pte_val(pte) != pte_val(*ptep))) { put_page(head); goto pte_unmap; } VM_BUG_ON_PAGE(compound_head(page) != head, page); SetPageReferenced(page); pages[*nr] = page; (*nr)++; } while (ptep++, addr += PAGE_SIZE, addr != end); ret = 1; pte_unmap: if (pgmap) put_dev_pagemap(pgmap); pte_unmap(ptem); return ret; }
170,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual void RemoveObserver(Observer* observer) { virtual void RemoveObserver(InputMethodLibrary::Observer* observer) { observers_.RemoveObserver(observer); }
170,503
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* NOTE: we can actually pend the tRNS processing at this point because we * can correctly recognize the original pixel value even though we have * mapped the one gray channel to the three RGB ones, but in fact libpng * doesn't do this, so we don't either. */ if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS) image_pixel_add_alpha(that, &display->this); /* Simply expand the bit depth and alter the colour type as required. */ if (that->colour_type == PNG_COLOR_TYPE_GRAY) { /* RGB images have a bit depth at least equal to '8' */ if (that->bit_depth < 8) that->sample_depth = that->bit_depth = 8; /* And just changing the colour type works here because the green and blue * channels are being maintained in lock-step with the red/gray: */ that->colour_type = PNG_COLOR_TYPE_RGB; } else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this, image_transform_png_set_gray_to_rgb_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* NOTE: we can actually pend the tRNS processing at this point because we * can correctly recognize the original pixel value even though we have * mapped the one gray channel to the three RGB ones, but in fact libpng * doesn't do this, so we don't either. */ if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); /* Simply expand the bit depth and alter the colour type as required. */ if (that->colour_type == PNG_COLOR_TYPE_GRAY) { /* RGB images have a bit depth at least equal to '8' */ if (that->bit_depth < 8) that->sample_depth = that->bit_depth = 8; /* And just changing the colour type works here because the green and blue * channels are being maintained in lock-step with the red/gray: */ that->colour_type = PNG_COLOR_TYPE_RGB; } else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; this->next->mod(this->next, that, pp, display); }
173,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StopCastCallback( CastConfigDelegate* cast_config, const CastConfigDelegate::ReceiversAndActivites& receivers_activities) { for (auto& item : receivers_activities) { CastConfigDelegate::Activity activity = item.second.activity; if (activity.allow_stop && activity.id.empty() == false) cast_config->StopCasting(activity.id); } } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} CWE ID: CWE-79
void StopCastCallback(
171,626
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%04x, ", EXTRACT_16BITS(ptr))); ptr++; /* Disconnect Code */ ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(ptr))); ptr++; /* Control Protocol Number */ ND_PRINT((ndo, "%s", tok2str(l2tp_cc_direction2str, "Direction-#%u", *((const u_char *)ptr++)))); if (length > 5) { ND_PRINT((ndo, " ")); print_string(ndo, (const u_char *)ptr, length-5); } } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; if (length < 5) { ND_PRINT((ndo, "AVP too short")); return; } /* Disconnect Code */ ND_PRINT((ndo, "%04x, ", EXTRACT_16BITS(dat))); dat += 2; length -= 2; /* Control Protocol Number */ ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(dat))); dat += 2; length -= 2; /* Direction */ ND_PRINT((ndo, "%s", tok2str(l2tp_cc_direction2str, "Direction-#%u", EXTRACT_8BITS(ptr)))); ptr++; length--; if (length != 0) { ND_PRINT((ndo, " ")); print_string(ndo, (const u_char *)ptr, length); } }
167,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IndexedDBCursor::~IndexedDBCursor() { Close(); } Commit Message: [IndexedDB] Fix Cursor UAF If the connection is closed before we return a cursor, it dies in IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on the correct thread, but we also need to makes sure to remove it from its transaction. To make things simpler, we have the cursor remove itself from its transaction on destruction. R: pwnall@chromium.org Bug: 728887 Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2 Reviewed-on: https://chromium-review.googlesource.com/526284 Commit-Queue: Daniel Murphy <dmurph@chromium.org> Reviewed-by: Victor Costan <pwnall@chromium.org> Cr-Commit-Position: refs/heads/master@{#477504} CWE ID: CWE-416
IndexedDBCursor::~IndexedDBCursor() { if (transaction_) transaction_->UnregisterOpenCursor(this); Close(); }
172,308
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main() { gdImagePtr im; char *buffer; size_t size; size = read_test_file(&buffer, "heap_overflow.tga"); im = gdImageCreateFromTgaPtr(size, (void *) buffer); gdTestAssert(im == NULL); free(buffer); return gdNumFailures(); } Commit Message: Fix OOB reads of the TGA decompression buffer It is possible to craft TGA files which will overflow the decompression buffer, but not the image's bitmap. Therefore we also have to check for potential decompression buffer overflows. This issue had been reported by Ibrahim El-Sayed to security@libgd.org; a modified case exposing an off-by-one error of the first patch had been provided by Konrad Beckmann. This commit is an amendment to commit fb0e0cce, so we use CVE-2016-6906 as well. CWE ID: CWE-125
int main() { check_file("heap_overflow_1.tga"); check_file("heap_overflow_2.tga"); return gdNumFailures(); } static void check_file(char *basename) { gdImagePtr im; char *buffer; size_t size; size = read_test_file(&buffer, basename); im = gdImageCreateFromTgaPtr(size, (void *) buffer); gdTestAssert(im == NULL); free(buffer); }
170,121
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StreamingProcessor::releaseRecordingFrame(const sp<IMemory>& mem) { ATRACE_CALL(); status_t res; Mutex::Autolock m(mMutex); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); if (heap->getHeapID() != mRecordingHeap->mHeap->getHeapID()) { ALOGW("%s: Camera %d: Mismatched heap ID, ignoring release " "(got %x, expected %x)", __FUNCTION__, mId, heap->getHeapID(), mRecordingHeap->mHeap->getHeapID()); return; } VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); if (payload->eType != kMetadataBufferTypeANWBuffer) { ALOGE("%s: Camera %d: Recording frame type invalid (got %x, expected %x)", __FUNCTION__, mId, payload->eType, kMetadataBufferTypeANWBuffer); return; } size_t itemIndex; for (itemIndex = 0; itemIndex < mRecordingBuffers.size(); itemIndex++) { const BufferItem item = mRecordingBuffers[itemIndex]; if (item.mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT && item.mGraphicBuffer->getNativeBuffer() == payload->pBuffer) { break; } } if (itemIndex == mRecordingBuffers.size()) { ALOGE("%s: Camera %d: Can't find returned ANW Buffer %p in list of " "outstanding buffers", __FUNCTION__, mId, payload->pBuffer); return; } ALOGVV("%s: Camera %d: Freeing returned ANW buffer %p index %d", __FUNCTION__, mId, payload->pBuffer, itemIndex); res = mRecordingConsumer->releaseBuffer(mRecordingBuffers[itemIndex]); if (res != OK) { ALOGE("%s: Camera %d: Unable to free recording frame " "(Returned ANW buffer: %p): %s (%d)", __FUNCTION__, mId, payload->pBuffer, strerror(-res), res); return; } mRecordingBuffers.replaceAt(itemIndex); mRecordingHeapFree++; ALOGV_IF(mRecordingHeapFree == mRecordingHeapCount, "%s: Camera %d: All %d recording buffers returned", __FUNCTION__, mId, mRecordingHeapCount); } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200
void StreamingProcessor::releaseRecordingFrame(const sp<IMemory>& mem) { ATRACE_CALL(); status_t res; Mutex::Autolock m(mMutex); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); if (heap->getHeapID() != mRecordingHeap->mHeap->getHeapID()) { ALOGW("%s: Camera %d: Mismatched heap ID, ignoring release " "(got %x, expected %x)", __FUNCTION__, mId, heap->getHeapID(), mRecordingHeap->mHeap->getHeapID()); return; } VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); if (payload->eType != kMetadataBufferTypeANWBuffer) { ALOGE("%s: Camera %d: Recording frame type invalid (got %x, expected %x)", __FUNCTION__, mId, payload->eType, kMetadataBufferTypeANWBuffer); return; } // b/28466701 payload->pBuffer = (ANativeWindowBuffer*)(((uint8_t*)payload->pBuffer) + ICameraRecordingProxy::getCommonBaseAddress()); size_t itemIndex; for (itemIndex = 0; itemIndex < mRecordingBuffers.size(); itemIndex++) { const BufferItem item = mRecordingBuffers[itemIndex]; if (item.mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT && item.mGraphicBuffer->getNativeBuffer() == payload->pBuffer) { break; } } if (itemIndex == mRecordingBuffers.size()) { ALOGE("%s: Camera %d: Can't find returned ANW Buffer %p in list of " "outstanding buffers", __FUNCTION__, mId, payload->pBuffer); return; } ALOGVV("%s: Camera %d: Freeing returned ANW buffer %p index %d", __FUNCTION__, mId, payload->pBuffer, itemIndex); res = mRecordingConsumer->releaseBuffer(mRecordingBuffers[itemIndex]); if (res != OK) { ALOGE("%s: Camera %d: Unable to free recording frame " "(Returned ANW buffer: %p): %s (%d)", __FUNCTION__, mId, payload->pBuffer, strerror(-res), res); return; } mRecordingBuffers.replaceAt(itemIndex); mRecordingHeapFree++; ALOGV_IF(mRecordingHeapFree == mRecordingHeapCount, "%s: Camera %d: All %d recording buffers returned", __FUNCTION__, mId, mRecordingHeapCount); }
173,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.zshrc", &s) == 0) { if (copy_file("/etc/skel/.zshrc", fname, u, g, 0644) == 0) { fs_logger("clone /etc/skel/.zshrc"); } } else { // FILE *fp = fopen(fname, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR); fclose(fp); fs_logger2("touch", fname); } } free(fname); } else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.cshrc", &s) == 0) { if (copy_file("/etc/skel/.cshrc", fname, u, g, 0644) == 0) { fs_logger("clone /etc/skel/.cshrc"); } } else { // /* coverity[toctou] */ FILE *fp = fopen(fname, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR); fclose(fp); fs_logger2("touch", fname); } } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.bashrc", &s) == 0) { if (copy_file("/etc/skel/.bashrc", fname, u, g, 0644) == 0) { fs_logger("clone /etc/skel/.bashrc"); } } free(fname); } } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.zshrc", &s) == 0) { copy_file("/etc/skel/.zshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.zshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.cshrc", &s) == 0) { copy_file("/etc/skel/.cshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.cshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.bashrc", &s) == 0) { copy_file("/etc/skel/.bashrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.bashrc"); } free(fname); } }
170,093
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, struct rpcrdma_msg *rmsgp) { __be32 *p = (__be32 *)rmsgp; if (!xprt->xpt_bc_xprt) return false; if (rmsgp->rm_type != rdma_msg) return false; if (rmsgp->rm_body.rm_chunks[0] != xdr_zero) return false; if (rmsgp->rm_body.rm_chunks[1] != xdr_zero) return false; if (rmsgp->rm_body.rm_chunks[2] != xdr_zero) return false; /* sanity */ if (p[7] != rmsgp->rm_xid) return false; /* call direction */ if (p[8] == cpu_to_be32(RPC_CALL)) return false; return true; } 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
svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, struct rpcrdma_msg *rmsgp) static bool svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, __be32 *rdma_resp) { __be32 *p; if (!xprt->xpt_bc_xprt) return false; p = rdma_resp + 3; if (*p++ != rdma_msg) return false; if (*p++ != xdr_zero) return false; if (*p++ != xdr_zero) return false; if (*p++ != xdr_zero) return false; /* XID sanity */ if (*p++ != *rdma_resp) return false; /* call direction */ if (*p == cpu_to_be32(RPC_CALL)) return false; return true; }
168,164
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HistoryController::UpdateForCommit(RenderFrameImpl* frame, const WebHistoryItem& item, WebHistoryCommitType commit_type, bool navigation_within_page) { switch (commit_type) { case blink::WebBackForwardCommit: if (!provisional_entry_) return; current_entry_.reset(provisional_entry_.release()); if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { node->set_item(item); } break; case blink::WebStandardCommit: CreateNewBackForwardItem(frame, item, navigation_within_page); break; case blink::WebInitialCommitInChildFrame: UpdateForInitialLoadInChildFrame(frame, item); break; case blink::WebHistoryInertCommit: if (current_entry_) { if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { if (!navigation_within_page) node->RemoveChildren(); node->set_item(item); } } break; default: NOTREACHED() << "Invalid commit type: " << commit_type; } } Commit Message: Fix HistoryEntry corruption when commit isn't for provisional entry. BUG=597322 TEST=See bug for repro steps. Review URL: https://codereview.chromium.org/1848103004 Cr-Commit-Position: refs/heads/master@{#384659} CWE ID: CWE-254
void HistoryController::UpdateForCommit(RenderFrameImpl* frame, const WebHistoryItem& item, WebHistoryCommitType commit_type, bool navigation_within_page) { switch (commit_type) { case blink::WebBackForwardCommit: if (!provisional_entry_) return; // Commit the provisional entry, but only if this back/forward item // matches it. Otherwise it could be a commit from an earlier attempt to // go back/forward, and we should leave the provisional entry in place. if (HistoryEntry::HistoryNode* node = provisional_entry_->GetHistoryNodeForFrame(frame)) { if (node->item().itemSequenceNumber() == item.itemSequenceNumber()) current_entry_.reset(provisional_entry_.release()); } if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { node->set_item(item); } break; case blink::WebStandardCommit: CreateNewBackForwardItem(frame, item, navigation_within_page); break; case blink::WebInitialCommitInChildFrame: UpdateForInitialLoadInChildFrame(frame, item); break; case blink::WebHistoryInertCommit: if (current_entry_) { if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { if (!navigation_within_page) node->RemoveChildren(); node->set_item(item); } } break; default: NOTREACHED() << "Invalid commit type: " << commit_type; } }
172,565
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat) { int code = gs_distance_transform_inverse(dx, dy, pmat, pdist); double rounded; if (code == gs_error_undefinedresult) { /* The CTM is degenerate. Can't know the distance in user space. } else if (code < 0) return code; /* If the distance is very close to integers, round it. */ if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005) pdist->x = rounded; if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005) pdist->y = rounded; return 0; } Commit Message: CWE ID: CWE-119
set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat) { int code; double rounded; if (dx > 1e38 || dy > 1e38) code = gs_error_undefinedresult; else code = gs_distance_transform_inverse(dx, dy, pmat, pdist); if (code == gs_error_undefinedresult) { /* The CTM is degenerate. Can't know the distance in user space. } else if (code < 0) return code; /* If the distance is very close to integers, round it. */ if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005) pdist->x = rounded; if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005) pdist->y = rounded; return 0; }
164,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } Commit Message: [MJ2] Avoid index out of bounds access to pi->include[] Signed-off-by: Young_X <YangX92@hotmail.com> CWE ID: CWE-20
static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; /* Avoids index out of bounds access with include*/ if (index >= pi->include_size) { opj_pi_emit_error(pi, "Invalid access to pi->include"); return OPJ_FALSE; } if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; }
169,769
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BlobURLRequestJob::CountSize() { error_ = false; pending_get_file_info_count_ = 0; total_size_ = 0; item_length_list_.resize(blob_data_->items().size()); for (size_t i = 0; i < blob_data_->items().size(); ++i) { const BlobData::Item& item = blob_data_->items().at(i); if (IsFileType(item.type())) { ++pending_get_file_info_count_; GetFileStreamReader(i)->GetLength( base::Bind(&BlobURLRequestJob::DidGetFileItemLength, weak_factory_.GetWeakPtr(), i)); continue; } int64 item_length = static_cast<int64>(item.length()); item_length_list_[i] = item_length; total_size_ += item_length; } if (pending_get_file_info_count_ == 0) DidCountSize(net::OK); } Commit Message: Avoid integer overflows in BlobURLRequestJob. BUG=169685 Review URL: https://chromiumcodereview.appspot.com/12047012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void BlobURLRequestJob::CountSize() { error_ = false; pending_get_file_info_count_ = 0; total_size_ = 0; item_length_list_.resize(blob_data_->items().size()); for (size_t i = 0; i < blob_data_->items().size(); ++i) { const BlobData::Item& item = blob_data_->items().at(i); if (IsFileType(item.type())) { ++pending_get_file_info_count_; GetFileStreamReader(i)->GetLength( base::Bind(&BlobURLRequestJob::DidGetFileItemLength, weak_factory_.GetWeakPtr(), i)); continue; } if (!AddItemLength(i, item.length())) return; } if (pending_get_file_info_count_ == 0) DidCountSize(net::OK); }
171,398
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CoordinatorImpl::FinalizeGlobalMemoryDumpIfAllManagersReplied() { TRACE_EVENT0(base::trace_event::MemoryDumpManager::kTraceCategory, "GlobalMemoryDump.Computation"); DCHECK(!queued_memory_dump_requests_.empty()); QueuedRequest* request = &queued_memory_dump_requests_.front(); if (!request->dump_in_progress || request->pending_responses.size() > 0 || request->heap_dump_in_progress) { return; } QueuedRequestDispatcher::Finalize(request, tracing_observer_.get()); queued_memory_dump_requests_.pop_front(); request = nullptr; if (!queued_memory_dump_requests_.empty()) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::PerformNextQueuedGlobalMemoryDump, base::Unretained(this))); } } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <hjd@chromium.org> Commit-Queue: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
void CoordinatorImpl::FinalizeGlobalMemoryDumpIfAllManagersReplied() { TRACE_EVENT0(base::trace_event::MemoryDumpManager::kTraceCategory, "GlobalMemoryDump.Computation"); DCHECK(!queued_memory_dump_requests_.empty()); QueuedRequest* request = &queued_memory_dump_requests_.front(); if (!request->dump_in_progress || request->pending_responses.size() > 0 || request->heap_dump_in_progress) { return; } QueuedRequestDispatcher::Finalize(request, tracing_observer_.get()); queued_memory_dump_requests_.pop_front(); request = nullptr; if (!queued_memory_dump_requests_.empty()) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::PerformNextQueuedGlobalMemoryDump, weak_ptr_factory_.GetWeakPtr())); } }
173,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int extract_status_code(char *buffer, size_t size) { char *buf_code; char *begin; char *end = buffer + size; size_t inc = 0; int code; /* Allocate the room */ buf_code = (char *)MALLOC(10); /* Status-Code extraction */ while (buffer < end && *buffer++ != ' ') ; begin = buffer; while (buffer < end && *buffer++ != ' ') inc++; strncat(buf_code, begin, inc); code = atoi(buf_code); FREE(buf_code); return code; } Commit Message: Fix buffer overflow in extract_status_code() Issue #960 identified that the buffer allocated for copying the HTTP status code could overflow if the http response was corrupted. This commit changes the way the status code is read, avoids copying data, and also ensures that the status code is three digits long, is non-negative and occurs on the first line of the response. Signed-off-by: Quentin Armitage <quentin@armitage.org.uk> CWE ID: CWE-119
int extract_status_code(char *buffer, size_t size) { char *end = buffer + size; unsigned long code; /* Status-Code extraction */ while (buffer < end && *buffer != ' ' && *buffer != '\r') buffer++; buffer++; if (buffer + 3 >= end || *buffer == ' ' || buffer[3] != ' ') return 0; code = strtoul(buffer, &end, 10); if (buffer + 3 != end) return 0; return code; }
168,978
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update) { EAS_U32 endPhaseAccum; EAS_U32 endPhaseFrac; EAS_I32 numSamples; EAS_BOOL done = EAS_FALSE; /* check to see if we hit the end of the waveform this time */ /*lint -e{703} use shift for performance */ endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS); endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac); if (endPhaseAccum >= pWTVoice->loopEnd) { /* calculate how far current ptr is from end */ numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum); /* now account for the fractional portion */ /*lint -e{703} use shift for performance */ numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac); if (pWTIntFrame->frame.phaseIncrement) { pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement); } else { pWTIntFrame->numSamples = numSamples; } if (pWTIntFrame->numSamples < 0) { ALOGE("b/26366256"); pWTIntFrame->numSamples = 0; } /* sound will be done this frame */ done = EAS_TRUE; } /* update data for off-chip synth */ if (update) { pWTVoice->phaseFrac = endPhaseFrac; pWTVoice->phaseAccum = endPhaseAccum; } return done; } Commit Message: Sonivox: add SafetyNet log. Bug: 26366256 Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0 CWE ID: CWE-119
EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update) { EAS_U32 endPhaseAccum; EAS_U32 endPhaseFrac; EAS_I32 numSamples; EAS_BOOL done = EAS_FALSE; /* check to see if we hit the end of the waveform this time */ /*lint -e{703} use shift for performance */ endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS); endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac); if (endPhaseAccum >= pWTVoice->loopEnd) { /* calculate how far current ptr is from end */ numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum); /* now account for the fractional portion */ /*lint -e{703} use shift for performance */ numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac); if (pWTIntFrame->frame.phaseIncrement) { pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement); } else { pWTIntFrame->numSamples = numSamples; } if (pWTIntFrame->numSamples < 0) { ALOGE("b/26366256"); android_errorWriteLog(0x534e4554, "26366256"); pWTIntFrame->numSamples = 0; } /* sound will be done this frame */ done = EAS_TRUE; } /* update data for off-chip synth */ if (update) { pWTVoice->phaseFrac = endPhaseFrac; pWTVoice->phaseAccum = endPhaseAccum; } return done; }
174,607
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; } Commit Message: common: [security fix] Make sure sockets only listen locally CWE ID: CWE-284
int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; }
167,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Session* SessionManager::GetSession(const std::string& id) const { std::map<std::string, Session*>::const_iterator it; base::AutoLock lock(map_lock_); it = map_.find(id); if (it == map_.end()) { VLOG(1) << "No such session with ID " << id; return NULL; } return it->second; } 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
Session* SessionManager::GetSession(const std::string& id) const { std::map<std::string, Session*>::const_iterator it; base::AutoLock lock(map_lock_); it = map_.find(id); if (it == map_.end()) return NULL; return it->second; }
170,463
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NaClProcessHost::ReplyToRenderer( const IPC::ChannelHandle& channel_handle) { std::vector<nacl::FileDescriptor> handles_for_renderer; for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) { #if defined(OS_WIN) HANDLE handle_in_renderer; if (!DuplicateHandle(base::GetCurrentProcessHandle(), reinterpret_cast<HANDLE>( internal_->sockets_for_renderer[i]), chrome_render_message_filter_->peer_handle(), &handle_in_renderer, 0, // Unused given DUPLICATE_SAME_ACCESS. FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) { DLOG(ERROR) << "DuplicateHandle() failed"; return false; } handles_for_renderer.push_back( reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer)); #else nacl::FileDescriptor imc_handle; imc_handle.fd = internal_->sockets_for_renderer[i]; imc_handle.auto_close = true; handles_for_renderer.push_back(imc_handle); #endif } #if defined(OS_WIN) if (RunningOnWOW64()) { if (!content::BrokerAddTargetPeer(process_->GetData().handle)) { DLOG(ERROR) << "Failed to add NaCl process PID"; return false; } } #endif ChromeViewHostMsg_LaunchNaCl::WriteReplyParams( reply_msg_, handles_for_renderer, channel_handle); chrome_render_message_filter_->Send(reply_msg_); chrome_render_message_filter_ = NULL; reply_msg_ = NULL; internal_->sockets_for_renderer.clear(); return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool NaClProcessHost::ReplyToRenderer( bool NaClProcessHost::ReplyToRenderer() { std::vector<nacl::FileDescriptor> handles_for_renderer; for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) { #if defined(OS_WIN) HANDLE handle_in_renderer; if (!DuplicateHandle(base::GetCurrentProcessHandle(), reinterpret_cast<HANDLE>( internal_->sockets_for_renderer[i]), chrome_render_message_filter_->peer_handle(), &handle_in_renderer, 0, // Unused given DUPLICATE_SAME_ACCESS. FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) { DLOG(ERROR) << "DuplicateHandle() failed"; return false; } handles_for_renderer.push_back( reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer)); #else nacl::FileDescriptor imc_handle; imc_handle.fd = internal_->sockets_for_renderer[i]; imc_handle.auto_close = true; handles_for_renderer.push_back(imc_handle); #endif } #if defined(OS_WIN) if (RunningOnWOW64()) { if (!content::BrokerAddTargetPeer(process_->GetData().handle)) { DLOG(ERROR) << "Failed to add NaCl process PID"; return false; } } #endif ChromeViewHostMsg_LaunchNaCl::WriteReplyParams( reply_msg_, handles_for_renderer); chrome_render_message_filter_->Send(reply_msg_); chrome_render_message_filter_ = NULL; reply_msg_ = NULL; internal_->sockets_for_renderer.clear(); return true; }
170,727
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); }
167,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void IBusBusNameOwnerChangedCallback( IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name, gpointer user_data) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); DLOG(INFO) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; return; } LOG(INFO) << "IBus config daemon is started. Recovering ibus_config_"; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } 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
static void IBusBusNameOwnerChangedCallback( void IBusBusNameOwnerChanged(IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); VLOG(1) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; // |OnConnectionChange| with false here to allow Chrome to return; } VLOG(1) << "IBus config daemon is started. Recovering ibus_config_"; // successfully created, |OnConnectionChange| will be called to MaybeRestoreConnections(); }
170,539
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppControllerImpl::BindRequest(mojom::AppControllerRequest request) { bindings_.AddBinding(this, std::move(request)); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <michaelpg@chromium.org> Commit-Queue: Lucas Tenório <ltenorio@chromium.org> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
void AppControllerImpl::BindRequest(mojom::AppControllerRequest request) { void AppControllerService::BindRequest(mojom::AppControllerRequest request) { bindings_.AddBinding(this, std::move(request)); }
172,080
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int add_ballooned_pages(int nr_pages) { enum bp_state st; if (xen_hotplug_unpopulated) { st = reserve_additional_memory(); if (st != BP_ECANCELED) { mutex_unlock(&balloon_mutex); wait_event(balloon_wq, !list_empty(&ballooned_pages)); mutex_lock(&balloon_mutex); return 0; } } st = decrease_reservation(nr_pages, GFP_USER); if (st != BP_DONE) return -ENOMEM; return 0; } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <jgross@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-400
static int add_ballooned_pages(int nr_pages) { enum bp_state st; if (xen_hotplug_unpopulated) { st = reserve_additional_memory(); if (st != BP_ECANCELED) { mutex_unlock(&balloon_mutex); wait_event(balloon_wq, !list_empty(&ballooned_pages)); mutex_lock(&balloon_mutex); return 0; } } if (si_mem_available() < nr_pages) return -ENOMEM; st = decrease_reservation(nr_pages, GFP_USER); if (st != BP_DONE) return -ENOMEM; return 0; }
169,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, "w"); if (!fp) { if (name) flog(LOG_ERR, "failed to set %s (%u) for %s: %s", name, val, iface, strerror(errno)); return -1; } fprintf(fp, "%u", val); fclose(fp); return 0; } Commit Message: set_interface_var() doesn't check interface name and blindly does fopen(path "/" ifname, "w") on it. As "ifname" is an untrusted input, it should be checked for ".." and/or "/" in it. Otherwise, an infected unprivileged daemon may overwrite contents of file named "mtu", "hoplimit", etc. in arbitrary location with arbitrary 32-bit value in decimal representation ("%d"). If an attacker has a local account or may create arbitrary symlinks with these names in any location (e.g. /tmp), any file may be overwritten with a decimal value. CWE ID: CWE-22
set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; /* No path traversal */ if (strstr(name, "..") || strchr(name, '/')) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, "w"); if (!fp) { if (name) flog(LOG_ERR, "failed to set %s (%u) for %s: %s", name, val, iface, strerror(errno)); return -1; } fprintf(fp, "%u", val); fclose(fp); return 0; }
166,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK); len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE) { return -1; } qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as); if (off + len > 4096) { /* transfer crosses page border */ uint32_t len2 = off + len - 4096; uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); /* Fall through */ case USB_RET_IOERROR: case USB_RET_NODEV: /* 3.3.2: XACTERR is only allowed on IN transactions */ if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: /* no data for us, so do a zero-length transfer */ ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* OUT */ } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* IN */ } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; } } return 0; } Commit Message: CWE ID: CWE-20
static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp, xfers = 0; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK); len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE) { return -1; } qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as); if (off + len > 4096) { /* transfer crosses page border */ uint32_t len2 = off + len - 4096; uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); /* Fall through */ case USB_RET_IOERROR: case USB_RET_NODEV: /* 3.3.2: XACTERR is only allowed on IN transactions */ if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: /* no data for us, so do a zero-length transfer */ ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* OUT */ } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* IN */ } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; xfers++; } } return xfers ? 0 : -1; }
165,279
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void close_connection(h2o_http2_conn_t *conn) { conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING; if (conn->_write.buf_in_flight != NULL || h2o_timeout_is_linked(&conn->_write.timeout_entry)) { /* there is a pending write, let on_write_complete actually close the connection */ } else { close_connection_now(conn); } } Commit Message: h2: use after free on premature connection close #920 lib/http2/connection.c:on_read() calls parse_input(), which might free `conn`. It does so in particular if the connection preface isn't the expected one in expect_preface(). `conn` is then used after the free in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`. We fix this by adding a return value to close_connection that returns a negative value if `conn` has been free'd and can't be used anymore. Credits for finding the bug to Tim Newsham. CWE ID:
void close_connection(h2o_http2_conn_t *conn) int close_connection(h2o_http2_conn_t *conn) { conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING; if (conn->_write.buf_in_flight != NULL || h2o_timeout_is_linked(&conn->_write.timeout_entry)) { /* there is a pending write, let on_write_complete actually close the connection */ } else { close_connection_now(conn); return -1; } return 0; }
167,225
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(DirectoryIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.dirp) { RETURN_LONG(intern->u.dir.index); } else { RETURN_FALSE; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.dirp) { RETURN_LONG(intern->u.dir.index); } else { RETURN_FALSE; } }
167,028
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::open() { ASSERT(!importLoader()); if (m_frame) { if (ScriptableDocumentParser* parser = scriptableDocumentParser()) { if (parser->isParsing()) { if (parser->isExecutingScript()) return; if (!parser->wasCreatedByScript() && parser->hasInsertionPoint()) return; } } if (m_frame->loader().provisionalDocumentLoader()) m_frame->loader().stopAllLoaders(); } removeAllEventListenersRecursively(); implicitOpen(ForceSynchronousParsing); if (ScriptableDocumentParser* parser = scriptableDocumentParser()) parser->setWasCreatedByScript(true); if (m_frame) m_frame->loader().didExplicitOpen(); if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress) m_loadEventProgress = LoadEventNotRun; } Commit Message: Don't change Document load progress in any page dismissal events. This can confuse the logic for blocking modal dialogs. BUG=536652 Review URL: https://codereview.chromium.org/1373113002 Cr-Commit-Position: refs/heads/master@{#351419} CWE ID: CWE-20
void Document::open() { ASSERT(!importLoader()); if (m_frame) { if (ScriptableDocumentParser* parser = scriptableDocumentParser()) { if (parser->isParsing()) { if (parser->isExecutingScript()) return; if (!parser->wasCreatedByScript() && parser->hasInsertionPoint()) return; } } if (m_frame->loader().provisionalDocumentLoader()) m_frame->loader().stopAllLoaders(); } removeAllEventListenersRecursively(); implicitOpen(ForceSynchronousParsing); if (ScriptableDocumentParser* parser = scriptableDocumentParser()) parser->setWasCreatedByScript(true); if (m_frame) m_frame->loader().didExplicitOpen(); if (m_loadEventProgress != LoadEventInProgress && pageDismissalEventBeingDispatched() == NoDismissal) m_loadEventProgress = LoadEventNotRun; }
171,783
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Splash::scaleMaskYdXu(SplashImageMaskSource src, void *srcData, int srcWidth, int srcHeight, int scaledWidth, int scaledHeight, SplashBitmap *dest) { Guchar *lineBuf; Guint *pixBuf; Guint pix; Guchar *destPtr; int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, d; int i, j; yp = srcHeight / scaledHeight; lineBuf = (Guchar *)gmalloc(srcWidth); pixBuf = (Guint *)gmallocn(srcWidth, sizeof(int)); yt = 0; destPtr = dest->data; for (y = 0; y < scaledHeight; ++y) { yt = 0; destPtr = dest->data; for (y = 0; y < scaledHeight; ++y) { } memset(pixBuf, 0, srcWidth * sizeof(int)); for (i = 0; i < yStep; ++i) { (*src)(srcData, lineBuf); for (j = 0; j < srcWidth; ++j) { pixBuf[j] += lineBuf[j]; } } xt = 0; d = (255 << 23) / yStep; for (x = 0; x < srcWidth; ++x) { if ((xt += xq) >= srcWidth) { xt -= srcWidth; xStep = xp + 1; } else { xStep = xp; } pix = pixBuf[x]; pix = (pix * d) >> 23; for (i = 0; i < xStep; ++i) { *destPtr++ = (Guchar)pix; } } } gfree(pixBuf); gfree(lineBuf); } Commit Message: CWE ID: CWE-119
void Splash::scaleMaskYdXu(SplashImageMaskSource src, void *srcData, int srcWidth, int srcHeight, int scaledWidth, int scaledHeight, SplashBitmap *dest) { Guchar *lineBuf; Guint *pixBuf; Guint pix; Guchar *destPtr; int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, d; int i, j; destPtr = dest->data; if (destPtr == NULL) { error(errInternal, -1, "dest->data is NULL in Splash::scaleMaskYdXu"); return; } yp = srcHeight / scaledHeight; lineBuf = (Guchar *)gmalloc(srcWidth); pixBuf = (Guint *)gmallocn(srcWidth, sizeof(int)); yt = 0; destPtr = dest->data; for (y = 0; y < scaledHeight; ++y) { yt = 0; for (y = 0; y < scaledHeight; ++y) { } memset(pixBuf, 0, srcWidth * sizeof(int)); for (i = 0; i < yStep; ++i) { (*src)(srcData, lineBuf); for (j = 0; j < srcWidth; ++j) { pixBuf[j] += lineBuf[j]; } } xt = 0; d = (255 << 23) / yStep; for (x = 0; x < srcWidth; ++x) { if ((xt += xq) >= srcWidth) { xt -= srcWidth; xStep = xp + 1; } else { xStep = xp; } pix = pixBuf[x]; pix = (pix * d) >> 23; for (i = 0; i < xStep; ++i) { *destPtr++ = (Guchar)pix; } } } gfree(pixBuf); gfree(lineBuf); }
164,737
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin, const GURL& embedding_origin) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); if (!CanRequestObjectPermission(requesting_origin, embedding_origin)) return {}; std::vector<std::unique_ptr<Object>> results; auto* info = new content_settings::SettingInfo(); std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin, info); std::unique_ptr<base::Value> objects; if (!setting->Remove(kObjectListKey, &objects)) return results; std::unique_ptr<base::ListValue> object_list = base::ListValue::From(std::move(objects)); if (!object_list) return results; for (auto& object : *object_list) { base::DictionaryValue* object_dict; if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) { results.push_back(std::make_unique<Object>( requesting_origin, embedding_origin, object_dict, info->source, host_content_settings_map_->is_incognito())); } } return results; } Commit Message: Fix memory leak in ChooserContextBase::GetGrantedObjects. Bug: 854329 Change-Id: Ia163d503a4207859cd41c847c9d5f67e77580fbc Reviewed-on: https://chromium-review.googlesource.com/c/1456080 Reviewed-by: Balazs Engedy <engedy@chromium.org> Reviewed-by: Raymes Khoury <raymes@chromium.org> Commit-Queue: Marek Haranczyk <mharanczyk@opera.com> Cr-Commit-Position: refs/heads/master@{#629919} CWE ID: CWE-190
ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin, const GURL& embedding_origin) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); if (!CanRequestObjectPermission(requesting_origin, embedding_origin)) return {}; std::vector<std::unique_ptr<Object>> results; content_settings::SettingInfo info; std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin, &info); std::unique_ptr<base::Value> objects; if (!setting->Remove(kObjectListKey, &objects)) return results; std::unique_ptr<base::ListValue> object_list = base::ListValue::From(std::move(objects)); if (!object_list) return results; for (auto& object : *object_list) { base::DictionaryValue* object_dict; if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) { results.push_back(std::make_unique<Object>( requesting_origin, embedding_origin, object_dict, info.source, host_content_settings_map_->is_incognito())); } } return results; }
172,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftGSM::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex > 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = 1; pcmParams->nSamplingRate = 8000; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftGSM::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex > 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = 1; pcmParams->nSamplingRate = 8000; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateNull( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_NULL; return item; } 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
cJSON *cJSON_CreateNull( void )
167,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void igmp_heard_query(struct in_device *in_dev, struct sk_buff *skb, int len) { struct igmphdr *ih = igmp_hdr(skb); struct igmpv3_query *ih3 = igmpv3_query_hdr(skb); struct ip_mc_list *im; __be32 group = ih->group; int max_delay; int mark = 0; if (len == 8) { if (ih->code == 0) { /* Alas, old v1 router presents here. */ max_delay = IGMP_Query_Response_Interval; in_dev->mr_v1_seen = jiffies + IGMP_V1_Router_Present_Timeout; group = 0; } else { /* v2 router present */ max_delay = ih->code*(HZ/IGMP_TIMER_SCALE); in_dev->mr_v2_seen = jiffies + IGMP_V2_Router_Present_Timeout; } /* cancel the interface change timer */ in_dev->mr_ifc_count = 0; if (del_timer(&in_dev->mr_ifc_timer)) __in_dev_put(in_dev); /* clear deleted report items */ igmpv3_clear_delrec(in_dev); } else if (len < 12) { return; /* ignore bogus packet; freed by caller */ } else if (IGMP_V1_SEEN(in_dev)) { /* This is a v3 query with v1 queriers present */ max_delay = IGMP_Query_Response_Interval; group = 0; } else if (IGMP_V2_SEEN(in_dev)) { /* this is a v3 query with v2 queriers present; * Interpretation of the max_delay code is problematic here. * A real v2 host would use ih_code directly, while v3 has a * different encoding. We use the v3 encoding as more likely * to be intended in a v3 query. */ max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE); } else { /* v3 */ if (!pskb_may_pull(skb, sizeof(struct igmpv3_query))) return; ih3 = igmpv3_query_hdr(skb); if (ih3->nsrcs) { if (!pskb_may_pull(skb, sizeof(struct igmpv3_query) + ntohs(ih3->nsrcs)*sizeof(__be32))) return; ih3 = igmpv3_query_hdr(skb); } max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE); if (!max_delay) max_delay = 1; /* can't mod w/ 0 */ in_dev->mr_maxdelay = max_delay; if (ih3->qrv) in_dev->mr_qrv = ih3->qrv; if (!group) { /* general query */ if (ih3->nsrcs) return; /* no sources allowed */ igmp_gq_start_timer(in_dev); return; } /* mark sources to include, if group & source-specific */ mark = ih3->nsrcs != 0; } /* * - Start the timers in all of our membership records * that the query applies to for the interface on * which the query arrived excl. those that belong * to a "local" group (224.0.0.X) * - For timers already running check if they need to * be reset. * - Use the igmp->igmp_code field as the maximum * delay possible */ rcu_read_lock(); for_each_pmc_rcu(in_dev, im) { int changed; if (group && group != im->multiaddr) continue; if (im->multiaddr == IGMP_ALL_HOSTS) continue; spin_lock_bh(&im->lock); if (im->tm_running) im->gsquery = im->gsquery && mark; else im->gsquery = mark; changed = !im->gsquery || igmp_marksources(im, ntohs(ih3->nsrcs), ih3->srcs); spin_unlock_bh(&im->lock); if (changed) igmp_mod_timer(im, max_delay); } rcu_read_unlock(); } Commit Message: igmp: Avoid zero delay when receiving odd mixture of IGMP queries Commit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP behavior on v3 query during v2-compatibility mode') added yet another case for query parsing, which can result in max_delay = 0. Substitute a value of 1, as in the usual v3 case. Reported-by: Simon McVittie <smcv@debian.org> References: http://bugs.debian.org/654876 Signed-off-by: Ben Hutchings <ben@decadent.org.uk> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static void igmp_heard_query(struct in_device *in_dev, struct sk_buff *skb, int len) { struct igmphdr *ih = igmp_hdr(skb); struct igmpv3_query *ih3 = igmpv3_query_hdr(skb); struct ip_mc_list *im; __be32 group = ih->group; int max_delay; int mark = 0; if (len == 8) { if (ih->code == 0) { /* Alas, old v1 router presents here. */ max_delay = IGMP_Query_Response_Interval; in_dev->mr_v1_seen = jiffies + IGMP_V1_Router_Present_Timeout; group = 0; } else { /* v2 router present */ max_delay = ih->code*(HZ/IGMP_TIMER_SCALE); in_dev->mr_v2_seen = jiffies + IGMP_V2_Router_Present_Timeout; } /* cancel the interface change timer */ in_dev->mr_ifc_count = 0; if (del_timer(&in_dev->mr_ifc_timer)) __in_dev_put(in_dev); /* clear deleted report items */ igmpv3_clear_delrec(in_dev); } else if (len < 12) { return; /* ignore bogus packet; freed by caller */ } else if (IGMP_V1_SEEN(in_dev)) { /* This is a v3 query with v1 queriers present */ max_delay = IGMP_Query_Response_Interval; group = 0; } else if (IGMP_V2_SEEN(in_dev)) { /* this is a v3 query with v2 queriers present; * Interpretation of the max_delay code is problematic here. * A real v2 host would use ih_code directly, while v3 has a * different encoding. We use the v3 encoding as more likely * to be intended in a v3 query. */ max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE); if (!max_delay) max_delay = 1; /* can't mod w/ 0 */ } else { /* v3 */ if (!pskb_may_pull(skb, sizeof(struct igmpv3_query))) return; ih3 = igmpv3_query_hdr(skb); if (ih3->nsrcs) { if (!pskb_may_pull(skb, sizeof(struct igmpv3_query) + ntohs(ih3->nsrcs)*sizeof(__be32))) return; ih3 = igmpv3_query_hdr(skb); } max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE); if (!max_delay) max_delay = 1; /* can't mod w/ 0 */ in_dev->mr_maxdelay = max_delay; if (ih3->qrv) in_dev->mr_qrv = ih3->qrv; if (!group) { /* general query */ if (ih3->nsrcs) return; /* no sources allowed */ igmp_gq_start_timer(in_dev); return; } /* mark sources to include, if group & source-specific */ mark = ih3->nsrcs != 0; } /* * - Start the timers in all of our membership records * that the query applies to for the interface on * which the query arrived excl. those that belong * to a "local" group (224.0.0.X) * - For timers already running check if they need to * be reset. * - Use the igmp->igmp_code field as the maximum * delay possible */ rcu_read_lock(); for_each_pmc_rcu(in_dev, im) { int changed; if (group && group != im->multiaddr) continue; if (im->multiaddr == IGMP_ALL_HOSTS) continue; spin_lock_bh(&im->lock); if (im->tm_running) im->gsquery = im->gsquery && mark; else im->gsquery = mark; changed = !im->gsquery || igmp_marksources(im, ntohs(ih3->nsrcs), ih3->srcs); spin_unlock_bh(&im->lock); if (changed) igmp_mod_timer(im, max_delay); } rcu_read_unlock(); }
165,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void bdt_enable(void) { bdt_log("ENABLE BT"); if (bt_enabled) { bdt_log("Bluetooth is already enabled"); return; } status = sBtInterface->enable(); check_return_status(status); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
void bdt_enable(void) { bdt_log("ENABLE BT"); if (bt_enabled) { bdt_log("Bluetooth is already enabled"); return; } status = sBtInterface->enable(false); check_return_status(status); }
173,555
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } }
167,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; xmlChar stop; int state = ctxt->instate; int count = 0; SHRINK; if (RAW == '"') { NEXT; stop = '"'; } else if (RAW == '\'') { NEXT; stop = '\''; } else { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } ctxt->instate = XML_PARSER_SYSTEM_LITERAL; cur = CUR_CHAR(l); while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */ if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); ctxt->instate = (xmlParserInputState) state; return(NULL); } buf = tmp; } count++; if (count > 50) { GROW; count = 0; } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { GROW; SHRINK; cur = CUR_CHAR(l); } } buf[len] = 0; ctxt->instate = (xmlParserInputState) state; if (!IS_CHAR(cur)) { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL); } else { NEXT; } return(buf); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; xmlChar stop; int state = ctxt->instate; int count = 0; SHRINK; if (RAW == '"') { NEXT; stop = '"'; } else if (RAW == '\'') { NEXT; stop = '\''; } else { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } ctxt->instate = XML_PARSER_SYSTEM_LITERAL; cur = CUR_CHAR(l); while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */ if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); ctxt->instate = (xmlParserInputState) state; return(NULL); } buf = tmp; } count++; if (count > 50) { GROW; count = 0; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { GROW; SHRINK; cur = CUR_CHAR(l); } } buf[len] = 0; ctxt->instate = (xmlParserInputState) state; if (!IS_CHAR(cur)) { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL); } else { NEXT; } return(buf); }
171,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; _TIFFmemset(buf, 0, stripsize); for (s = 0; s < ns; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; } Commit Message: * tools/tiffcp.c: avoid uint32 underflow in cpDecodedStrips that can cause various issues, such as buffer overflows in the library. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2598 CWE ID: CWE-191
DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; _TIFFmemset(buf, 0, stripsize); for (s = 0; s < ns && row < imagelength; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; }
168,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); }
174,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static scoped_refptr<Extension> MakeSyncTestExtension( SyncTestExtensionType type, const GURL& update_url, const GURL& launch_url, Manifest::Location location, int num_plugins, const base::FilePath& extension_path, int creation_flags) { base::DictionaryValue source; source.SetString(keys::kName, "PossiblySyncableExtension"); source.SetString(keys::kVersion, "0.0.0.0"); if (type == APP) source.SetString(keys::kApp, "true"); if (type == THEME) source.Set(keys::kTheme, new base::DictionaryValue()); if (!update_url.is_empty()) { source.SetString(keys::kUpdateURL, update_url.spec()); } if (!launch_url.is_empty()) { source.SetString(keys::kLaunchWebURL, launch_url.spec()); } if (type != THEME) { source.SetBoolean(keys::kConvertedFromUserScript, type == USER_SCRIPT); base::ListValue* plugins = new base::ListValue(); for (int i = 0; i < num_plugins; ++i) { base::DictionaryValue* plugin = new base::DictionaryValue(); plugin->SetString(keys::kPluginsPath, std::string()); plugins->Set(i, plugin); } source.Set(keys::kPlugins, plugins); } std::string error; scoped_refptr<Extension> extension = Extension::Create( extension_path, location, source, creation_flags, &error); EXPECT_TRUE(extension.get()); EXPECT_EQ("", error); return extension; } Commit Message: Fix syncing of NPAPI plugins. This fix adds a check for |plugin| permission while syncing NPAPI plugins. BUG=252034 Review URL: https://chromiumcodereview.appspot.com/16816024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207830 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
static scoped_refptr<Extension> MakeSyncTestExtension( static scoped_refptr<Extension> MakeSyncTestExtensionWithPluginPermission( SyncTestExtensionType type, const GURL& update_url, const GURL& launch_url, Manifest::Location location, int num_plugins, const base::FilePath& extension_path, int creation_flags, bool has_plugin_permission) { base::DictionaryValue source; source.SetString(keys::kName, "PossiblySyncableExtension"); source.SetString(keys::kVersion, "0.0.0.0"); if (type == APP) source.SetString(keys::kApp, "true"); if (type == THEME) source.Set(keys::kTheme, new base::DictionaryValue()); if (!update_url.is_empty()) { source.SetString(keys::kUpdateURL, update_url.spec()); } if (!launch_url.is_empty()) { source.SetString(keys::kLaunchWebURL, launch_url.spec()); } if (type != THEME) { source.SetBoolean(keys::kConvertedFromUserScript, type == USER_SCRIPT); base::ListValue* plugins = new base::ListValue(); for (int i = 0; i < num_plugins; ++i) { base::DictionaryValue* plugin = new base::DictionaryValue(); plugin->SetString(keys::kPluginsPath, std::string()); plugins->Set(i, plugin); } source.Set(keys::kPlugins, plugins); } if (has_plugin_permission) { ListValue* plugins = new ListValue(); plugins->Set(0, new StringValue("plugin")); source.Set(keys::kPermissions, plugins); } std::string error; scoped_refptr<Extension> extension = Extension::Create( extension_path, location, source, creation_flags, &error); EXPECT_TRUE(extension.get()); EXPECT_EQ("", error); return extension; }
171,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintWebViewHelper::OnPrintPreview(const DictionaryValue& settings) { DCHECK(is_preview_); print_preview_context_.OnPrintPreview(); if (!InitPrintSettings(print_preview_context_.frame(), print_preview_context_.node(), true)) { Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings( routing_id(), print_pages_params_->params.document_cookie)); return; } if (!UpdatePrintSettings(settings, true)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PREVIEW); return; } if (!print_pages_params_->params.is_first_request && old_print_pages_params_.get() && PrintMsg_Print_Params_IsEqual(*old_print_pages_params_, *print_pages_params_)) { PrintHostMsg_DidPreviewDocument_Params preview_params; preview_params.reuse_existing_data = true; preview_params.data_size = 0; preview_params.document_cookie = print_pages_params_->params.document_cookie; preview_params.expected_pages_count = print_preview_context_.total_page_count(); preview_params.modifiable = print_preview_context_.IsModifiable(); preview_params.preview_request_id = print_pages_params_->params.preview_request_id; Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params)); return; } old_print_pages_params_.reset(); is_print_ready_metafile_sent_ = false; print_pages_params_->params.supports_alpha_blend = true; bool generate_draft_pages = false; if (!settings.GetBoolean(printing::kSettingGenerateDraftData, &generate_draft_pages)) { NOTREACHED(); } print_preview_context_.set_generate_draft_pages(generate_draft_pages); if (CreatePreviewDocument()) { DidFinishPrinting(OK); } else { if (notify_browser_of_print_failure_) LOG(ERROR) << "CreatePreviewDocument failed"; DidFinishPrinting(FAIL_PREVIEW); } } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintWebViewHelper::OnPrintPreview(const DictionaryValue& settings) { DCHECK(is_preview_); print_preview_context_.OnPrintPreview(); if (!UpdatePrintSettings(settings, true)) { if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) { Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings( routing_id(), print_pages_params_->params.document_cookie)); notify_browser_of_print_failure_ = false; // Already sent. } DidFinishPrinting(FAIL_PREVIEW); return; } if (!print_pages_params_->params.is_first_request && old_print_pages_params_.get() && PrintMsg_Print_Params_IsEqual(*old_print_pages_params_, *print_pages_params_)) { PrintHostMsg_DidPreviewDocument_Params preview_params; preview_params.reuse_existing_data = true; preview_params.data_size = 0; preview_params.document_cookie = print_pages_params_->params.document_cookie; preview_params.expected_pages_count = print_preview_context_.total_page_count(); preview_params.modifiable = print_preview_context_.IsModifiable(); preview_params.preview_request_id = print_pages_params_->params.preview_request_id; Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params)); return; } old_print_pages_params_.reset(); is_print_ready_metafile_sent_ = false; print_pages_params_->params.supports_alpha_blend = true; bool generate_draft_pages = false; if (!settings.GetBoolean(printing::kSettingGenerateDraftData, &generate_draft_pages)) { NOTREACHED(); } print_preview_context_.set_generate_draft_pages(generate_draft_pages); if (CreatePreviewDocument()) { DidFinishPrinting(OK); } else { if (notify_browser_of_print_failure_) LOG(ERROR) << "CreatePreviewDocument failed"; DidFinishPrinting(FAIL_PREVIEW); } }
170,262
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } 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_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; }
168,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool FileUtilProxy::Read( scoped_refptr<MessageLoopProxy> message_loop_proxy, PlatformFile file, int64 offset, int bytes_to_read, ReadCallback* callback) { if (bytes_to_read < 0) return false; return Start(FROM_HERE, message_loop_proxy, new RelayRead(file, offset, bytes_to_read, callback)); } Commit Message: Fix a small leak in FileUtilProxy BUG=none TEST=green mem bots Review URL: http://codereview.chromium.org/7669046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool FileUtilProxy::Read( scoped_refptr<MessageLoopProxy> message_loop_proxy, PlatformFile file, int64 offset, int bytes_to_read, ReadCallback* callback) { if (bytes_to_read < 0) { delete callback; return false; } return Start(FROM_HERE, message_loop_proxy, new RelayRead(file, offset, bytes_to_read, callback)); }
170,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunRoundTripErrorCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); int max_error = 0; int total_error = 0; const int count_test_block = 100000; DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_temp_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_temp_block[j] > 0) { test_temp_block[j] += 2; test_temp_block[j] /= 4; test_temp_block[j] *= 4; } else { test_temp_block[j] -= 2; test_temp_block[j] /= 4; test_temp_block[j] *= 4; } } REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < 64; ++j) { const int diff = dst[j] - src[j]; const int error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1, max_error) << "Error: 8x8 FDCT/IDCT or FHT/IHT has an individual" << " roundtrip error > 1"; EXPECT_GE(count_test_block/5, total_error) << "Error: 8x8 FDCT/IDCT or FHT/IHT has average roundtrip " << "error > 1/5 per block"; } 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 RunRoundTripErrorCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); int max_error = 0; int total_error = 0; const int count_test_block = 100000; DECLARE_ALIGNED(16, int16_t, test_input_block[64]); DECLARE_ALIGNED(16, tran_low_t, test_temp_block[64]); DECLARE_ALIGNED(16, uint8_t, dst[64]); DECLARE_ALIGNED(16, uint8_t, src[64]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[64]); DECLARE_ALIGNED(16, uint16_t, src16[64]); #endif for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < 64; ++j) { if (bit_depth_ == VPX_BITS_8) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { src16[j] = rnd.Rand16() & mask_; dst16[j] = rnd.Rand16() & mask_; test_input_block[j] = src16[j] - dst16[j]; #endif } } ASM_REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_temp_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_temp_block[j] > 0) { test_temp_block[j] += 2; test_temp_block[j] /= 4; test_temp_block[j] *= 4; } else { test_temp_block[j] -= 2; test_temp_block[j] /= 4; test_temp_block[j] *= 4; } } if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, dst, pitch_)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_)); #endif } for (int j = 0; j < 64; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const int diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else const int diff = dst[j] - src[j]; #endif const int error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1 << 2 * (bit_depth_ - 8), max_error) << "Error: 8x8 FDCT/IDCT or FHT/IHT has an individual" << " roundtrip error > 1"; EXPECT_GE((count_test_block << 2 * (bit_depth_ - 8))/5, total_error) << "Error: 8x8 FDCT/IDCT or FHT/IHT has average roundtrip " << "error > 1/5 per block"; }
174,560
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_user_token (const char *authfile, const char *username, const char *otp_id, int verbose, FILE *debug_file) { char buf[1024]; char *s_user, *s_token; int retval = AUTH_ERROR; int fd; struct stat st; FILE *opwfile; fd = open(authfile, O_RDONLY, 0); if (fd < 0) { if(verbose) D (debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno)); return retval; } if (fstat(fd, &st) < 0) { if(verbose) D (debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno)); close(fd); return retval; } if (!S_ISREG(st.st_mode)) { if(verbose) D (debug_file, "%s is not a regular file", authfile); close(fd); return retval; } opwfile = fdopen(fd, "r"); if (opwfile == NULL) { if(verbose) D (debug_file, "fdopen: %s", strerror(errno)); close(fd); return retval; } retval = AUTH_NO_TOKENS; while (fgets (buf, 1024, opwfile)) { char *saveptr = NULL; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (buf[0] == '#') { /* This is a comment and we may skip it. */ if(verbose) D (debug_file, "Skipping comment line: %s", buf); continue; } if(verbose) D (debug_file, "Authorization line: %s", buf); s_user = strtok_r (buf, ":", &saveptr); if (s_user && strcmp (username, s_user) == 0) { if(verbose) D (debug_file, "Matched user: %s", s_user); retval = AUTH_NOT_FOUND; /* We found at least one line for the user */ do { s_token = strtok_r (NULL, ":", &saveptr); if(verbose) D (debug_file, "Authorization token: %s", s_token); if (s_token && otp_id && strcmp (otp_id, s_token) == 0) { if(verbose) D (debug_file, "Match user/token as %s/%s", username, otp_id); return AUTH_FOUND; } } while (s_token != NULL); } } fclose (opwfile); return retval; } Commit Message: util: make sure to close the authfile before returning success fixes #136 CWE ID: CWE-200
check_user_token (const char *authfile, const char *username, const char *otp_id, int verbose, FILE *debug_file) { char buf[1024]; char *s_user, *s_token; int retval = AUTH_ERROR; int fd; struct stat st; FILE *opwfile; fd = open(authfile, O_RDONLY, 0); if (fd < 0) { if(verbose) D (debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno)); return retval; } if (fstat(fd, &st) < 0) { if(verbose) D (debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno)); close(fd); return retval; } if (!S_ISREG(st.st_mode)) { if(verbose) D (debug_file, "%s is not a regular file", authfile); close(fd); return retval; } opwfile = fdopen(fd, "r"); if (opwfile == NULL) { if(verbose) D (debug_file, "fdopen: %s", strerror(errno)); close(fd); return retval; } retval = AUTH_NO_TOKENS; while (fgets (buf, 1024, opwfile)) { char *saveptr = NULL; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (buf[0] == '#') { /* This is a comment and we may skip it. */ if(verbose) D (debug_file, "Skipping comment line: %s", buf); continue; } if(verbose) D (debug_file, "Authorization line: %s", buf); s_user = strtok_r (buf, ":", &saveptr); if (s_user && strcmp (username, s_user) == 0) { if(verbose) D (debug_file, "Matched user: %s", s_user); retval = AUTH_NOT_FOUND; /* We found at least one line for the user */ do { s_token = strtok_r (NULL, ":", &saveptr); if(verbose) D (debug_file, "Authorization token: %s", s_token); if (s_token && otp_id && strcmp (otp_id, s_token) == 0) { if(verbose) D (debug_file, "Match user/token as %s/%s", username, otp_id); fclose(opwfile); return AUTH_FOUND; } } while (s_token != NULL); } } fclose (opwfile); return retval; }
169,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item ) { cJSON_AddItemToObject( object, string, create_reference( item ) ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item )
167,266