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: error::Error GLES2DecoderImpl::HandleDrawArrays( uint32 immediate_data_size, const gles2::DrawArrays& c) { GLenum mode = static_cast<GLenum>(c.mode); GLint first = static_cast<GLint>(c.first); GLsizei count = static_cast<GLsizei>(c.count); if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawArrays: mode GL_INVALID_ENUM"); return error::kNoError; } if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawArrays: count < 0"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawArrays")) { return error::kNoError; } if (first < 0) { SetGLError(GL_INVALID_VALUE, "glDrawArrays: first < 0"); return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed = first + count - 1; 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(); glDrawArrays(mode, first, count); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawArrays."; 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::HandleDrawArrays( uint32 immediate_data_size, const gles2::DrawArrays& c) { GLenum mode = static_cast<GLenum>(c.mode); GLint first = static_cast<GLint>(c.first); GLsizei count = static_cast<GLsizei>(c.count); if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawArrays: mode GL_INVALID_ENUM"); return error::kNoError; } if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawArrays: count < 0"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawArrays")) { return error::kNoError; } if (first < 0) { SetGLError(GL_INVALID_VALUE, "glDrawArrays: first < 0"); return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed = first + count - 1; 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(); glDrawArrays(mode, first, count); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawArrays."; return error::kLostContext; } } return error::kNoError; }
170,330
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 Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { assert(m_count == 0); if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size; CuePoint** const qq = new CuePoint* [n]; CuePoint** q = qq; // beginning of target CuePoint** p = m_cue_points; // beginning of source CuePoint** const pp = p + m_preload_count; // end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new CuePoint(m_preload_count, pos); m_cue_points[m_preload_count++] = pCP; } 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
void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { bool Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { if (m_count != 0) return false; if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size; CuePoint** const qq = new (std::nothrow) CuePoint*[n]; if (qq == NULL) return false; CuePoint** q = qq; // beginning of target CuePoint** p = m_cue_points; // beginning of source CuePoint** const pp = p + m_preload_count; // end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new (std::nothrow) CuePoint(m_preload_count, pos); if (pCP == NULL) return false; m_cue_points[m_preload_count++] = pCP; return true; }
173,861
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 assertObjectHasGCInfo(const void* payload, size_t gcInfoIndex) { ASSERT(HeapObjectHeader::fromPayload(payload)->checkHeader()); #if !defined(COMPONENT_BUILD) ASSERT(HeapObjectHeader::fromPayload(payload)->gcInfoIndex() == gcInfoIndex); #endif } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
void assertObjectHasGCInfo(const void* payload, size_t gcInfoIndex) { HeapObjectHeader::fromPayload(payload)->checkHeader(); #if !defined(COMPONENT_BUILD) ASSERT(HeapObjectHeader::fromPayload(payload)->gcInfoIndex() == gcInfoIndex); #endif }
172,704
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 rpc_type_of_NPPVariable(int variable) { int type; switch (variable) { case NPPVpluginNameString: case NPPVpluginDescriptionString: case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000 type = RPC_TYPE_STRING; break; case NPPVpluginWindowSize: case NPPVpluginTimerInterval: type = RPC_TYPE_INT32; break; case NPPVpluginNeedsXEmbed: case NPPVpluginWindowBool: case NPPVpluginTransparentBool: case NPPVjavascriptPushCallerBool: case NPPVpluginKeepLibraryInMemory: type = RPC_TYPE_BOOLEAN; break; case NPPVpluginScriptableNPObject: type = RPC_TYPE_NP_OBJECT; break; default: type = RPC_ERROR_GENERIC; break; } return type; } Commit Message: Support all the new variables added CWE ID: CWE-264
int rpc_type_of_NPPVariable(int variable) { int type; switch (variable) { case NPPVpluginNameString: case NPPVpluginDescriptionString: case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000 case NPPVpluginNativeAccessibleAtkPlugId: type = RPC_TYPE_STRING; break; case NPPVpluginWindowSize: case NPPVpluginTimerInterval: type = RPC_TYPE_INT32; break; case NPPVpluginNeedsXEmbed: case NPPVpluginWindowBool: case NPPVpluginTransparentBool: case NPPVjavascriptPushCallerBool: case NPPVpluginKeepLibraryInMemory: case NPPVpluginUrlRequestsDisplayedBool: case NPPVpluginWantsAllNetworkStreams: case NPPVpluginCancelSrcStream: case NPPVSupportsAdvancedKeyHandling: type = RPC_TYPE_BOOLEAN; break; case NPPVpluginScriptableNPObject: type = RPC_TYPE_NP_OBJECT; break; default: type = RPC_ERROR_GENERIC; break; } return type; }
165,863
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 rndis_query_response(USBNetState *s, rndis_query_msg_type *buf, unsigned int length) { rndis_query_cmplt_type *resp; /* oid_supported_list is the largest data reply */ uint8_t infobuf[sizeof(oid_supported_list)]; uint32_t bufoffs, buflen; int infobuflen; unsigned int resplen; bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8; buflen = le32_to_cpu(buf->InformationBufferLength); if (bufoffs + buflen > length) return USB_RET_STALL; infobuflen = ndis_query(s, le32_to_cpu(buf->OID), bufoffs + (uint8_t *) buf, buflen, infobuf, resplen = sizeof(rndis_query_cmplt_type) + ((infobuflen < 0) ? 0 : infobuflen); resp = rndis_queue_response(s, resplen); if (!resp) return USB_RET_STALL; resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT); resp->RequestID = buf->RequestID; /* Still LE in msg buffer */ resp->MessageLength = cpu_to_le32(resplen); if (infobuflen < 0) { /* OID not supported */ resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); resp->InformationBufferLength = cpu_to_le32(0); resp->InformationBufferOffset = cpu_to_le32(0); return 0; } resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); resp->InformationBufferOffset = cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0); resp->InformationBufferLength = cpu_to_le32(infobuflen); memcpy(resp + 1, infobuf, infobuflen); return 0; } Commit Message: CWE ID: CWE-189
static int rndis_query_response(USBNetState *s, rndis_query_msg_type *buf, unsigned int length) { rndis_query_cmplt_type *resp; /* oid_supported_list is the largest data reply */ uint8_t infobuf[sizeof(oid_supported_list)]; uint32_t bufoffs, buflen; int infobuflen; unsigned int resplen; bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8; buflen = le32_to_cpu(buf->InformationBufferLength); if (buflen > length || bufoffs >= length || bufoffs + buflen > length) { return USB_RET_STALL; } infobuflen = ndis_query(s, le32_to_cpu(buf->OID), bufoffs + (uint8_t *) buf, buflen, infobuf, resplen = sizeof(rndis_query_cmplt_type) + ((infobuflen < 0) ? 0 : infobuflen); resp = rndis_queue_response(s, resplen); if (!resp) return USB_RET_STALL; resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT); resp->RequestID = buf->RequestID; /* Still LE in msg buffer */ resp->MessageLength = cpu_to_le32(resplen); if (infobuflen < 0) { /* OID not supported */ resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); resp->InformationBufferLength = cpu_to_le32(0); resp->InformationBufferOffset = cpu_to_le32(0); return 0; } resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); resp->InformationBufferOffset = cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0); resp->InformationBufferLength = cpu_to_le32(infobuflen); memcpy(resp + 1, infobuf, infobuflen); return 0; }
165,185
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 RenderWidgetHostImpl::SendFrontSurfaceIsProtected( bool is_protected, uint32 protection_state_id, int32 route_id, int gpu_host_id) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) { ui_shim->Send(new AcceleratedSurfaceMsg_SetFrontSurfaceIsProtected( route_id, is_protected, protection_state_id)); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostImpl::SendFrontSurfaceIsProtected(
171,368
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: std::unique_ptr<views::View> AutofillPopupBaseView::CreateWrapperView() { return nullptr; } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <rkaplow@chromium.org> Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org> Reviewed-by: Fabio Tirelo <ftirelo@chromium.org> Reviewed-by: Tommy Martino <tmartino@chromium.org> Commit-Queue: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
std::unique_ptr<views::View> AutofillPopupBaseView::CreateWrapperView() {
172,095
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: IOHandler::IOHandler(DevToolsIOContext* io_context) : DevToolsDomainHandler(IO::Metainfo::domainName), io_context_(io_context), process_host_(nullptr), weak_factory_(this) {} Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
IOHandler::IOHandler(DevToolsIOContext* io_context) : DevToolsDomainHandler(IO::Metainfo::domainName), io_context_(io_context), browser_context_(nullptr), storage_partition_(nullptr), weak_factory_(this) {}
172,749
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 _xml_add_to_info(xml_parser *parser,char *name) { zval **element, *values; if (! parser->info) { return; } if (zend_hash_find(Z_ARRVAL_P(parser->info),name,strlen(name) + 1,(void **) &element) == FAILURE) { MAKE_STD_ZVAL(values); array_init(values); zend_hash_update(Z_ARRVAL_P(parser->info), name, strlen(name)+1, (void *) &values, sizeof(zval*), (void **) &element); } add_next_index_long(*element,parser->curtag); parser->curtag++; } Commit Message: CWE ID: CWE-119
static void _xml_add_to_info(xml_parser *parser,char *name) { zval **element, *values; if (! parser->info) { return; } if (zend_hash_find(Z_ARRVAL_P(parser->info),name,strlen(name) + 1,(void **) &element) == FAILURE) { MAKE_STD_ZVAL(values); array_init(values); zend_hash_update(Z_ARRVAL_P(parser->info), name, strlen(name)+1, (void *) &values, sizeof(zval*), (void **) &element); } add_next_index_long(*element,parser->curtag); parser->curtag++; }
165,039
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 Cues::GetCount() const { if (m_cue_points == NULL) return -1; return m_count; //TODO: really ignore preload count? } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cues::GetCount() const const long long stop = m_start + m_size;
174,298
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 char* getPreferredTag(const char* gf_tag) { char* result = NULL; int grOffset = 0; grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag); if(grOffset < 0) { return NULL; } if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){ /* return preferred tag */ result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] ); } else { /* Return correct grandfathered language tag */ result = estrdup( LOC_GRANDFATHERED[grOffset] ); } return result; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static char* getPreferredTag(const char* gf_tag) { char* result = NULL; int grOffset = 0; grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag); if(grOffset < 0) { return NULL; } if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){ /* return preferred tag */ result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] ); } else { /* Return correct grandfathered language tag */ result = estrdup( LOC_GRANDFATHERED[grOffset] ); } return result; }
167,201
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 SetUp() { const tuple<int, int, SubpelVarianceFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; subpel_variance_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); sec_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); ref_ = new uint8_t[block_size_ + width_ + height_ + 1]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(sec_ != NULL); ASSERT_TRUE(ref_ != NULL); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { const tuple<int, int, MseFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; mse_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); ref_ = new uint8_t[block_size_]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(ref_ != NULL); }
174,590
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 rose_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name; size_t copied; unsigned char *asmptr; struct sk_buff *skb; int n, er, qbit; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) return er; qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT; skb_pull(skb, ROSE_MIN_LEN); if (rose->qbitincl) { asmptr = skb_push(skb, 1); *asmptr = qbit; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (srose != NULL) { srose->srose_family = AF_ROSE; srose->srose_addr = rose->dest_addr; srose->srose_call = rose->dest_call; srose->srose_ndigis = rose->dest_ndigis; if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name; for (n = 0 ; n < rose->dest_ndigis ; n++) full_srose->srose_digis[n] = rose->dest_digis[n]; msg->msg_namelen = sizeof(struct full_sockaddr_rose); } else { if (rose->dest_ndigis >= 1) { srose->srose_ndigis = 1; srose->srose_digi = rose->dest_digis[0]; } msg->msg_namelen = sizeof(struct sockaddr_rose); } } skb_free_datagram(sk, skb); return copied; } Commit Message: rose: fix info leak via msg_name in rose_recvmsg() The code in rose_recvmsg() does not initialize all of the members of struct sockaddr_rose/full_sockaddr_rose when filling the sockaddr info. Nor does it initialize the padding bytes of the structure inserted by the compiler for alignment. This will lead to leaking uninitialized kernel stack bytes in net/socket.c. Fix the issue by initializing the memory used for sockaddr info with memset(0). Cc: Ralf Baechle <ralf@linux-mips.org> Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
static int rose_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name; size_t copied; unsigned char *asmptr; struct sk_buff *skb; int n, er, qbit; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) return er; qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT; skb_pull(skb, ROSE_MIN_LEN); if (rose->qbitincl) { asmptr = skb_push(skb, 1); *asmptr = qbit; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (srose != NULL) { memset(srose, 0, msg->msg_namelen); srose->srose_family = AF_ROSE; srose->srose_addr = rose->dest_addr; srose->srose_call = rose->dest_call; srose->srose_ndigis = rose->dest_ndigis; if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name; for (n = 0 ; n < rose->dest_ndigis ; n++) full_srose->srose_digis[n] = rose->dest_digis[n]; msg->msg_namelen = sizeof(struct full_sockaddr_rose); } else { if (rose->dest_ndigis >= 1) { srose->srose_ndigis = 1; srose->srose_digi = rose->dest_digis[0]; } msg->msg_namelen = sizeof(struct sockaddr_rose); } } skb_free_datagram(sk, skb); return copied; }
166,033
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 _yr_scan_match_callback( uint8_t* match_data, int32_t match_length, int flags, void* args) { CALLBACK_ARGS* callback_args = (CALLBACK_ARGS*) args; YR_STRING* string = callback_args->string; YR_MATCH* new_match; int result = ERROR_SUCCESS; int tidx = callback_args->context->tidx; size_t match_offset = match_data - callback_args->data; match_length += callback_args->forward_matches; if (callback_args->full_word) { if (flags & RE_FLAGS_WIDE) { if (match_offset >= 2 && *(match_data - 1) == 0 && isalnum(*(match_data - 2))) return ERROR_SUCCESS; if (match_offset + match_length + 1 < callback_args->data_size && *(match_data + match_length + 1) == 0 && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } else { if (match_offset >= 1 && isalnum(*(match_data - 1))) return ERROR_SUCCESS; if (match_offset + match_length < callback_args->data_size && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } } if (STRING_IS_CHAIN_PART(string)) { result = _yr_scan_verify_chained_string_match( string, callback_args->context, match_data, callback_args->data_base, match_offset, match_length); } else { if (string->matches[tidx].count == 0) { FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matching_strings_arena, &string, sizeof(string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( callback_args->context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); if (result == ERROR_SUCCESS) { new_match->base = callback_args->data_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &string->matches[tidx], STRING_IS_GREEDY_REGEXP(string))); } } return result; } Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier. CWE ID: CWE-125
int _yr_scan_match_callback( uint8_t* match_data, int32_t match_length, int flags, void* args) { CALLBACK_ARGS* callback_args = (CALLBACK_ARGS*) args; YR_STRING* string = callback_args->string; YR_MATCH* new_match; int result = ERROR_SUCCESS; int tidx = callback_args->context->tidx; size_t match_offset = match_data - callback_args->data; match_length += callback_args->forward_matches; // make sure that match fits into the data. assert(match_offset + match_length <= callback_args->data_size); if (callback_args->full_word) { if (flags & RE_FLAGS_WIDE) { if (match_offset >= 2 && *(match_data - 1) == 0 && isalnum(*(match_data - 2))) return ERROR_SUCCESS; if (match_offset + match_length + 1 < callback_args->data_size && *(match_data + match_length + 1) == 0 && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } else { if (match_offset >= 1 && isalnum(*(match_data - 1))) return ERROR_SUCCESS; if (match_offset + match_length < callback_args->data_size && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } } if (STRING_IS_CHAIN_PART(string)) { result = _yr_scan_verify_chained_string_match( string, callback_args->context, match_data, callback_args->data_base, match_offset, match_length); } else { if (string->matches[tidx].count == 0) { FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matching_strings_arena, &string, sizeof(string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( callback_args->context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); if (result == ERROR_SUCCESS) { new_match->base = callback_args->data_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &string->matches[tidx], STRING_IS_GREEDY_REGEXP(string))); } } return result; }
168,099
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 WebPageSerializerImpl::openTagToString(Element* element, SerializeDomParam* param) { bool needSkip; StringBuilder result; result.append(preActionBeforeSerializeOpenTag(element, param, &needSkip)); if (needSkip) return; result.append('<'); result.append(element->nodeName().lower()); AttributeCollection attributes = element->attributes(); AttributeCollection::iterator end = attributes.end(); for (AttributeCollection::iterator it = attributes.begin(); it != end; ++it) { result.append(' '); result.append(it->name().toString()); result.appendLiteral("=\""); if (!it->value().isEmpty()) { const String& attrValue = it->value(); const QualifiedName& attrName = it->name(); if (element->hasLegalLinkAttribute(attrName)) { if (attrValue.startsWith("javascript:", TextCaseInsensitive)) { result.append(attrValue); } else { WebLocalFrameImpl* subFrame = WebLocalFrameImpl::fromFrameOwnerElement(element); String completeURL = subFrame ? subFrame->frame()->document()->url() : param->document->completeURL(attrValue); if (m_localLinks.contains(completeURL)) { if (!param->directoryName.isEmpty()) { result.appendLiteral("./"); result.append(param->directoryName); result.append('/'); } result.append(m_localLinks.get(completeURL)); } else { result.append(completeURL); } } } else { if (param->isHTMLDocument) result.append(m_htmlEntities.convertEntitiesInString(attrValue)); else result.append(m_xmlEntities.convertEntitiesInString(attrValue)); } } result.append('\"'); } String addedContents = postActionAfterSerializeOpenTag(element, param); if (element->hasChildren() || param->haveAddedContentsBeforeEnd) result.append('>'); result.append(addedContents); saveHTMLContentToBuffer(result.toString(), param); } Commit Message: Make WebPageSerializerImpl to escape URL attribute values in result. This patch makes |WebPageSerializerImpl| to escape URL attribute values rather than directly output URL attribute values into result. BUG=542054 TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.URLAttributeValues Review URL: https://codereview.chromium.org/1398453005 Cr-Commit-Position: refs/heads/master@{#353712} CWE ID: CWE-20
void WebPageSerializerImpl::openTagToString(Element* element, SerializeDomParam* param) { bool needSkip; StringBuilder result; result.append(preActionBeforeSerializeOpenTag(element, param, &needSkip)); if (needSkip) return; result.append('<'); result.append(element->nodeName().lower()); AttributeCollection attributes = element->attributes(); AttributeCollection::iterator end = attributes.end(); for (AttributeCollection::iterator it = attributes.begin(); it != end; ++it) { result.append(' '); result.append(it->name().toString()); result.appendLiteral("=\""); if (!it->value().isEmpty()) { const String& attrValue = it->value(); const QualifiedName& attrName = it->name(); if (element->hasLegalLinkAttribute(attrName)) { if (attrValue.startsWith("javascript:", TextCaseInsensitive)) { result.append(m_htmlEntities.convertEntitiesInString(attrValue)); } else { WebLocalFrameImpl* subFrame = WebLocalFrameImpl::fromFrameOwnerElement(element); String completeURL = subFrame ? subFrame->frame()->document()->url() : param->document->completeURL(attrValue); if (m_localLinks.contains(completeURL)) { if (!param->directoryName.isEmpty()) { result.appendLiteral("./"); result.append(param->directoryName); result.append('/'); } result.append(m_htmlEntities.convertEntitiesInString(m_localLinks.get(completeURL))); } else { result.append(m_htmlEntities.convertEntitiesInString(completeURL)); } } } else { if (param->isHTMLDocument) result.append(m_htmlEntities.convertEntitiesInString(attrValue)); else result.append(m_xmlEntities.convertEntitiesInString(attrValue)); } } result.append('\"'); } String addedContents = postActionAfterSerializeOpenTag(element, param); if (element->hasChildren() || param->haveAddedContentsBeforeEnd) result.append('>'); result.append(addedContents); saveHTMLContentToBuffer(result.toString(), param); }
171,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: void AcceleratedStaticBitmapImage::CreateImageFromMailboxIfNeeded() { if (texture_holder_->IsSkiaTextureHolder()) return; texture_holder_ = std::make_unique<SkiaTextureHolder>(std::move(texture_holder_)); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void AcceleratedStaticBitmapImage::CreateImageFromMailboxIfNeeded() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (texture_holder_->IsSkiaTextureHolder()) return; texture_holder_ = std::make_unique<SkiaTextureHolder>(std::move(texture_holder_)); }
172,592
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 xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx); } } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <mattjd@gmail.com> Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Acked-by: Ian Campbell <ian.campbell@citrix.com> Acked-by: Jan Beulich <JBeulich@suse.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY); } }
166,167
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: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->options -= XML_PARSE_DTDLOAD; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; ctxt->sax->error = NULL; /*ctxt->sax->fatalError = NULL;*/ #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; } Commit Message: CWE ID: CWE-200
xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->options &= ~XML_PARSE_DTDLOAD; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; ctxt->sax->error = NULL; /*ctxt->sax->fatalError = NULL;*/ #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; }
164,726
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: get_next_file(FILE *VFile, char *ptr) { char *ret; ret = fgets(ptr, PATH_MAX, VFile); if (!ret) return NULL; if (ptr[strlen(ptr) - 1] == '\n') ptr[strlen(ptr) - 1] = '\0'; return ret; } Commit Message: (for 4.9.3) CVE-2018-14879/fix -V to fail invalid input safely get_next_file() did not check the return value of strlen() and underflowed an array index if the line read by fgets() from the file started with \0. This caused an out-of-bounds read and could cause a write. Add the missing check. This vulnerability was discovered by Brian Carpenter & Geeknik Labs. CWE ID: CWE-120
get_next_file(FILE *VFile, char *ptr) { char *ret; size_t len; ret = fgets(ptr, PATH_MAX, VFile); if (!ret) return NULL; len = strlen (ptr); if (len > 0 && ptr[len - 1] == '\n') ptr[len - 1] = '\0'; return ret; }
169,835
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 sctp_getsockopt_assoc_stats(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_stats sas; struct sctp_association *asoc = NULL; /* User must provide at least the assoc id */ if (len < sizeof(sctp_assoc_t)) return -EINVAL; if (copy_from_user(&sas, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, sas.sas_assoc_id); if (!asoc) return -EINVAL; sas.sas_rtxchunks = asoc->stats.rtxchunks; sas.sas_gapcnt = asoc->stats.gapcnt; sas.sas_outofseqtsns = asoc->stats.outofseqtsns; sas.sas_osacks = asoc->stats.osacks; sas.sas_isacks = asoc->stats.isacks; sas.sas_octrlchunks = asoc->stats.octrlchunks; sas.sas_ictrlchunks = asoc->stats.ictrlchunks; sas.sas_oodchunks = asoc->stats.oodchunks; sas.sas_iodchunks = asoc->stats.iodchunks; sas.sas_ouodchunks = asoc->stats.ouodchunks; sas.sas_iuodchunks = asoc->stats.iuodchunks; sas.sas_idupchunks = asoc->stats.idupchunks; sas.sas_opackets = asoc->stats.opackets; sas.sas_ipackets = asoc->stats.ipackets; /* New high max rto observed, will return 0 if not a single * RTO update took place. obs_rto_ipaddr will be bogus * in such a case */ sas.sas_maxrto = asoc->stats.max_obs_rto; memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr, sizeof(struct sockaddr_storage)); /* Mark beginning of a new observation period */ asoc->stats.max_obs_rto = asoc->rto_min; /* Allow the struct to grow and fill in as much as possible */ len = min_t(size_t, len, sizeof(sas)); if (put_user(len, optlen)) return -EFAULT; SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n", len, sas.sas_assoc_id); if (copy_to_user(optval, &sas, len)) return -EFAULT; return 0; } Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS Building sctp may fail with: In function ‘copy_from_user’, inlined from ‘sctp_getsockopt_assoc_stats’ at net/sctp/socket.c:5656:20: arch/x86/include/asm/uaccess_32.h:211:26: error: call to ‘copy_from_user_overflow’ declared with attribute error: copy_from_user() buffer size is not provably correct if built with W=1 due to a missing parameter size validation before the call to copy_from_user. Signed-off-by: Guenter Roeck <linux@roeck-us.net> Acked-by: Vlad Yasevich <vyasevich@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
static int sctp_getsockopt_assoc_stats(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_stats sas; struct sctp_association *asoc = NULL; /* User must provide at least the assoc id */ if (len < sizeof(sctp_assoc_t)) return -EINVAL; /* Allow the struct to grow and fill in as much as possible */ len = min_t(size_t, len, sizeof(sas)); if (copy_from_user(&sas, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, sas.sas_assoc_id); if (!asoc) return -EINVAL; sas.sas_rtxchunks = asoc->stats.rtxchunks; sas.sas_gapcnt = asoc->stats.gapcnt; sas.sas_outofseqtsns = asoc->stats.outofseqtsns; sas.sas_osacks = asoc->stats.osacks; sas.sas_isacks = asoc->stats.isacks; sas.sas_octrlchunks = asoc->stats.octrlchunks; sas.sas_ictrlchunks = asoc->stats.ictrlchunks; sas.sas_oodchunks = asoc->stats.oodchunks; sas.sas_iodchunks = asoc->stats.iodchunks; sas.sas_ouodchunks = asoc->stats.ouodchunks; sas.sas_iuodchunks = asoc->stats.iuodchunks; sas.sas_idupchunks = asoc->stats.idupchunks; sas.sas_opackets = asoc->stats.opackets; sas.sas_ipackets = asoc->stats.ipackets; /* New high max rto observed, will return 0 if not a single * RTO update took place. obs_rto_ipaddr will be bogus * in such a case */ sas.sas_maxrto = asoc->stats.max_obs_rto; memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr, sizeof(struct sockaddr_storage)); /* Mark beginning of a new observation period */ asoc->stats.max_obs_rto = asoc->rto_min; if (put_user(len, optlen)) return -EFAULT; SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n", len, sas.sas_assoc_id); if (copy_to_user(optval, &sas, len)) return -EFAULT; return 0; }
166,111
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 PrintPreviewUI::GetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedBytes>* data) { print_preview_data_service()->GetDataEntry(preview_ui_addr_str_, index, data); } 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 PrintPreviewUI::GetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedBytes>* data) { print_preview_data_service()->GetDataEntry(id_, index, data); }
170,834
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: INST_HANDLER (sbrx) { // SBRC Rr, b int b = buf[0] & 0x7; int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4); RAnalOp next_op; avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; op->cycles = 1; // XXX: This is a bug, because depends on eval state, ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBRC => branch if cleared : "!,!,"); // SBRS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } Commit Message: Fix invalid free in RAnal.avr CWE ID: CWE-125
INST_HANDLER (sbrx) { // SBRC Rr, b int b = buf[0] & 0x7; int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4); RAnalOp next_op = {0}; avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; op->cycles = 1; // XXX: This is a bug, because depends on eval state, ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBRC => branch if cleared : "!,!,"); // SBRS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp }
169,231
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 WebMediaPlayerImpl::OnError(PipelineStatus status) { DVLOG(1) << __func__; DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK_NE(status, PIPELINE_OK); if (suppress_destruction_errors_) return; #if defined(OS_ANDROID) if (status == PipelineStatus::DEMUXER_ERROR_DETECTED_HLS) { renderer_factory_selector_->SetUseMediaPlayer(true); pipeline_controller_.Stop(); SetMemoryReportingState(false); main_task_runner_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerImpl::StartPipeline, AsWeakPtr())); return; } #endif ReportPipelineError(load_type_, status, media_log_.get()); media_log_->AddEvent(media_log_->CreatePipelineErrorEvent(status)); media_metrics_provider_->OnError(status); if (watch_time_reporter_) watch_time_reporter_->OnError(status); if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) { SetNetworkState(WebMediaPlayer::kNetworkStateFormatError); } else { SetNetworkState(PipelineErrorToNetworkState(status)); } pipeline_controller_.Stop(); UpdatePlayState(); } Commit Message: Fix HasSingleSecurityOrigin for HLS HLS manifests can request segments from a different origin than the original manifest's origin. We do not inspect HLS manifests within Chromium, and instead delegate to Android's MediaPlayer. This means we need to be conservative, and always assume segments might come from a different origin. HasSingleSecurityOrigin should always return false when decoding HLS. Bug: 864283 Change-Id: Ie16849ac6f29ae7eaa9caf342ad0509a226228ef Reviewed-on: https://chromium-review.googlesource.com/1142691 Reviewed-by: Dale Curtis <dalecurtis@chromium.org> Reviewed-by: Dominick Ng <dominickn@chromium.org> Commit-Queue: Thomas Guilbert <tguilbert@chromium.org> Cr-Commit-Position: refs/heads/master@{#576378} CWE ID: CWE-346
void WebMediaPlayerImpl::OnError(PipelineStatus status) { DVLOG(1) << __func__; DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK_NE(status, PIPELINE_OK); if (suppress_destruction_errors_) return; #if defined(OS_ANDROID) if (status == PipelineStatus::DEMUXER_ERROR_DETECTED_HLS) { demuxer_found_hls_ = true; renderer_factory_selector_->SetUseMediaPlayer(true); pipeline_controller_.Stop(); SetMemoryReportingState(false); main_task_runner_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerImpl::StartPipeline, AsWeakPtr())); return; } #endif ReportPipelineError(load_type_, status, media_log_.get()); media_log_->AddEvent(media_log_->CreatePipelineErrorEvent(status)); media_metrics_provider_->OnError(status); if (watch_time_reporter_) watch_time_reporter_->OnError(status); if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) { SetNetworkState(WebMediaPlayer::kNetworkStateFormatError); } else { SetNetworkState(PipelineErrorToNetworkState(status)); } pipeline_controller_.Stop(); UpdatePlayState(); }
173,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: static void cmd_parse_lsub(struct ImapData *idata, char *s) { char buf[STRING]; char errstr[STRING]; struct Buffer err, token; struct Url url; struct ImapList list; if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST) { /* caller will handle response itself */ cmd_parse_list(idata, s); return; } if (!ImapCheckSubscribed) return; idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &list; cmd_parse_list(idata, s); idata->cmddata = NULL; /* noselect is for a gmail quirk (#3445) */ if (!list.name || list.noselect) return; mutt_debug(3, "Subscribing to %s\n", list.name); mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf)); mutt_account_tourl(&idata->conn->account, &url); /* escape \ and " */ imap_quote_string(errstr, sizeof(errstr), list.name); url.path = errstr + 1; url.path[strlen(url.path) - 1] = '\0'; if (mutt_str_strcmp(url.user, ImapUser) == 0) url.user = NULL; url_tostring(&url, buf + 11, sizeof(buf) - 11, 0); mutt_str_strcat(buf, sizeof(buf), "\""); mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); if (mutt_parse_rc_line(buf, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } Commit Message: quote imap strings more carefully Co-authored-by: JerikoOne <jeriko.one@gmx.us> CWE ID: CWE-77
static void cmd_parse_lsub(struct ImapData *idata, char *s) { char buf[STRING]; char errstr[STRING]; struct Buffer err, token; struct Url url; struct ImapList list; if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST) { /* caller will handle response itself */ cmd_parse_list(idata, s); return; } if (!ImapCheckSubscribed) return; idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &list; cmd_parse_list(idata, s); idata->cmddata = NULL; /* noselect is for a gmail quirk (#3445) */ if (!list.name || list.noselect) return; mutt_debug(3, "Subscribing to %s\n", list.name); mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf)); mutt_account_tourl(&idata->conn->account, &url); /* escape \ and " */ imap_quote_string(errstr, sizeof(errstr), list.name, true); url.path = errstr + 1; url.path[strlen(url.path) - 1] = '\0'; if (mutt_str_strcmp(url.user, ImapUser) == 0) url.user = NULL; url_tostring(&url, buf + 11, sizeof(buf) - 11, 0); mutt_str_strcat(buf, sizeof(buf), "\""); mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); if (mutt_parse_rc_line(buf, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); }
169,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: dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree, guint8 *drep _U_, char **data, int hf_name) { gint len, remaining; char *text; if (offset % 2) offset += 2 - (offset % 2); /* Get remaining data in buffer as a string */ remaining = tvb_captured_length_remaining(tvb, offset); if (remaining <= 0) { if (data) *data = g_strdup(""); return offset; } text = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN); len = (int)strlen(text); proto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text); if (data) *data = text; else g_free(text); return offset + (len + 1) * 2; } Commit Message: SPOOLSS: Try to avoid an infinite loop. Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make sure our offset always increments in dissect_spoolss_keybuffer. Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793 Reviewed-on: https://code.wireshark.org/review/14687 Reviewed-by: Gerald Combs <gerald@wireshark.org> Petri-Dish: Gerald Combs <gerald@wireshark.org> Tested-by: Petri Dish Buildbot <buildbot-no-reply@wireshark.org> Reviewed-by: Michael Mann <mmann78@netscape.net> CWE ID: CWE-399
dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree, guint8 *drep _U_, char **data, int hf_name) { gint len, remaining; char *text; if (offset % 2) offset += 2 - (offset % 2); /* Get remaining data in buffer as a string */ remaining = tvb_reported_length_remaining(tvb, offset); if (remaining <= 0) { if (data) *data = g_strdup(""); return offset; } text = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN); len = (int)strlen(text); proto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text); if (data) *data = text; else g_free(text); return offset + (len + 1) * 2; }
167,160
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 PageRequestSummary::UpdateOrAddToOrigins( const GURL& url, const content::mojom::CommonNetworkInfoPtr& network_info) { GURL origin = url.GetOrigin(); if (!origin.is_valid()) return; auto it = origins.find(origin); if (it == origins.end()) { OriginRequestSummary summary; summary.origin = origin; summary.first_occurrence = origins.size(); it = origins.insert({origin, summary}).first; } it->second.always_access_network |= network_info->always_access_network; it->second.accessed_network |= network_info->network_accessed; } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void PageRequestSummary::UpdateOrAddToOrigins( const url::Origin& origin, const content::mojom::CommonNetworkInfoPtr& network_info) { if (origin.opaque()) return; auto it = origins.find(origin); if (it == origins.end()) { OriginRequestSummary summary; summary.origin = origin; summary.first_occurrence = origins.size(); it = origins.insert({origin, summary}).first; } it->second.always_access_network |= network_info->always_access_network; it->second.accessed_network |= network_info->network_accessed; }
172,368
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 uint8_t *extend_raw_data(LHAFileHeader **header, LHAInputStream *stream, size_t nbytes) { LHAFileHeader *new_header; size_t new_raw_len; uint8_t *result; new_raw_len = RAW_DATA_LEN(header) + nbytes; new_header = realloc(*header, sizeof(LHAFileHeader) + new_raw_len); if (new_header == NULL) { return NULL; } *header = new_header; new_header->raw_data = (uint8_t *) (new_header + 1); result = new_header->raw_data + new_header->raw_data_len; if (!lha_input_stream_read(stream, result, nbytes)) { return NULL; } new_header->raw_data_len = new_raw_len; return result; } Commit Message: Fix integer underflow vulnerability in L3 decode. Marcin 'Icewall' Noga of Cisco TALOS discovered that the level 3 header decoding routines were vulnerable to an integer underflow, if the 32-bit header length was less than the base level 3 header length. This could lead to an exploitable heap corruption condition. Thanks go to Marcin Noga and Regina Wilson of Cisco TALOS for reporting this vulnerability. CWE ID: CWE-190
static uint8_t *extend_raw_data(LHAFileHeader **header, LHAInputStream *stream, size_t nbytes) { LHAFileHeader *new_header; size_t new_raw_len; uint8_t *result; if (nbytes > LEVEL_3_MAX_HEADER_LEN) { return NULL; } new_raw_len = RAW_DATA_LEN(header) + nbytes; new_header = realloc(*header, sizeof(LHAFileHeader) + new_raw_len); if (new_header == NULL) { return NULL; } *header = new_header; new_header->raw_data = (uint8_t *) (new_header + 1); result = new_header->raw_data + new_header->raw_data_len; if (!lha_input_stream_read(stream, result, nbytes)) { return NULL; } new_header->raw_data_len = new_raw_len; return result; }
168,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: void EC_GROUP_clear_free(EC_GROUP *group) { if (!group) return; if (group->meth->group_clear_finish != 0) group->meth->group_clear_finish(group); else if (group->meth->group_finish != 0) group->meth->group_finish(group); EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_POINT_clear_free(group->generator); BN_clear_free(&group->order); OPENSSL_cleanse(group, sizeof *group); OPENSSL_free(group); } Commit Message: CWE ID: CWE-320
void EC_GROUP_clear_free(EC_GROUP *group) { if (!group) return; if (group->meth->group_clear_finish != 0) group->meth->group_clear_finish(group); else if (group->meth->group_finish != 0) group->meth->group_finish(group); EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->mont_data) BN_MONT_CTX_free(group->mont_data); if (group->generator != NULL) EC_POINT_clear_free(group->generator); BN_clear_free(&group->order); OPENSSL_cleanse(group, sizeof *group); OPENSSL_free(group); }
165,506
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 AutoFillMetrics::Log(QualityMetric metric) const { DCHECK(metric < NUM_QUALITY_METRICS); UMA_HISTOGRAM_ENUMERATION("AutoFill.Quality", metric, NUM_QUALITY_METRICS); } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutoFillMetrics::Log(QualityMetric metric) const { void AutoFillMetrics::Log(QualityMetric metric, const std::string& experiment_id) const { DCHECK(metric < NUM_QUALITY_METRICS); std::string histogram_name = "AutoFill.Quality"; if (!experiment_id.empty()) histogram_name += "_" + experiment_id; UMA_HISTOGRAM_ENUMERATION(histogram_name, metric, NUM_QUALITY_METRICS); }
170,652
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: pdf_load_xobject(fz_context *ctx, pdf_document *doc, pdf_obj *dict) { pdf_xobject *form; if ((form = pdf_find_item(ctx, pdf_drop_xobject_imp, dict)) != NULL) return form; form->iteration = 0; /* Store item immediately, to avoid possible recursion if objects refer back to this one */ pdf_store_item(ctx, dict, form, pdf_xobject_size(form)); form->obj = pdf_keep_obj(ctx, dict); return form; } Commit Message: CWE ID: CWE-20
pdf_load_xobject(fz_context *ctx, pdf_document *doc, pdf_obj *dict) { pdf_xobject *form; if (!pdf_is_stream(ctx, dict)) fz_throw(ctx, FZ_ERROR_SYNTAX, "XObject must be a stream"); if ((form = pdf_find_item(ctx, pdf_drop_xobject_imp, dict)) != NULL) return form; form->iteration = 0; /* Store item immediately, to avoid possible recursion if objects refer back to this one */ pdf_store_item(ctx, dict, form, pdf_xobject_size(form)); form->obj = pdf_keep_obj(ctx, dict); return form; }
164,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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: Response StorageHandler::TrackIndexedDBForOrigin(const std::string& origin) { if (!process_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); GetIndexedDBObserver()->TaskRunner()->PostTask( FROM_HERE, base::BindOnce(&IndexedDBObserver::TrackOriginOnIDBThread, base::Unretained(GetIndexedDBObserver()), url::Origin::Create(origin_url))); return Response::OK(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
Response StorageHandler::TrackIndexedDBForOrigin(const std::string& origin) { if (!storage_partition_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); GetIndexedDBObserver()->TaskRunner()->PostTask( FROM_HERE, base::BindOnce(&IndexedDBObserver::TrackOriginOnIDBThread, base::Unretained(GetIndexedDBObserver()), url::Origin::Create(origin_url))); return Response::OK(); }
172,777
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 __net_init int setup_net(struct net *net, struct user_namespace *user_ns) { /* Must be called with pernet_ops_rwsem held */ const struct pernet_operations *ops, *saved_ops; int error = 0; LIST_HEAD(net_exit_list); refcount_set(&net->count, 1); refcount_set(&net->passive, 1); net->dev_base_seq = 1; net->user_ns = user_ns; idr_init(&net->netns_ids); spin_lock_init(&net->nsid_lock); mutex_init(&net->ipv4.ra_mutex); list_for_each_entry(ops, &pernet_list, list) { error = ops_init(ops, net); if (error < 0) goto out_undo; } down_write(&net_rwsem); list_add_tail_rcu(&net->list, &net_namespace_list); up_write(&net_rwsem); out: return error; out_undo: /* Walk through the list backwards calling the exit functions * for the pernet modules whose init functions did not fail. */ list_add(&net->exit_list, &net_exit_list); saved_ops = ops; list_for_each_entry_continue_reverse(ops, &pernet_list, list) ops_exit_list(ops, &net_exit_list); ops = saved_ops; list_for_each_entry_continue_reverse(ops, &pernet_list, list) ops_free_list(ops, &net_exit_list); rcu_barrier(); goto out; } Commit Message: netns: provide pure entropy for net_hash_mix() net_hash_mix() currently uses kernel address of a struct net, and is used in many places that could be used to reveal this address to a patient attacker, thus defeating KASLR, for the typical case (initial net namespace, &init_net is not dynamically allocated) I believe the original implementation tried to avoid spending too many cycles in this function, but security comes first. Also provide entropy regardless of CONFIG_NET_NS. Fixes: 0b4419162aa6 ("netns: introduce the net_hash_mix "salt" for hashes") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Pavel Emelyanov <xemul@openvz.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
static __net_init int setup_net(struct net *net, struct user_namespace *user_ns) { /* Must be called with pernet_ops_rwsem held */ const struct pernet_operations *ops, *saved_ops; int error = 0; LIST_HEAD(net_exit_list); refcount_set(&net->count, 1); refcount_set(&net->passive, 1); get_random_bytes(&net->hash_mix, sizeof(u32)); net->dev_base_seq = 1; net->user_ns = user_ns; idr_init(&net->netns_ids); spin_lock_init(&net->nsid_lock); mutex_init(&net->ipv4.ra_mutex); list_for_each_entry(ops, &pernet_list, list) { error = ops_init(ops, net); if (error < 0) goto out_undo; } down_write(&net_rwsem); list_add_tail_rcu(&net->list, &net_namespace_list); up_write(&net_rwsem); out: return error; out_undo: /* Walk through the list backwards calling the exit functions * for the pernet modules whose init functions did not fail. */ list_add(&net->exit_list, &net_exit_list); saved_ops = ops; list_for_each_entry_continue_reverse(ops, &pernet_list, list) ops_exit_list(ops, &net_exit_list); ops = saved_ops; list_for_each_entry_continue_reverse(ops, &pernet_list, list) ops_free_list(ops, &net_exit_list); rcu_barrier(); goto out; }
169,715
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 MediaElementAudioSourceHandler::OnCurrentSrcChanged( const KURL& current_src) { DCHECK(IsMainThread()); Locker<MediaElementAudioSourceHandler> locker(*this); passes_current_src_cors_access_check_ = PassesCurrentSrcCORSAccessCheck(current_src); maybe_print_cors_message_ = !passes_current_src_cors_access_check_; current_src_string_ = current_src.GetString(); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <rtoy@chromium.org> Reviewed-by: Yutaka Hirano <yhirano@chromium.org> Reviewed-by: Hongchan Choi <hongchan@chromium.org> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceHandler::OnCurrentSrcChanged( bool MediaElementAudioSourceHandler::WouldTaintOrigin() { // If we're cross-origin and allowed access vie CORS, we're not tainted. if (MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) { return false; } // Handles the case where the url is a redirect to another site that we're not // allowed to access. if (!MediaElement()->HasSingleSecurityOrigin()) { return true; }
173,145
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 php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; php_stream *file; size_t memsize; char *membuf; off_t pos; assert(ts != NULL); if (!ts->innerstream) { return FAILURE; } if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) { return php_stream_cast(ts->innerstream, castas, ret, 0); } /* we are still using a memory based backing. If they are if we can be * a FILE*, say yes because we can perform the conversion. * If they actually want to perform the conversion, we need to switch * the memory stream to a tmpfile stream */ if (ret == NULL && castas == PHP_STREAM_AS_STDIO) { return SUCCESS; } /* say "no" to other stream forms */ if (ret == NULL) { return FAILURE; } /* perform the conversion and then pass the request on to the innerstream */ membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize); file = php_stream_fopen_tmpfile(); php_stream_write(file, membuf, memsize); pos = php_stream_tell(ts->innerstream); php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE); ts->innerstream = file; php_stream_encloses(stream, ts->innerstream); php_stream_seek(ts->innerstream, pos, SEEK_SET); return php_stream_cast(ts->innerstream, castas, ret, 1); } Commit Message: CWE ID: CWE-20
static int php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; php_stream *file; size_t memsize; char *membuf; off_t pos; assert(ts != NULL); if (!ts->innerstream) { return FAILURE; } if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) { return php_stream_cast(ts->innerstream, castas, ret, 0); } /* we are still using a memory based backing. If they are if we can be * a FILE*, say yes because we can perform the conversion. * If they actually want to perform the conversion, we need to switch * the memory stream to a tmpfile stream */ if (ret == NULL && castas == PHP_STREAM_AS_STDIO) { return SUCCESS; } /* say "no" to other stream forms */ if (ret == NULL) { return FAILURE; } /* perform the conversion and then pass the request on to the innerstream */ membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize); file = php_stream_fopen_tmpfile(); php_stream_write(file, membuf, memsize); pos = php_stream_tell(ts->innerstream); php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE); ts->innerstream = file; php_stream_encloses(stream, ts->innerstream); php_stream_seek(ts->innerstream, pos, SEEK_SET); return php_stream_cast(ts->innerstream, castas, ret, 1); }
165,478
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: standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id, int do_interlace, int use_update_info) { standard_display d; context(psIn, fault); /* Set up the display (stack frame) variables from the arguments to the * function and initialize the locals that are filled in later. */ standard_display_init(&d, psIn, id, do_interlace, use_update_info); /* Everything is protected by a Try/Catch. The functions called also * typically have local Try/Catch blocks. */ Try { png_structp pp; png_infop pi; /* Get a png_struct for reading the image. This will throw an error if it * fails, so we don't need to check the result. */ pp = set_store_for_read(d.ps, &pi, d.id, d.do_interlace ? (d.ps->progressive ? "pngvalid progressive deinterlacer" : "pngvalid sequential deinterlacer") : (d.ps->progressive ? "progressive reader" : "sequential reader")); /* Initialize the palette correctly from the png_store_file. */ standard_palette_init(&d); /* Introduce the correct read function. */ if (d.ps->progressive) { png_set_progressive_read_fn(pp, &d, standard_info, progressive_row, standard_end); /* Now feed data into the reader until we reach the end: */ store_progressive_read(d.ps, pp, pi); } else { /* Note that this takes the store, not the display. */ png_set_read_fn(pp, d.ps, store_read); /* Check the header values: */ png_read_info(pp, pi); /* The code tests both versions of the images that the sequential * reader can produce. */ standard_info_imp(&d, pp, pi, 2 /*images*/); /* Need the total bytes in the image below; we can't get to this point * unless the PNG file values have been checked against the expected * values. */ { sequential_row(&d, pp, pi, 0, 1); /* After the last pass loop over the rows again to check that the * image is correct. */ if (!d.speed) { standard_text_validate(&d, pp, pi, 1/*check_end*/); standard_image_validate(&d, pp, 0, 1); } else d.ps->validated = 1; } } /* Check for validation. */ if (!d.ps->validated) png_error(pp, "image read failed silently"); /* Successful completion. */ } Catch(fault) d.ps = fault; /* make sure this hasn't been clobbered. */ /* In either case clean up the store. */ store_read_reset(d.ps); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id, standard_test(png_store* const psIn, png_uint_32 const id, int do_interlace, int use_update_info) { standard_display d; context(psIn, fault); /* Set up the display (stack frame) variables from the arguments to the * function and initialize the locals that are filled in later. */ standard_display_init(&d, psIn, id, do_interlace, use_update_info); /* Everything is protected by a Try/Catch. The functions called also * typically have local Try/Catch blocks. */ Try { png_structp pp; png_infop pi; /* Get a png_struct for reading the image. This will throw an error if it * fails, so we don't need to check the result. */ pp = set_store_for_read(d.ps, &pi, d.id, d.do_interlace ? (d.ps->progressive ? "pngvalid progressive deinterlacer" : "pngvalid sequential deinterlacer") : (d.ps->progressive ? "progressive reader" : "sequential reader")); /* Initialize the palette correctly from the png_store_file. */ standard_palette_init(&d); /* Introduce the correct read function. */ if (d.ps->progressive) { png_set_progressive_read_fn(pp, &d, standard_info, progressive_row, standard_end); /* Now feed data into the reader until we reach the end: */ store_progressive_read(d.ps, pp, pi); } else { /* Note that this takes the store, not the display. */ png_set_read_fn(pp, d.ps, store_read); /* Check the header values: */ png_read_info(pp, pi); /* The code tests both versions of the images that the sequential * reader can produce. */ standard_info_imp(&d, pp, pi, 2 /*images*/); /* Need the total bytes in the image below; we can't get to this point * unless the PNG file values have been checked against the expected * values. */ { sequential_row(&d, pp, pi, 0, 1); /* After the last pass loop over the rows again to check that the * image is correct. */ if (!d.speed) { standard_text_validate(&d, pp, pi, 1/*check_end*/); standard_image_validate(&d, pp, 0, 1); } else d.ps->validated = 1; } } /* Check for validation. */ if (!d.ps->validated) png_error(pp, "image read failed silently"); /* Successful completion. */ } Catch(fault) d.ps = fault; /* make sure this hasn't been clobbered. */ /* In either case clean up the store. */ store_read_reset(d.ps); }
173,702
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: zsetcolor(i_ctx_t * i_ctx_p) { os_ptr op = osp; es_ptr ep; const gs_color_space * pcs = gs_currentcolorspace(igs); gs_client_color cc; int n_comps, n_numeric_comps, num_offset = 0, code, depth; PS_colour_space_t *space; /* initialize the client color pattern pointer for GC */ cc.pattern = 0; /* check for a pattern color space */ if ((n_comps = cs_num_components(pcs)) < 0) { n_comps = -n_comps; if (r_has_type(op, t_dictionary)) { ref *pImpl, pPatInst; code = dict_find_string(op, "Implementation", &pImpl); if (code != 0) { code = array_get(imemory, pImpl, 0, &pPatInst); if (code < 0) return code; n_numeric_comps = ( pattern_instance_uses_base_space(cc.pattern) ? n_comps - 1 : 0 ); } else n_numeric_comps = 0; } else n_numeric_comps = 0; num_offset = 1; } else n_numeric_comps = n_comps; /* gather the numeric operands */ code = float_params(op - num_offset, n_numeric_comps, cc.paint.values); if (code < 0) return code; /* The values are copied to graphic state and compared with */ /* other colors by memcmp() in gx_hld_saved_color_equal() */ /* This is the easiest way to avoid indeterminism */ memset(cc.paint.values + n_numeric_comps, 0, sizeof(cc.paint.values) - sizeof(*cc.paint.values)*n_numeric_comps); code = get_space_object(i_ctx_p, &istate->colorspace[0].array, &space); if (code < 0) return code; if (space->validatecomponents) { code = space->validatecomponents(i_ctx_p, &istate->colorspace[0].array, cc.paint.values, n_numeric_comps); if (code < 0) return code; } /* pass the color to the graphic library */ if ((code = gs_setcolor(igs, &cc)) >= 0) { if (n_comps > n_numeric_comps) { istate->pattern[0] = *op; /* save pattern dict or null */ } } /* Check the color spaces, to see if we need to run any tint transform * procedures. Some Adobe applications *eg Photoshop) expect that the * tint transform will be run and use this to set up duotone DeviceN * spaces. */ code = validate_spaces(i_ctx_p, &istate->colorspace[0].array, &depth); if (code < 0) return code; /* Set up for the continuation procedure which will do the work */ /* Make sure the exec stack has enough space */ check_estack(5); /* A place holder for data potentially used by transform functions */ ep = esp += 1; make_int(ep, 0); /* Store the 'depth' of the space returned during checking above */ ep = esp += 1; make_int(ep, 0); /* Store the 'stage' of processing (initially 0) */ ep = esp += 1; make_int(ep, 0); /* Store a pointer to the color space stored on the operand stack * as the stack may grow unpredictably making further access * to the space difficult */ ep = esp += 1; *ep = istate->colorspace[0].array; /* Finally, the actual continuation routine */ push_op_estack(setcolor_cont); return o_push_estack; } Commit Message: CWE ID: CWE-704
zsetcolor(i_ctx_t * i_ctx_p) { os_ptr op = osp; es_ptr ep; const gs_color_space * pcs = gs_currentcolorspace(igs); gs_client_color cc; int n_comps, n_numeric_comps, num_offset = 0, code, depth; PS_colour_space_t *space; /* initialize the client color pattern pointer for GC */ cc.pattern = 0; /* check for a pattern color space */ if ((n_comps = cs_num_components(pcs)) < 0) { n_comps = -n_comps; if (r_has_type(op, t_dictionary)) { ref *pImpl, pPatInst; if ((code = dict_find_string(op, "Implementation", &pImpl)) < 0) return code; if (code > 0) { code = array_get(imemory, pImpl, 0, &pPatInst); if (code < 0) return code; n_numeric_comps = ( pattern_instance_uses_base_space(cc.pattern) ? n_comps - 1 : 0 ); } else n_numeric_comps = 0; } else n_numeric_comps = 0; num_offset = 1; } else n_numeric_comps = n_comps; /* gather the numeric operands */ code = float_params(op - num_offset, n_numeric_comps, cc.paint.values); if (code < 0) return code; /* The values are copied to graphic state and compared with */ /* other colors by memcmp() in gx_hld_saved_color_equal() */ /* This is the easiest way to avoid indeterminism */ memset(cc.paint.values + n_numeric_comps, 0, sizeof(cc.paint.values) - sizeof(*cc.paint.values)*n_numeric_comps); code = get_space_object(i_ctx_p, &istate->colorspace[0].array, &space); if (code < 0) return code; if (space->validatecomponents) { code = space->validatecomponents(i_ctx_p, &istate->colorspace[0].array, cc.paint.values, n_numeric_comps); if (code < 0) return code; } /* pass the color to the graphic library */ if ((code = gs_setcolor(igs, &cc)) >= 0) { if (n_comps > n_numeric_comps) { istate->pattern[0] = *op; /* save pattern dict or null */ } } /* Check the color spaces, to see if we need to run any tint transform * procedures. Some Adobe applications *eg Photoshop) expect that the * tint transform will be run and use this to set up duotone DeviceN * spaces. */ code = validate_spaces(i_ctx_p, &istate->colorspace[0].array, &depth); if (code < 0) return code; /* Set up for the continuation procedure which will do the work */ /* Make sure the exec stack has enough space */ check_estack(5); /* A place holder for data potentially used by transform functions */ ep = esp += 1; make_int(ep, 0); /* Store the 'depth' of the space returned during checking above */ ep = esp += 1; make_int(ep, 0); /* Store the 'stage' of processing (initially 0) */ ep = esp += 1; make_int(ep, 0); /* Store a pointer to the color space stored on the operand stack * as the stack may grow unpredictably making further access * to the space difficult */ ep = esp += 1; *ep = istate->colorspace[0].array; /* Finally, the actual continuation routine */ push_op_estack(setcolor_cont); return o_push_estack; }
164,697
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 DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(data_reduction_proxy_service_->compression_stats()); if (spdy_proxy_auth_enabled_.GetValue() != enabled) { spdy_proxy_auth_enabled_.SetValue(enabled); OnProxyEnabledPrefChange(); #if defined(OS_ANDROID) data_reduction_proxy_service_->compression_stats() ->SetDataUsageReportingEnabled(enabled); #endif // defined(OS_ANDROID) } } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(data_reduction_proxy_service_->compression_stats()); if (GetOriginalProfilePrefs()->GetBoolean(prefs::kDataSaverEnabled) != enabled) { GetOriginalProfilePrefs()->SetBoolean(prefs::kDataSaverEnabled, enabled); OnProxyEnabledPrefChange(); #if defined(OS_ANDROID) data_reduction_proxy_service_->compression_stats() ->SetDataUsageReportingEnabled(enabled); #endif // defined(OS_ANDROID) } }
172,558
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: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return (*field_rtrn != NULL); case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; } Commit Message: Fail expression lookup on invalid atoms If we fail atom lookup, then we should not claim that we successfully looked up the expression. Signed-off-by: Daniel Stone <daniels@collabora.com> CWE ID: CWE-476
ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return (*field_rtrn != NULL); case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return (*elem_rtrn != NULL && *field_rtrn != NULL); case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; if (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL) return false; if (*field_rtrn == NULL) return false; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; }
169,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 DocumentLoader::CommitNavigation(const AtomicString& mime_type, const KURL& overriding_url) { if (state_ != kProvisional) return; if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) { SetHistoryItemStateForCommit( GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_, HistoryNavigationType::kDifferentDocument); } DCHECK_EQ(state_, kProvisional); GetFrameLoader().CommitProvisionalLoad(); if (!frame_) return; const AtomicString& encoding = GetResponse().TextEncodingName(); Document* owner_document = nullptr; if (Document::ShouldInheritSecurityOriginFromOwner(Url())) { Frame* owner_frame = frame_->Tree().Parent(); if (!owner_frame) owner_frame = frame_->Loader().Opener(); if (owner_frame && owner_frame->IsLocalFrame()) owner_document = ToLocalFrame(owner_frame)->GetDocument(); } DCHECK(frame_->GetPage()); ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing; if (!Document::ThreadedParsingEnabledForTesting()) parsing_policy = kForceSynchronousParsing; InstallNewDocument(Url(), owner_document, frame_->ShouldReuseDefaultView(Url()) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew, mime_type, encoding, InstallNewDocumentReason::kNavigation, parsing_policy, overriding_url); parser_->SetDocumentWasLoadedAsPartOfNavigation(); if (request_.WasDiscarded()) frame_->GetDocument()->SetWasDiscarded(true); frame_->GetDocument()->MaybeHandleHttpRefresh( response_.HttpHeaderField(HTTPNames::Refresh), Document::kHttpRefreshFromHeader); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
void DocumentLoader::CommitNavigation(const AtomicString& mime_type, const KURL& overriding_url) { if (state_ != kProvisional) return; if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) { SetHistoryItemStateForCommit( GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_, HistoryNavigationType::kDifferentDocument); } DCHECK_EQ(state_, kProvisional); GetFrameLoader().CommitProvisionalLoad(); if (!frame_) return; const AtomicString& encoding = GetResponse().TextEncodingName(); Document* owner_document = nullptr; if (Document::ShouldInheritSecurityOriginFromOwner(Url())) { Frame* owner_frame = frame_->Tree().Parent(); if (!owner_frame) owner_frame = frame_->Loader().Opener(); if (owner_frame && owner_frame->IsLocalFrame()) owner_document = ToLocalFrame(owner_frame)->GetDocument(); } DCHECK(frame_->GetPage()); ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing; if (!Document::ThreadedParsingEnabledForTesting()) parsing_policy = kForceSynchronousParsing; InstallNewDocument( Url(), owner_document, frame_->ShouldReuseDefaultView(Url(), GetContentSecurityPolicy()) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew, mime_type, encoding, InstallNewDocumentReason::kNavigation, parsing_policy, overriding_url); parser_->SetDocumentWasLoadedAsPartOfNavigation(); if (request_.WasDiscarded()) frame_->GetDocument()->SetWasDiscarded(true); frame_->GetDocument()->MaybeHandleHttpRefresh( response_.HttpHeaderField(HTTPNames::Refresh), Document::kHttpRefreshFromHeader); }
173,197
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 update_open_stateflags(struct nfs4_state *state, mode_t open_flags) { switch (open_flags) { case FMODE_WRITE: state->n_wronly++; break; case FMODE_READ: state->n_rdonly++; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr++; } nfs4_state_set_mode_locked(state, state->state | open_flags); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static void update_open_stateflags(struct nfs4_state *state, mode_t open_flags) static void update_open_stateflags(struct nfs4_state *state, fmode_t fmode) { switch (fmode) { case FMODE_WRITE: state->n_wronly++; break; case FMODE_READ: state->n_rdonly++; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr++; } nfs4_state_set_mode_locked(state, state->state | fmode); }
165,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: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 4; fwd_txfm_ref = fdct4x4_ref; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 4; fwd_txfm_ref = fdct4x4_ref; bit_depth_ = GET_PARAM(3); mask_ = (1 << bit_depth_) - 1; }
174,555
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; SMP_TRACE_DEBUG("%s", __func__); STREAM_TO_ARRAY(p_cb->ltk, p, BT_OCTET16_LEN); smp_key_distribution(p_cb, NULL); } Commit Message: Checks the SMP length to fix OOB read Bug: 111937065 Test: manual Change-Id: I330880a6e1671d0117845430db4076dfe1aba688 Merged-In: I330880a6e1671d0117845430db4076dfe1aba688 (cherry picked from commit fceb753bda651c4135f3f93a510e5fcb4c7542b8) CWE ID: CWE-200
void smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; SMP_TRACE_DEBUG("%s", __func__); if (smp_command_has_invalid_parameters(p_cb)) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_INVALID_PARAMETERS; android_errorWriteLog(0x534e4554, "111937065"); smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); return; } STREAM_TO_ARRAY(p_cb->ltk, p, BT_OCTET16_LEN); smp_key_distribution(p_cb, NULL); }
174,074
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 v9fs_attach(void *opaque) { V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; int32_t fid, afid, n_uname; V9fsString uname, aname; V9fsFidState *fidp; size_t offset = 7; V9fsQID qid; ssize_t err; v9fs_string_init(&uname); v9fs_string_init(&aname); err = pdu_unmarshal(pdu, offset, "ddssd", &fid, &afid, &uname, &aname, &n_uname); if (err < 0) { goto out_nofid; } trace_v9fs_attach(pdu->tag, pdu->id, fid, afid, uname.data, aname.data); fidp = alloc_fid(s, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } fidp->uid = n_uname; err = v9fs_co_name_to_path(pdu, NULL, "/", &fidp->path); if (err < 0) { err = -EINVAL; clunk_fid(s, fid); goto out; } err = fid_to_qid(pdu, fidp, &qid); if (err < 0) { err = -EINVAL; clunk_fid(s, fid); goto out; } err = pdu_marshal(pdu, offset, "Q", &qid); if (err < 0) { clunk_fid(s, fid); goto out; } err += offset; trace_v9fs_attach_return(pdu->tag, pdu->id, qid.type, qid.version, qid.path); /* * attach could get called multiple times for the same export. */ if (!s->migration_blocker) { s->root_fid = fid; error_setg(&s->migration_blocker, "Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'", s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag); migrate_add_blocker(s->migration_blocker); } out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&uname); v9fs_string_free(&aname); } Commit Message: CWE ID: CWE-22
static void v9fs_attach(void *opaque) { V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; int32_t fid, afid, n_uname; V9fsString uname, aname; V9fsFidState *fidp; size_t offset = 7; V9fsQID qid; ssize_t err; v9fs_string_init(&uname); v9fs_string_init(&aname); err = pdu_unmarshal(pdu, offset, "ddssd", &fid, &afid, &uname, &aname, &n_uname); if (err < 0) { goto out_nofid; } trace_v9fs_attach(pdu->tag, pdu->id, fid, afid, uname.data, aname.data); fidp = alloc_fid(s, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } fidp->uid = n_uname; err = v9fs_co_name_to_path(pdu, NULL, "/", &fidp->path); if (err < 0) { err = -EINVAL; clunk_fid(s, fid); goto out; } err = fid_to_qid(pdu, fidp, &qid); if (err < 0) { err = -EINVAL; clunk_fid(s, fid); goto out; } err = pdu_marshal(pdu, offset, "Q", &qid); if (err < 0) { clunk_fid(s, fid); goto out; } err += offset; memcpy(&s->root_qid, &qid, sizeof(qid)); trace_v9fs_attach_return(pdu->tag, pdu->id, qid.type, qid.version, qid.path); /* * attach could get called multiple times for the same export. */ if (!s->migration_blocker) { s->root_fid = fid; error_setg(&s->migration_blocker, "Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'", s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag); migrate_add_blocker(s->migration_blocker); } out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&uname); v9fs_string_free(&aname); }
164,938
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: walk_string(fz_context *ctx, int uni, int remove, editable_str *str) { int rune; if (str->utf8 == NULL) return; do { char *s = &str->utf8[str->pos]; size_t len; int n = fz_chartorune(&rune, s); if (rune == uni) { /* Match. Skip over that one. */ str->pos += n; } else if (uni == 32) { /* We don't care if we're given whitespace * and it doesn't match the string. Don't * skip forward. Nothing to remove. */ break; } else if (rune == 32) { /* The string has a whitespace, and we * don't match it; that's forgivable as * PDF often misses out spaces. Remove this * if we are removing stuff. */ } else { /* Mismatch. No point in tracking through any more. */ str->pos = -1; break; } if (remove) { len = strlen(s+n); memmove(s, s+n, len+1); str->edited = 1; } } while (rune != uni); } Commit Message: CWE ID: CWE-125
walk_string(fz_context *ctx, int uni, int remove, editable_str *str) { int rune; if (str->utf8 == NULL || str->pos == -1) return; do { char *s = &str->utf8[str->pos]; size_t len; int n = fz_chartorune(&rune, s); if (rune == uni) { /* Match. Skip over that one. */ str->pos += n; } else if (uni == 32) { /* We don't care if we're given whitespace * and it doesn't match the string. Don't * skip forward. Nothing to remove. */ break; } else if (rune == 32) { /* The string has a whitespace, and we * don't match it; that's forgivable as * PDF often misses out spaces. Remove this * if we are removing stuff. */ } else { /* Mismatch. No point in tracking through any more. */ str->pos = -1; break; } if (remove) { len = strlen(s+n); memmove(s, s+n, len+1); str->edited = 1; } } while (rune != uni); }
164,660
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(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); }
167,041
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: cid_parse_font_matrix( CID_Face face, CID_Parser* parser ) { CID_FaceDict dict; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts ) { FT_Matrix* matrix; FT_Vector* offset; dict = face->cid.font_dicts + parser->num_dict; matrix = &dict->font_matrix; offset = &dict->font_offset; (void)cid_parser_to_fixed_array( parser, 6, temp, 3 ); temp_scale = FT_ABS( temp[3] ); /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = 0x10000L; } Commit Message: CWE ID: CWE-20
cid_parse_font_matrix( CID_Face face, CID_Parser* parser ) { CID_FaceDict dict; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts ) { FT_Matrix* matrix; FT_Vector* offset; FT_Int result; dict = face->cid.font_dicts + parser->num_dict; matrix = &dict->font_matrix; offset = &dict->font_offset; result = cid_parser_to_fixed_array( parser, 6, temp, 3 ); if ( result < 6 ) return FT_THROW( Invalid_File_Format ); temp_scale = FT_ABS( temp[3] ); if ( temp_scale == 0 ) { FT_ERROR(( "cid_parse_font_matrix: invalid font matrix\n" )); return FT_THROW( Invalid_File_Format ); } /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L; }
165,341
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 PrintPreviewMessageHandler::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { int page_number = params.page_number; if (page_number < FIRST_PAGE_INDEX || !params.data_size) return; PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; scoped_refptr<base::RefCountedBytes> data_bytes = GetDataFromHandle(params.metafile_data_handle, params.data_size); DCHECK(data_bytes); print_preview_ui->SetPrintPreviewDataForIndex(page_number, std::move(data_bytes)); print_preview_ui->OnDidPreviewPage(page_number, params.preview_request_id); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. TBR=jzfeng@chromium.org BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <weili@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
void PrintPreviewMessageHandler::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { int page_number = params.page_number; if (page_number < FIRST_PAGE_INDEX || !params.data_size) return; PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; if (IsOopifEnabled() && print_preview_ui->source_is_modifiable()) { auto* client = PrintCompositeClient::FromWebContents(web_contents()); DCHECK(client); // Use utility process to convert skia metafile to pdf. client->DoComposite( params.metafile_data_handle, params.data_size, base::BindOnce(&PrintPreviewMessageHandler::OnCompositePdfPageDone, weak_ptr_factory_.GetWeakPtr(), params.page_number, params.preview_request_id)); } else { NotifyUIPreviewPageReady( page_number, params.preview_request_id, GetDataFromHandle(params.metafile_data_handle, params.data_size)); } }
171,888
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 SoftMPEG4Encoder::initEncParams() { CHECK(mHandle != NULL); memset(mHandle, 0, sizeof(tagvideoEncControls)); CHECK(mEncParams != NULL); memset(mEncParams, 0, sizeof(tagvideoEncOptions)); if (!PVGetDefaultEncOption(mEncParams, 0)) { ALOGE("Failed to get default encoding parameters"); return OMX_ErrorUndefined; } mEncParams->encMode = mEncodeMode; mEncParams->encWidth[0] = mWidth; mEncParams->encHeight[0] = mHeight; mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format mEncParams->rcType = VBR_1; mEncParams->vbvDelay = 5.0f; mEncParams->profile_level = CORE_PROFILE_LEVEL2; mEncParams->packetSize = 32; mEncParams->rvlcEnable = PV_OFF; mEncParams->numLayers = 1; mEncParams->timeIncRes = 1000; mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate; mEncParams->bitRate[0] = mBitrate; mEncParams->iQuant[0] = 15; mEncParams->pQuant[0] = 12; mEncParams->quantType[0] = 0; mEncParams->noFrameSkipped = PV_OFF; if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) { free(mInputFrameData); mInputFrameData = (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1); CHECK(mInputFrameData != NULL); } if (mWidth % 16 != 0 || mHeight % 16 != 0) { ALOGE("Video frame size %dx%d must be a multiple of 16", mWidth, mHeight); return OMX_ErrorBadParameter; } if (mIDRFrameRefreshIntervalInSec < 0) { mEncParams->intraPeriod = -1; } else if (mIDRFrameRefreshIntervalInSec == 0) { mEncParams->intraPeriod = 1; // All I frames } else { mEncParams->intraPeriod = (mIDRFrameRefreshIntervalInSec * mFramerate) >> 16; } mEncParams->numIntraMB = 0; mEncParams->sceneDetect = PV_ON; mEncParams->searchRange = 16; mEncParams->mv8x8Enable = PV_OFF; mEncParams->gobHeaderInterval = 0; mEncParams->useACPred = PV_ON; mEncParams->intraDCVlcTh = 0; return OMX_ErrorNone; } Commit Message: DO NOT MERGE - libstagefright: check requested memory size before allocation for SoftMPEG4Encoder and SoftVPXEncoder. Bug: 25812794 Change-Id: I96dc74734380d462583f6efa33d09946f9532809 (cherry picked from commit 87f8cbb223ee516803dbb99699320c2484cbf3ba) (cherry picked from commit 0462975291796e414891e04bcec9da993914e458) CWE ID: CWE-119
OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() { CHECK(mHandle != NULL); memset(mHandle, 0, sizeof(tagvideoEncControls)); CHECK(mEncParams != NULL); memset(mEncParams, 0, sizeof(tagvideoEncOptions)); if (!PVGetDefaultEncOption(mEncParams, 0)) { ALOGE("Failed to get default encoding parameters"); return OMX_ErrorUndefined; } mEncParams->encMode = mEncodeMode; mEncParams->encWidth[0] = mWidth; mEncParams->encHeight[0] = mHeight; mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format mEncParams->rcType = VBR_1; mEncParams->vbvDelay = 5.0f; mEncParams->profile_level = CORE_PROFILE_LEVEL2; mEncParams->packetSize = 32; mEncParams->rvlcEnable = PV_OFF; mEncParams->numLayers = 1; mEncParams->timeIncRes = 1000; mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate; mEncParams->bitRate[0] = mBitrate; mEncParams->iQuant[0] = 15; mEncParams->pQuant[0] = 12; mEncParams->quantType[0] = 0; mEncParams->noFrameSkipped = PV_OFF; if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) { free(mInputFrameData); mInputFrameData = NULL; if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) { ALOGE("b/25812794, Buffer size is too big."); return OMX_ErrorBadParameter; } mInputFrameData = (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1); CHECK(mInputFrameData != NULL); } if (mWidth % 16 != 0 || mHeight % 16 != 0) { ALOGE("Video frame size %dx%d must be a multiple of 16", mWidth, mHeight); return OMX_ErrorBadParameter; } if (mIDRFrameRefreshIntervalInSec < 0) { mEncParams->intraPeriod = -1; } else if (mIDRFrameRefreshIntervalInSec == 0) { mEncParams->intraPeriod = 1; // All I frames } else { mEncParams->intraPeriod = (mIDRFrameRefreshIntervalInSec * mFramerate) >> 16; } mEncParams->numIntraMB = 0; mEncParams->sceneDetect = PV_ON; mEncParams->searchRange = 16; mEncParams->mv8x8Enable = PV_OFF; mEncParams->gobHeaderInterval = 0; mEncParams->useACPred = PV_ON; mEncParams->intraDCVlcTh = 0; return OMX_ErrorNone; }
173,970
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 size_t GetNumActiveInputMethods() { scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); return input_methods->size(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual size_t GetNumActiveInputMethods() { scoped_ptr<input_method::InputMethodDescriptors> input_methods( GetActiveInputMethods()); return input_methods->size(); }
170,490
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: tbGetBuffer(unsigned size) { char *rtrn; if (size >= BUFFER_SIZE) return NULL; if ((BUFFER_SIZE - tbNext) <= size) tbNext = 0; rtrn = &textBuffer[tbNext]; tbNext += size; return rtrn; } Commit Message: CWE ID: CWE-119
tbGetBuffer(unsigned size) { struct textBuffer *tb; tb = &textBuffer[textBufferIndex]; textBufferIndex = (textBufferIndex + 1) % NUM_BUFFER; if (size > tb->size) { free(tb->buffer); tb->buffer = xnfalloc(size); tb->size = size; } return tb->buffer; }
164,692
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: ProcEstablishConnection(ClientPtr client) { const char *reason; char *auth_proto, *auth_string; xConnClientPrefix *prefix; REQUEST(xReq); prefix = (xConnClientPrefix *) ((char *) stuff + sz_xReq); auth_proto = (char *) prefix + sz_xConnClientPrefix; auth_string = auth_proto + pad_to_int32(prefix->nbytesAuthProto); if ((prefix->majorVersion != X_PROTOCOL) || (prefix->minorVersion != X_PROTOCOL_REVISION)) reason = "Protocol version mismatch"; else return (SendConnSetup(client, reason)); } Commit Message: CWE ID: CWE-20
ProcEstablishConnection(ClientPtr client) { const char *reason; char *auth_proto, *auth_string; xConnClientPrefix *prefix; REQUEST(xReq); prefix = (xConnClientPrefix *) ((char *) stuff + sz_xReq); auth_proto = (char *) prefix + sz_xConnClientPrefix; auth_string = auth_proto + pad_to_int32(prefix->nbytesAuthProto); if ((client->req_len << 2) != sz_xReq + sz_xConnClientPrefix + pad_to_int32(prefix->nbytesAuthProto) + pad_to_int32(prefix->nbytesAuthString)) reason = "Bad length"; else if ((prefix->majorVersion != X_PROTOCOL) || (prefix->minorVersion != X_PROTOCOL_REVISION)) reason = "Protocol version mismatch"; else return (SendConnSetup(client, reason)); }
165,448
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: ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, "Missing descriptor data\n"); return NULL; } if (!buflen) { dev_err(&intf->dev, "Zero length descriptor\n"); return NULL; } while (buflen > 0) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "Found union header\n"); return union_desc; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, "Missing CDC union descriptor\n"); return NULL; } Commit Message: Input: ims-psu - check if CDC union descriptor is sane Before trying to use CDC union descriptor, try to validate whether that it is sane by checking that intf->altsetting->extra is big enough and that descriptor bLength is not too big and not too small. Reported-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com> CWE ID: CWE-125
ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, "Missing descriptor data\n"); return NULL; } if (!buflen) { dev_err(&intf->dev, "Zero length descriptor\n"); return NULL; } while (buflen >= sizeof(*union_desc)) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bLength > buflen) { dev_err(&intf->dev, "Too large descriptor\n"); return NULL; } if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "Found union header\n"); if (union_desc->bLength >= sizeof(*union_desc)) return union_desc; dev_err(&intf->dev, "Union descriptor to short (%d vs %zd\n)", union_desc->bLength, sizeof(*union_desc)); return NULL; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, "Missing CDC union descriptor\n"); return NULL; }
167,672
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 pdo_stmt_init(TSRMLS_D) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "PDOStatement", pdo_dbstmt_functions); pdo_dbstmt_ce = zend_register_internal_class(&ce TSRMLS_CC); pdo_dbstmt_ce->get_iterator = pdo_stmt_iter_get; pdo_dbstmt_ce->create_object = pdo_dbstmt_new; zend_class_implements(pdo_dbstmt_ce TSRMLS_CC, 1, zend_ce_traversable); zend_declare_property_null(pdo_dbstmt_ce, "queryString", sizeof("queryString")-1, ZEND_ACC_PUBLIC TSRMLS_CC); memcpy(&pdo_dbstmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers)); pdo_dbstmt_object_handlers.write_property = dbstmt_prop_write; pdo_dbstmt_object_handlers.unset_property = dbstmt_prop_delete; pdo_dbstmt_object_handlers.get_method = dbstmt_method_get; pdo_dbstmt_object_handlers.compare_objects = dbstmt_compare; pdo_dbstmt_object_handlers.clone_obj = dbstmt_clone_obj; INIT_CLASS_ENTRY(ce, "PDORow", pdo_row_functions); pdo_row_ce = zend_register_internal_class(&ce TSRMLS_CC); pdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */ pdo_row_ce->create_object = pdo_row_new; pdo_row_ce->serialize = pdo_row_serialize; } Commit Message: Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle Proper soltion would be to call serialize/unserialize and deal with the result, but this requires more work that should be done by wddx maintainer (not me). CWE ID: CWE-476
void pdo_stmt_init(TSRMLS_D) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "PDOStatement", pdo_dbstmt_functions); pdo_dbstmt_ce = zend_register_internal_class(&ce TSRMLS_CC); pdo_dbstmt_ce->get_iterator = pdo_stmt_iter_get; pdo_dbstmt_ce->create_object = pdo_dbstmt_new; zend_class_implements(pdo_dbstmt_ce TSRMLS_CC, 1, zend_ce_traversable); zend_declare_property_null(pdo_dbstmt_ce, "queryString", sizeof("queryString")-1, ZEND_ACC_PUBLIC TSRMLS_CC); memcpy(&pdo_dbstmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers)); pdo_dbstmt_object_handlers.write_property = dbstmt_prop_write; pdo_dbstmt_object_handlers.unset_property = dbstmt_prop_delete; pdo_dbstmt_object_handlers.get_method = dbstmt_method_get; pdo_dbstmt_object_handlers.compare_objects = dbstmt_compare; pdo_dbstmt_object_handlers.clone_obj = dbstmt_clone_obj; INIT_CLASS_ENTRY(ce, "PDORow", pdo_row_functions); pdo_row_ce = zend_register_internal_class(&ce TSRMLS_CC); pdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */ pdo_row_ce->create_object = pdo_row_new; pdo_row_ce->serialize = pdo_row_serialize; pdo_row_ce->unserialize = zend_class_unserialize_deny; }
168,668
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 *load_device_tree(const char *filename_path, int *sizep) { int dt_size; int dt_file_load_size; int ret; void *fdt = NULL; *sizep = 0; dt_size = get_image_size(filename_path); if (dt_size < 0) { error_report("Unable to get size of device tree file '%s'", filename_path); goto fail; } /* Expand to 2x size to give enough room for manipulation. */ dt_size += 10000; dt_size *= 2; /* First allocate space in qemu for device tree */ fdt = g_malloc0(dt_size); dt_file_load_size = load_image(filename_path, fdt); if (dt_file_load_size < 0) { error_report("Unable to open device tree file '%s'", filename_path); goto fail; } ret = fdt_open_into(fdt, fdt, dt_size); if (ret) { error_report("Unable to copy device tree in memory"); goto fail; } /* Check sanity of device tree */ if (fdt_check_header(fdt)) { error_report("Device tree file loaded into memory is invalid: %s", filename_path); goto fail; } *sizep = dt_size; return fdt; fail: g_free(fdt); return NULL; } Commit Message: CWE ID: CWE-119
void *load_device_tree(const char *filename_path, int *sizep) { int dt_size; int dt_file_load_size; int ret; void *fdt = NULL; *sizep = 0; dt_size = get_image_size(filename_path); if (dt_size < 0) { error_report("Unable to get size of device tree file '%s'", filename_path); goto fail; } /* Expand to 2x size to give enough room for manipulation. */ dt_size += 10000; dt_size *= 2; /* First allocate space in qemu for device tree */ fdt = g_malloc0(dt_size); dt_file_load_size = load_image_size(filename_path, fdt, dt_size); if (dt_file_load_size < 0) { error_report("Unable to open device tree file '%s'", filename_path); goto fail; } ret = fdt_open_into(fdt, fdt, dt_size); if (ret) { error_report("Unable to copy device tree in memory"); goto fail; } /* Check sanity of device tree */ if (fdt_check_header(fdt)) { error_report("Device tree file loaded into memory is invalid: %s", filename_path); goto fail; } *sizep = dt_size; return fdt; fail: g_free(fdt); return NULL; }
165,222
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::buffer_id OMXNodeInstance::findBufferID(OMX_BUFFERHEADERTYPE *bufferHeader) { return (OMX::buffer_id)bufferHeader; } Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32 Bug: 20634516 Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c (cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4) CWE ID: CWE-119
OMX::buffer_id OMXNodeInstance::findBufferID(OMX_BUFFERHEADERTYPE *bufferHeader) {
173,358
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: transform_range_check(png_const_structp pp, unsigned int r, unsigned int g, unsigned int b, unsigned int a, unsigned int in_digitized, double in, unsigned int out, png_byte sample_depth, double err, double limit, PNG_CONST char *name, double digitization_error) { /* Compare the scaled, digitzed, values of our local calculation (in+-err) * with the digitized values libpng produced; 'sample_depth' is the actual * digitization depth of the libpng output colors (the bit depth except for * palette images where it is always 8.) The check on 'err' is to detect * internal errors in pngvalid itself. */ unsigned int max = (1U<<sample_depth)-1; double in_min = ceil((in-err)*max - digitization_error); double in_max = floor((in+err)*max + digitization_error); if (err > limit || !(out >= in_min && out <= in_max)) { char message[256]; size_t pos; pos = safecat(message, sizeof message, 0, name); pos = safecat(message, sizeof message, pos, " output value error: rgba("); pos = safecatn(message, sizeof message, pos, r); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, g); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, b); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, a); pos = safecat(message, sizeof message, pos, "): "); pos = safecatn(message, sizeof message, pos, out); pos = safecat(message, sizeof message, pos, " expected: "); pos = safecatn(message, sizeof message, pos, in_digitized); pos = safecat(message, sizeof message, pos, " ("); pos = safecatd(message, sizeof message, pos, (in-err)*max, 3); pos = safecat(message, sizeof message, pos, ".."); pos = safecatd(message, sizeof message, pos, (in+err)*max, 3); pos = safecat(message, sizeof message, pos, ")"); png_error(pp, message); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
transform_range_check(png_const_structp pp, unsigned int r, unsigned int g, unsigned int b, unsigned int a, unsigned int in_digitized, double in, unsigned int out, png_byte sample_depth, double err, double limit, const char *name, double digitization_error) { /* Compare the scaled, digitzed, values of our local calculation (in+-err) * with the digitized values libpng produced; 'sample_depth' is the actual * digitization depth of the libpng output colors (the bit depth except for * palette images where it is always 8.) The check on 'err' is to detect * internal errors in pngvalid itself. */ unsigned int max = (1U<<sample_depth)-1; double in_min = ceil((in-err)*max - digitization_error); double in_max = floor((in+err)*max + digitization_error); if (err > limit || !(out >= in_min && out <= in_max)) { char message[256]; size_t pos; pos = safecat(message, sizeof message, 0, name); pos = safecat(message, sizeof message, pos, " output value error: rgba("); pos = safecatn(message, sizeof message, pos, r); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, g); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, b); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, a); pos = safecat(message, sizeof message, pos, "): "); pos = safecatn(message, sizeof message, pos, out); pos = safecat(message, sizeof message, pos, " expected: "); pos = safecatn(message, sizeof message, pos, in_digitized); pos = safecat(message, sizeof message, pos, " ("); pos = safecatd(message, sizeof message, pos, (in-err)*max, 3); pos = safecat(message, sizeof message, pos, ".."); pos = safecatd(message, sizeof message, pos, (in+err)*max, 3); pos = safecat(message, sizeof message, pos, ")"); png_error(pp, message); } }
173,716
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 CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH); Com_sprintf(dllName, sizeof(dllName), "renderer_sp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_sp_opengl1_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; ri.Z_Malloc = Z_Malloc; ri.Free = Z_Free; ri.Hunk_Clear = Hunk_ClearToMark; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); if ( !ret ) { Com_Error( ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; Com_Printf( "---- Renderer Initialization Complete ----\n" ); Cvar_Set( "cl_paused", "0" ); } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
void CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED); Com_sprintf(dllName, sizeof(dllName), "renderer_sp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_sp_opengl1_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; ri.Z_Malloc = Z_Malloc; ri.Free = Z_Free; ri.Hunk_Clear = Hunk_ClearToMark; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); if ( !ret ) { Com_Error( ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; Com_Printf( "---- Renderer Initialization Complete ----\n" ); Cvar_Set( "cl_paused", "0" ); }
170,086
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::GetDialogSize(gfx::Size* size) const { size->SetSize(width_, height_); } 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::GetDialogSize(gfx::Size* size) const { bool LoginHtmlDialog::ShouldShowDialogTitle() const { return true; } 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(); }
170,615
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 UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT status; UINT32 Length; UINT32 ChannelId; ChannelId = drdynvc_read_variable_uint(s, cbChId); Length = drdynvc_read_variable_uint(s, Sp); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp, cbChId, ChannelId, Length); status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId, Length); if (status) return status; return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s); } Commit Message: Fix for #4866: Added additional length checks CWE ID:
static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT status; UINT32 Length; UINT32 ChannelId; if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId) + drdynvc_cblen_to_bytes(Sp)) return ERROR_INVALID_DATA; ChannelId = drdynvc_read_variable_uint(s, cbChId); Length = drdynvc_read_variable_uint(s, Sp); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp, cbChId, ChannelId, Length); status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId, Length); if (status) return status; return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s); }
168,938
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 PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // ENABLE_BASIC_PRINTING IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { // The class is not designed to handle recursive messages. This is not // expected during regular flow. However, during rendering of content for // printing, lower level code may run nested message loop. E.g. PDF may has // script to show message box http://crbug.com/502562. In that moment browser // may receive updated printer capabilities and decide to restart print // preview generation. When this happened message handling function may // choose to ignore message or safely crash process. ++ipc_nesting_level_; bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // ENABLE_BASIC_PRINTING IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() --ipc_nesting_level_; return handled; }
171,872
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 mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client->net, client, NULL); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->server->flags & F_COPYONWRITE) { if (client->difmap) g_free(client->difmap) ; close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE + sizeof(struct nbd_reply)) err("Request too big!"); #ifdef DODBG printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply, EINVAL); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { DEBUG("[RANGE!]"); ERROR(client, reply, EINVAL); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_READONLY) || (client->server->flags & F_AUTOREADONLY)) { DEBUG("[WRITE to READONLY!]"); ERROR(client, reply, EPERM); continue; } if (expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply, errno); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply, errno); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; } Commit Message: Fix buffer size checking Yes, this means we've re-introduced CVE-2005-3534. Sigh. CWE ID: CWE-119
int mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client->net, client, NULL); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->server->flags & F_COPYONWRITE) { if (client->difmap) g_free(client->difmap) ; close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE - sizeof(struct nbd_reply)) err("Request too big!"); #ifdef DODBG printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply, EINVAL); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { DEBUG("[RANGE!]"); ERROR(client, reply, EINVAL); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_READONLY) || (client->server->flags & F_AUTOREADONLY)) { DEBUG("[WRITE to READONLY!]"); ERROR(client, reply, EPERM); continue; } if (expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply, errno); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply, errno); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; }
165,527
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: PHP_FUNCTION(xml_parser_create) { php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } Commit Message: CWE ID: CWE-119
PHP_FUNCTION(xml_parser_create) { php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); }
165,035
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 gdAlphaBlend (int dst, int src) { int src_alpha = gdTrueColorGetAlpha(src); int dst_alpha, alpha, red, green, blue; int src_weight, dst_weight, tot_weight; /* -------------------------------------------------------------------- */ /* Simple cases we want to handle fast. */ /* -------------------------------------------------------------------- */ if( src_alpha == gdAlphaOpaque ) return src; dst_alpha = gdTrueColorGetAlpha(dst); if( src_alpha == gdAlphaTransparent ) return dst; if( dst_alpha == gdAlphaTransparent ) return src; /* -------------------------------------------------------------------- */ /* What will the source and destination alphas be? Note that */ /* the destination weighting is substantially reduced as the */ /* overlay becomes quite opaque. */ /* -------------------------------------------------------------------- */ src_weight = gdAlphaTransparent - src_alpha; dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax; tot_weight = src_weight + dst_weight; /* -------------------------------------------------------------------- */ /* What red, green and blue result values will we use? */ /* -------------------------------------------------------------------- */ alpha = src_alpha * dst_alpha / gdAlphaMax; red = (gdTrueColorGetRed(src) * src_weight + gdTrueColorGetRed(dst) * dst_weight) / tot_weight; green = (gdTrueColorGetGreen(src) * src_weight + gdTrueColorGetGreen(dst) * dst_weight) / tot_weight; blue = (gdTrueColorGetBlue(src) * src_weight + gdTrueColorGetBlue(dst) * dst_weight) / tot_weight; /* -------------------------------------------------------------------- */ /* Return merged result. */ /* -------------------------------------------------------------------- */ return ((alpha << 24) + (red << 16) + (green << 8) + blue); } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
int gdAlphaBlend (int dst, int src) { int src_alpha = gdTrueColorGetAlpha(src); int dst_alpha, alpha, red, green, blue; int src_weight, dst_weight, tot_weight; /* -------------------------------------------------------------------- */ /* Simple cases we want to handle fast. */ /* -------------------------------------------------------------------- */ if( src_alpha == gdAlphaOpaque ) return src; dst_alpha = gdTrueColorGetAlpha(dst); if( src_alpha == gdAlphaTransparent ) return dst; if( dst_alpha == gdAlphaTransparent ) return src; /* -------------------------------------------------------------------- */ /* What will the source and destination alphas be? Note that */ /* the destination weighting is substantially reduced as the */ /* overlay becomes quite opaque. */ /* -------------------------------------------------------------------- */ src_weight = gdAlphaTransparent - src_alpha; dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax; tot_weight = src_weight + dst_weight; /* -------------------------------------------------------------------- */ /* What red, green and blue result values will we use? */ /* -------------------------------------------------------------------- */ alpha = src_alpha * dst_alpha / gdAlphaMax; red = (gdTrueColorGetRed(src) * src_weight + gdTrueColorGetRed(dst) * dst_weight) / tot_weight; green = (gdTrueColorGetGreen(src) * src_weight + gdTrueColorGetGreen(dst) * dst_weight) / tot_weight; blue = (gdTrueColorGetBlue(src) * src_weight + gdTrueColorGetBlue(dst) * dst_weight) / tot_weight; /* -------------------------------------------------------------------- */ /* Return merged result. */ /* -------------------------------------------------------------------- */ return ((alpha << 24) + (red << 16) + (green << 8) + blue); }
167,124
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 PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1); } 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 PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(id_, -1); }
170,836
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 WebSocketJob::OnSentData(SocketStream* socket, int amount_sent) { DCHECK_NE(INITIALIZED, state_); if (state_ == CLOSED) return; if (state_ == CONNECTING) { OnSentHandshakeRequest(socket, amount_sent); return; } if (delegate_) { DCHECK(state_ == OPEN || state_ == CLOSING); DCHECK_GT(amount_sent, 0); DCHECK(current_buffer_); current_buffer_->DidConsume(amount_sent); if (current_buffer_->BytesRemaining() > 0) return; amount_sent = send_frame_handler_->GetOriginalBufferSize(); DCHECK_GT(amount_sent, 0); current_buffer_ = NULL; send_frame_handler_->ReleaseCurrentBuffer(); delegate_->OnSentData(socket, amount_sent); MessageLoopForIO::current()->PostTask( FROM_HERE, NewRunnableMethod(this, &WebSocketJob::SendPending)); } } Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob Don't post SendPending if it is already posted. BUG=89795 TEST=none Review URL: http://codereview.chromium.org/7488007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void WebSocketJob::OnSentData(SocketStream* socket, int amount_sent) { DCHECK_NE(INITIALIZED, state_); if (state_ == CLOSED) return; if (state_ == CONNECTING) { OnSentHandshakeRequest(socket, amount_sent); return; } if (delegate_) { DCHECK(state_ == OPEN || state_ == CLOSING); DCHECK_GT(amount_sent, 0); DCHECK(current_buffer_); current_buffer_->DidConsume(amount_sent); if (current_buffer_->BytesRemaining() > 0) return; amount_sent = send_frame_handler_->GetOriginalBufferSize(); DCHECK_GT(amount_sent, 0); current_buffer_ = NULL; send_frame_handler_->ReleaseCurrentBuffer(); if (method_factory_.empty()) { MessageLoopForIO::current()->PostTask( FROM_HERE, method_factory_.NewRunnableMethod(&WebSocketJob::SendPending)); } delegate_->OnSentData(socket, amount_sent); } }
170,305
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: explicit SyncInternal(const std::string& name) : name_(name), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), enable_sync_tabs_for_other_clients_(false), registrar_(NULL), change_delegate_(NULL), initialized_(false), testing_mode_(NON_TEST), observing_ip_address_changes_(false), traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord), encryptor_(NULL), unrecoverable_error_handler_(NULL), report_unrecoverable_error_function_(NULL), created_on_loop_(MessageLoop::current()), nigori_overwrite_count_(0) { for (int i = syncable::FIRST_REAL_MODEL_TYPE; i < syncable::MODEL_TYPE_COUNT; ++i) { notification_info_map_.insert( std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo())); } BindJsMessageHandler( "getNotificationState", &SyncManager::SyncInternal::GetNotificationState); BindJsMessageHandler( "getNotificationInfo", &SyncManager::SyncInternal::GetNotificationInfo); BindJsMessageHandler( "getRootNodeDetails", &SyncManager::SyncInternal::GetRootNodeDetails); BindJsMessageHandler( "getNodeSummariesById", &SyncManager::SyncInternal::GetNodeSummariesById); BindJsMessageHandler( "getNodeDetailsById", &SyncManager::SyncInternal::GetNodeDetailsById); BindJsMessageHandler( "getAllNodes", &SyncManager::SyncInternal::GetAllNodes); BindJsMessageHandler( "getChildNodeIds", &SyncManager::SyncInternal::GetChildNodeIds); BindJsMessageHandler( "getClientServerTraffic", &SyncManager::SyncInternal::GetClientServerTraffic); } 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
explicit SyncInternal(const std::string& name) : name_(name), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), registrar_(NULL), change_delegate_(NULL), initialized_(false), testing_mode_(NON_TEST), observing_ip_address_changes_(false), traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord), encryptor_(NULL), unrecoverable_error_handler_(NULL), report_unrecoverable_error_function_(NULL), created_on_loop_(MessageLoop::current()), nigori_overwrite_count_(0) { for (int i = syncable::FIRST_REAL_MODEL_TYPE; i < syncable::MODEL_TYPE_COUNT; ++i) { notification_info_map_.insert( std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo())); } BindJsMessageHandler( "getNotificationState", &SyncManager::SyncInternal::GetNotificationState); BindJsMessageHandler( "getNotificationInfo", &SyncManager::SyncInternal::GetNotificationInfo); BindJsMessageHandler( "getRootNodeDetails", &SyncManager::SyncInternal::GetRootNodeDetails); BindJsMessageHandler( "getNodeSummariesById", &SyncManager::SyncInternal::GetNodeSummariesById); BindJsMessageHandler( "getNodeDetailsById", &SyncManager::SyncInternal::GetNodeDetailsById); BindJsMessageHandler( "getAllNodes", &SyncManager::SyncInternal::GetAllNodes); BindJsMessageHandler( "getChildNodeIds", &SyncManager::SyncInternal::GetChildNodeIds); BindJsMessageHandler( "getClientServerTraffic", &SyncManager::SyncInternal::GetClientServerTraffic); }
170,797
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 BlockGroup::Parse() { const long status = m_block.Parse(m_pCluster); if (status) return status; m_block.SetKey((m_prev > 0) && (m_next <= 0)); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long BlockGroup::Parse()
174,411
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 UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { int value; UINT error; UINT32 ChannelId; wStream* data_out; ChannelId = drdynvc_read_variable_uint(s, cbChId); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp, cbChId, ChannelId); if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId))) { WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error); return error; } data_out = Stream_New(NULL, 4); if (!data_out) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03); Stream_Write_UINT8(data_out, value); drdynvc_write_variable_uint(data_out, ChannelId); error = drdynvc_send(drdynvc, data_out); if (error) WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]", WTSErrorToString(error), error); return error; } Commit Message: Fix for #4866: Added additional length checks CWE ID:
static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { int value; UINT error; UINT32 ChannelId; wStream* data_out; if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId)) return ERROR_INVALID_DATA; ChannelId = drdynvc_read_variable_uint(s, cbChId); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp, cbChId, ChannelId); if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId))) { WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error); return error; } data_out = Stream_New(NULL, 4); if (!data_out) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03); Stream_Write_UINT8(data_out, value); drdynvc_write_variable_uint(data_out, ChannelId); error = drdynvc_send(drdynvc, data_out); if (error) WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]", WTSErrorToString(error), error); return error; }
168,935
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 DataReductionProxySettings::IsDataReductionProxyEnabled() const { if (base::FeatureList::IsEnabled(network::features::kNetworkService) && !params::IsEnabledWithNetworkService()) { return false; } return IsDataSaverEnabledByUser(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
bool DataReductionProxySettings::IsDataReductionProxyEnabled() const { if (base::FeatureList::IsEnabled(network::features::kNetworkService) && !params::IsEnabledWithNetworkService()) { return false; } return IsDataSaverEnabledByUser(GetOriginalProfilePrefs()); }
172,554
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: cherokee_validator_ldap_check (cherokee_validator_ldap_t *ldap, cherokee_connection_t *conn) { int re; ret_t ret; size_t size; char *dn; LDAPMessage *message; LDAPMessage *first; char *attrs[] = { LDAP_NO_ATTRS, NULL }; cherokee_validator_ldap_props_t *props = VAL_LDAP_PROP(ldap); /* Sanity checks */ if ((conn->validator == NULL) || cherokee_buffer_is_empty (&conn->validator->user)) return ret_error; size = cherokee_buffer_cnt_cspn (&conn->validator->user, 0, "*()"); if (size != conn->validator->user.len) return ret_error; /* Build filter */ ret = init_filter (ldap, props, conn); if (ret != ret_ok) return ret; /* Search */ re = ldap_search_s (ldap->conn, props->basedn.buf, LDAP_SCOPE_SUBTREE, ldap->filter.buf, attrs, 0, &message); if (re != LDAP_SUCCESS) { LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_SEARCH, props->filter.buf ? props->filter.buf : ""); return ret_error; } TRACE (ENTRIES, "subtree search (%s): done\n", ldap->filter.buf ? ldap->filter.buf : ""); /* Check that there a single entry */ re = ldap_count_entries (ldap->conn, message); if (re != 1) { ldap_msgfree (message); return ret_not_found; } /* Pick up the first one */ first = ldap_first_entry (ldap->conn, message); if (first == NULL) { ldap_msgfree (message); return ret_not_found; } /* Get DN */ dn = ldap_get_dn (ldap->conn, first); if (dn == NULL) { ldap_msgfree (message); return ret_error; } ldap_msgfree (message); /* Check that it's right */ ret = validate_dn (props, dn, conn->validator->passwd.buf); if (ret != ret_ok) return ret; /* Disconnect from the LDAP server */ re = ldap_unbind_s (ldap->conn); if (re != LDAP_SUCCESS) return ret_error; /* Validated! */ TRACE (ENTRIES, "Access to use %s has been granted\n", conn->validator->user.buf); return ret_ok; } Commit Message: Prevent the LDAP validator from accepting an empty password. CWE ID: CWE-287
cherokee_validator_ldap_check (cherokee_validator_ldap_t *ldap, cherokee_connection_t *conn) { int re; ret_t ret; size_t size; char *dn; LDAPMessage *message; LDAPMessage *first; char *attrs[] = { LDAP_NO_ATTRS, NULL }; cherokee_validator_ldap_props_t *props = VAL_LDAP_PROP(ldap); /* Sanity checks */ if ((conn->validator == NULL) || cherokee_buffer_is_empty (&conn->validator->user) || cherokee_buffer_is_empty (&conn->validator->passwd)) return ret_error; size = cherokee_buffer_cnt_cspn (&conn->validator->user, 0, "*()"); if (size != conn->validator->user.len) return ret_error; /* Build filter */ ret = init_filter (ldap, props, conn); if (ret != ret_ok) return ret; /* Search */ re = ldap_search_s (ldap->conn, props->basedn.buf, LDAP_SCOPE_SUBTREE, ldap->filter.buf, attrs, 0, &message); if (re != LDAP_SUCCESS) { LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_SEARCH, props->filter.buf ? props->filter.buf : ""); return ret_error; } TRACE (ENTRIES, "subtree search (%s): done\n", ldap->filter.buf ? ldap->filter.buf : ""); /* Check that there a single entry */ re = ldap_count_entries (ldap->conn, message); if (re != 1) { ldap_msgfree (message); return ret_not_found; } /* Pick up the first one */ first = ldap_first_entry (ldap->conn, message); if (first == NULL) { ldap_msgfree (message); return ret_not_found; } /* Get DN */ dn = ldap_get_dn (ldap->conn, first); if (dn == NULL) { ldap_msgfree (message); return ret_error; } ldap_msgfree (message); /* Check that it's right */ ret = validate_dn (props, dn, conn->validator->passwd.buf); if (ret != ret_ok) return ret; /* Disconnect from the LDAP server */ re = ldap_unbind_s (ldap->conn); if (re != LDAP_SUCCESS) return ret_error; /* Validated! */ TRACE (ENTRIES, "Access to use %s has been granted\n", conn->validator->user.buf); return ret_ok; }
166,288
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 mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; uint32_t addr; mcf_fec_bd bd; int frame_size; int len; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; ptr = frame; ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (1) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } } Commit Message: CWE ID: CWE-399
static void mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; uint32_t addr; mcf_fec_bd bd; int frame_size; int len, descnt = 0; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; ptr = frame; ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (descnt++ < FEC_MAX_DESC) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } }
164,925
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: IPV6DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) goto end; if (IPV6_GET_PLEN(reassembled) != 19) goto end; /* 40 bytes in we should find 8 bytes of A. */ for (i = 40; i < 40 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 48; i < 48 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 56; i < 56 + 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
IPV6DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) goto end; if (IPV6_GET_PLEN(reassembled) != 19) goto end; /* 40 bytes in we should find 8 bytes of A. */ for (i = 40; i < 40 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 48; i < 48 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 56; i < 56 + 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,309
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: char *path_name(const struct name_path *path, const char *name) { const struct name_path *p; char *n, *m; int nlen = strlen(name); int len = nlen + 1; for (p = path; p; p = p->up) { if (p->elem_len) len += p->elem_len + 1; } n = xmalloc(len); m = n + len - (nlen + 1); strcpy(m, name); for (p = path; p; p = p->up) { if (p->elem_len) { m -= p->elem_len + 1; memcpy(m, p->elem, p->elem_len); m[p->elem_len] = '/'; } } return n; } Commit Message: prefer memcpy to strcpy When we already know the length of a string (e.g., because we just malloc'd to fit it), it's nicer to use memcpy than strcpy, as it makes it more obvious that we are not going to overflow the buffer (because the size we pass matches the size in the allocation). This also eliminates calls to strcpy, which make auditing the code base harder. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com> CWE ID: CWE-119
char *path_name(const struct name_path *path, const char *name) { const struct name_path *p; char *n, *m; int nlen = strlen(name); int len = nlen + 1; for (p = path; p; p = p->up) { if (p->elem_len) len += p->elem_len + 1; } n = xmalloc(len); m = n + len - (nlen + 1); memcpy(m, name, nlen + 1); for (p = path; p; p = p->up) { if (p->elem_len) { m -= p->elem_len + 1; memcpy(m, p->elem, p->elem_len); m[p->elem_len] = '/'; } } return n; }
167,429
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_pixel_setf(image_pixel *this, unsigned int max) { this->redf = this->red / (double)max; this->greenf = this->green / (double)max; this->bluef = this->blue / (double)max; this->alphaf = this->alpha / (double)max; if (this->red < max) this->rede = this->redf * DBL_EPSILON; else this->rede = 0; if (this->green < max) this->greene = this->greenf * DBL_EPSILON; else this->greene = 0; if (this->blue < max) this->bluee = this->bluef * DBL_EPSILON; else this->bluee = 0; if (this->alpha < max) this->alphae = this->alphaf * DBL_EPSILON; else this->alphae = 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_pixel_setf(image_pixel *this, unsigned int max) image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax, unsigned int bMax, unsigned int aMax) { this->redf = this->red / (double)rMax; this->greenf = this->green / (double)gMax; this->bluef = this->blue / (double)bMax; this->alphaf = this->alpha / (double)aMax; if (this->red < rMax) this->rede = this->redf * DBL_EPSILON; else this->rede = 0; if (this->green < gMax) this->greene = this->greenf * DBL_EPSILON; else this->greene = 0; if (this->blue < bMax) this->bluee = this->bluef * DBL_EPSILON; else this->bluee = 0; if (this->alpha < aMax) this->alphae = this->alphaf * DBL_EPSILON; else this->alphae = 0; }
173,618
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: SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() { return syslogs_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() {
170,631
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: BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; if (im == NULL) { return; } if (!gdImageTrueColor(im)) { gd_error("Paletter image not supported by webp"); return; } if (quality == -1) { quality = 80; } if (overflow2(gdImageSX(im), 4)) { return; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out); if (out_size == 0) { gd_error("gd-webp encoding failed"); goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); } Commit Message: Fix double-free in gdImageWebPtr() The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and the other WebP output functions to do the real work) does not return whether it succeeded or failed, so this is not checked in gdImageWebpPtr() and the function wrongly assumes everything is okay, which is not, in this case, because there is a size limitation for WebP, namely that the width and height must by less than 16383. We can't change the signature of gdImageWebpCtx() for API compatibility reasons, so we introduce the static helper _gdImageWebpCtx() which returns success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can check the return value. We leave it solely to libwebp for now to report warnings regarding the failing write. This issue had been reported by Ibrahim El-Sayed to security@libgd.org. CVE-2016-6912 CWE ID: CWE-415
BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) /* returns 0 on success, 1 on failure */ static int _gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; int ret = 0; if (im == NULL) { return 1; } if (!gdImageTrueColor(im)) { gd_error("Palette image not supported by webp"); return 1; } if (quality == -1) { quality = 80; } if (overflow2(gdImageSX(im), 4)) { return 1; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return 1; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return 1; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out); if (out_size == 0) { gd_error("gd-webp encoding failed"); ret = 1; goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); return ret; } /* Function: gdImageWebpCtx Write the image as WebP data via a <gdIOCtx>. See <gdImageWebpEx> for more details. Parameters: im - The image to write. outfile - The output sink. quality - Image quality. Returns: Nothing. */ BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { _gdImageWebpCtx(im, outfile, quality); }
168,817
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 SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused) { ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d", fd, offset, length, priority); Mutex::Autolock lock(&mLock); sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length); mSamples.add(sample->sampleID(), sample); doLoad(sample); return sample->sampleID(); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264
int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused) { ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d", fd, offset, length, priority);
173,962
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 LocalFileSystem::fileSystemAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, PassRefPtr<CallbackWrapper> callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::fileSystemAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, CallbackWrapper* callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); }
171,426
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: Strgrow(Str x) { char *old = x->ptr; int newlen; newlen = x->length * 6 / 5; if (newlen == x->length) newlen += 2; x->ptr = GC_MALLOC_ATOMIC(newlen); x->area_size = newlen; bcopy((void *)old, (void *)x->ptr, x->length); GC_free(old); } Commit Message: Merge pull request #27 from kcwu/fix-strgrow Fix potential heap buffer corruption due to Strgrow CWE ID: CWE-119
Strgrow(Str x) { char *old = x->ptr; int newlen; newlen = x->area_size * 6 / 5; if (newlen == x->area_size) newlen += 2; x->ptr = GC_MALLOC_ATOMIC(newlen); x->area_size = newlen; bcopy((void *)old, (void *)x->ptr, x->length); GC_free(old); }
166,892
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 Con_Dump_f( void ) { int l, x, i; short *line; fileHandle_t f; int bufferlen; char *buffer; char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "usage: condump <filename>\n" ); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); f = FS_FOpenFileWrite( filename ); if ( !f ) { Com_Printf ("ERROR: couldn't open %s.\n", filename); return; } Com_Printf ("Dumped console text to %s.\n", filename ); for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ ) { line = con.text + ( l % con.totallines ) * con.linewidth; for ( x = 0 ; x < con.linewidth ; x++ ) if ( ( line[x] & 0xff ) != ' ' ) { break; } if ( x != con.linewidth ) { break; } } #ifdef _WIN32 bufferlen = con.linewidth + 3 * sizeof ( char ); #else bufferlen = con.linewidth + 2 * sizeof ( char ); #endif buffer = Hunk_AllocateTempMemory( bufferlen ); buffer[bufferlen-1] = 0; for ( ; l <= con.current ; l++ ) { line = con.text + ( l % con.totallines ) * con.linewidth; for ( i = 0; i < con.linewidth; i++ ) buffer[i] = line[i] & 0xff; for ( x = con.linewidth - 1 ; x >= 0 ; x-- ) { if ( buffer[x] == ' ' ) { buffer[x] = 0; } else { break; } } #ifdef _WIN32 Q_strcat(buffer, bufferlen, "\r\n"); #else Q_strcat(buffer, bufferlen, "\n"); #endif FS_Write( buffer, strlen( buffer ), f ); } Hunk_FreeTempMemory( buffer ); FS_FCloseFile( f ); } Commit Message: All: Merge some file writing extension checks CWE ID: CWE-269
void Con_Dump_f( void ) { int l, x, i; short *line; fileHandle_t f; int bufferlen; char *buffer; char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "usage: condump <filename>\n" ); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); if (!COM_CompareExtension(filename, ".txt")) { Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n"); return; } f = FS_FOpenFileWrite( filename ); if ( !f ) { Com_Printf ("ERROR: couldn't open %s.\n", filename); return; } Com_Printf ("Dumped console text to %s.\n", filename ); for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ ) { line = con.text + ( l % con.totallines ) * con.linewidth; for ( x = 0 ; x < con.linewidth ; x++ ) if ( ( line[x] & 0xff ) != ' ' ) { break; } if ( x != con.linewidth ) { break; } } #ifdef _WIN32 bufferlen = con.linewidth + 3 * sizeof ( char ); #else bufferlen = con.linewidth + 2 * sizeof ( char ); #endif buffer = Hunk_AllocateTempMemory( bufferlen ); buffer[bufferlen-1] = 0; for ( ; l <= con.current ; l++ ) { line = con.text + ( l % con.totallines ) * con.linewidth; for ( i = 0; i < con.linewidth; i++ ) buffer[i] = line[i] & 0xff; for ( x = con.linewidth - 1 ; x >= 0 ; x-- ) { if ( buffer[x] == ' ' ) { buffer[x] = 0; } else { break; } } #ifdef _WIN32 Q_strcat(buffer, bufferlen, "\r\n"); #else Q_strcat(buffer, bufferlen, "\n"); #endif FS_Write( buffer, strlen( buffer ), f ); } Hunk_FreeTempMemory( buffer ); FS_FCloseFile( f ); }
170,079
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 ResourceDispatcherHostImpl::OnReadCompleted(net::URLRequest* request, int bytes_read) { DCHECK(request); VLOG(1) << "OnReadCompleted: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); if (bytes_read == -1) { DCHECK(!request->status().is_success()); ResponseCompleted(request); return; } info->set_has_started_reading(true); if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (request->status().is_success() && CompleteRead(request, &bytes_read)) { if (info->pause_count() == 0 && Read(request, &bytes_read) && request->status().is_success()) { if (bytes_read == 0) { CompleteRead(request, &bytes_read); } else { VLOG(1) << "OnReadCompleted postponing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; info->set_paused_read_bytes(bytes_read); info->set_is_paused(true); GlobalRequestID id(info->GetChildID(), info->GetRequestID()); MessageLoop::current()->PostTask( FROM_HERE, base::Bind( &ResourceDispatcherHostImpl::ResumeRequest, weak_factory_.GetWeakPtr(), id)); return; } } } if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted (CompleteRead) pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (!request->status().is_io_pending()) ResponseCompleted(request); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void ResourceDispatcherHostImpl::OnReadCompleted(net::URLRequest* request, int bytes_read) { DCHECK(request); VLOG(1) << "OnReadCompleted: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); if (bytes_read == -1) { DCHECK(!request->status().is_success()); ResponseCompleted(request); return; } info->set_has_started_reading(true); if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (request->status().is_success() && CompleteRead(request, &bytes_read)) { if (info->pause_count() == 0 && Read(request, &bytes_read) && request->status().is_success()) { if (bytes_read == 0) { CompleteRead(request, &bytes_read); } else { VLOG(1) << "OnReadCompleted postponing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; info->set_paused_read_bytes(bytes_read); info->set_is_paused(true); GlobalRequestID id(info->GetChildID(), info->GetRequestID()); MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceDispatcherHostImpl::ResumeRequest, AsWeakPtr(), id)); return; } } } if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted (CompleteRead) pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (!request->status().is_io_pending()) ResponseCompleted(request); }
170,988
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 DCTStream::init() { jpeg_std_error(&jerr); jerr.error_exit = &exitErrorHandler; src.pub.init_source = str_init_source; src.pub.fill_input_buffer = str_fill_input_buffer; src.pub.skip_input_data = str_skip_input_data; src.pub.resync_to_restart = jpeg_resync_to_restart; src.pub.term_source = str_term_source; src.pub.next_input_byte = NULL; src.str = str; src.index = 0; src.abort = false; current = NULL; limit = NULL; limit = NULL; cinfo.err = &jerr; jpeg_create_decompress(&cinfo); cinfo.src = (jpeg_source_mgr *)&src; row_buffer = NULL; } Commit Message: CWE ID: CWE-20
void DCTStream::init() { jpeg_std_error(&jerr); jerr.error_exit = &exitErrorHandler; src.pub.init_source = str_init_source; src.pub.fill_input_buffer = str_fill_input_buffer; src.pub.skip_input_data = str_skip_input_data; src.pub.resync_to_restart = jpeg_resync_to_restart; src.pub.term_source = str_term_source; src.pub.next_input_byte = NULL; src.str = str; src.index = 0; current = NULL; limit = NULL; limit = NULL; cinfo.err = &jerr; jpeg_create_decompress(&cinfo); cinfo.src = (jpeg_source_mgr *)&src; row_buffer = NULL; }
165,393
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 _xml_endElementHandler(void *userData, const XML_Char *name) { xml_parser *parser = (xml_parser *)userData; char *tag_name; if (parser) { zval *retval, *args[2]; tag_name = _xml_decode_tag(parser, name); if (parser->endElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); if ((retval = xml_call_handler(parser, parser->endElementHandler, parser->endElementPtr, 2, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { zval *tag; if (parser->lastwasopen) { add_assoc_string(*(parser->ctag),"type","complete",1); } else { MAKE_STD_ZVAL(tag); array_init(tag); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","close",1); add_assoc_long(tag,"level",parser->level); zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL); } parser->lastwasopen = 0; } efree(tag_name); if ((parser->ltags) && (parser->level <= XML_MAXLEVEL)) { efree(parser->ltags[parser->level-1]); } parser->level--; } } Commit Message: CWE ID: CWE-119
void _xml_endElementHandler(void *userData, const XML_Char *name) { xml_parser *parser = (xml_parser *)userData; char *tag_name; if (parser) { zval *retval, *args[2]; tag_name = _xml_decode_tag(parser, name); if (parser->endElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); if ((retval = xml_call_handler(parser, parser->endElementHandler, parser->endElementPtr, 2, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { zval *tag; if (parser->lastwasopen) { add_assoc_string(*(parser->ctag),"type","complete",1); } else { MAKE_STD_ZVAL(tag); array_init(tag); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","close",1); add_assoc_long(tag,"level",parser->level); zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL); } parser->lastwasopen = 0; } efree(tag_name); if ((parser->ltags) && (parser->level <= XML_MAXLEVEL)) { efree(parser->ltags[parser->level-1]); } parser->level--; } }
165,041
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_get_uint_16(png_bytep buf) { png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) + (png_uint_16)(*(buf + 1))); return (i); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_uint_16(png_bytep buf) { png_uint_16 i = ((png_uint_16)((*(buf )) & 0xff) << 8) + ((png_uint_16)((*(buf + 1)) & 0xff) ); return (i); }
172,174
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: X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) { X509_REQ *ret; X509_REQ_INFO *ri; int i; EVP_PKEY *pktmp; ret = X509_REQ_new(); if (ret == NULL) { X509err(X509_F_X509_TO_X509_REQ, ERR_R_MALLOC_FAILURE); goto err; } ri = ret->req_info; ri->version->length = 1; ri->version->data = (unsigned char *)OPENSSL_malloc(1); if (ri->version->data == NULL) goto err; ri->version->data[0] = 0; /* version == 0 */ if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x))) goto err; pktmp = X509_get_pubkey(x); i = X509_REQ_set_pubkey(ret, pktmp); EVP_PKEY_free(pktmp); if (!i) if (pkey != NULL) { if (!X509_REQ_sign(ret, pkey, md)) goto err; } return (ret); err: X509_REQ_free(ret); return (NULL); } Commit Message: CWE ID:
X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) { X509_REQ *ret; X509_REQ_INFO *ri; int i; EVP_PKEY *pktmp; ret = X509_REQ_new(); if (ret == NULL) { X509err(X509_F_X509_TO_X509_REQ, ERR_R_MALLOC_FAILURE); goto err; } ri = ret->req_info; ri->version->length = 1; ri->version->data = (unsigned char *)OPENSSL_malloc(1); if (ri->version->data == NULL) goto err; ri->version->data[0] = 0; /* version == 0 */ if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x))) goto err; pktmp = X509_get_pubkey(x); if (pktmp == NULL) goto err; i = X509_REQ_set_pubkey(ret, pktmp); EVP_PKEY_free(pktmp); if (!i) if (pkey != NULL) { if (!X509_REQ_sign(ret, pkey, md)) goto err; } return (ret); err: X509_REQ_free(ret); return (NULL); }
164,809
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 bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[4],b[0],c2,c3,c1); mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); mul_add_c(a[0],b[4],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[0],b[5],c3,c1,c2); mul_add_c(a[1],b[4],c3,c1,c2); mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); mul_add_c(a[4],b[1],c3,c1,c2); mul_add_c(a[5],b[0],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[6],b[0],c1,c2,c3); mul_add_c(a[5],b[1],c1,c2,c3); mul_add_c(a[4],b[2],c1,c2,c3); mul_add_c(a[3],b[3],c1,c2,c3); mul_add_c(a[2],b[4],c1,c2,c3); mul_add_c(a[1],b[5],c1,c2,c3); mul_add_c(a[0],b[6],c1,c2,c3); r[6]=c1; c1=0; mul_add_c(a[0],b[7],c2,c3,c1); mul_add_c(a[1],b[6],c2,c3,c1); mul_add_c(a[2],b[5],c2,c3,c1); mul_add_c(a[3],b[4],c2,c3,c1); mul_add_c(a[4],b[3],c2,c3,c1); mul_add_c(a[5],b[2],c2,c3,c1); mul_add_c(a[6],b[1],c2,c3,c1); mul_add_c(a[7],b[0],c2,c3,c1); r[7]=c2; c2=0; mul_add_c(a[7],b[1],c3,c1,c2); mul_add_c(a[6],b[2],c3,c1,c2); mul_add_c(a[5],b[3],c3,c1,c2); mul_add_c(a[4],b[4],c3,c1,c2); mul_add_c(a[3],b[5],c3,c1,c2); mul_add_c(a[2],b[6],c3,c1,c2); mul_add_c(a[1],b[7],c3,c1,c2); r[8]=c3; c3=0; mul_add_c(a[2],b[7],c1,c2,c3); mul_add_c(a[3],b[6],c1,c2,c3); mul_add_c(a[4],b[5],c1,c2,c3); mul_add_c(a[5],b[4],c1,c2,c3); mul_add_c(a[6],b[3],c1,c2,c3); mul_add_c(a[7],b[2],c1,c2,c3); r[9]=c1; c1=0; mul_add_c(a[7],b[3],c2,c3,c1); mul_add_c(a[6],b[4],c2,c3,c1); mul_add_c(a[5],b[5],c2,c3,c1); mul_add_c(a[4],b[6],c2,c3,c1); mul_add_c(a[3],b[7],c2,c3,c1); r[10]=c2; c2=0; mul_add_c(a[4],b[7],c3,c1,c2); mul_add_c(a[5],b[6],c3,c1,c2); mul_add_c(a[6],b[5],c3,c1,c2); mul_add_c(a[7],b[4],c3,c1,c2); r[11]=c3; c3=0; mul_add_c(a[7],b[5],c1,c2,c3); mul_add_c(a[6],b[6],c1,c2,c3); mul_add_c(a[5],b[7],c1,c2,c3); r[12]=c1; c1=0; mul_add_c(a[6],b[7],c2,c3,c1); mul_add_c(a[7],b[6],c2,c3,c1); r[13]=c2; c2=0; mul_add_c(a[7],b[7],c3,c1,c2); r[14]=c3; r[15]=c1; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <emilia@openssl.org> CWE ID: CWE-310
void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[4],b[0],c2,c3,c1); mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); mul_add_c(a[0],b[4],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[0],b[5],c3,c1,c2); mul_add_c(a[1],b[4],c3,c1,c2); mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); mul_add_c(a[4],b[1],c3,c1,c2); mul_add_c(a[5],b[0],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[6],b[0],c1,c2,c3); mul_add_c(a[5],b[1],c1,c2,c3); mul_add_c(a[4],b[2],c1,c2,c3); mul_add_c(a[3],b[3],c1,c2,c3); mul_add_c(a[2],b[4],c1,c2,c3); mul_add_c(a[1],b[5],c1,c2,c3); mul_add_c(a[0],b[6],c1,c2,c3); r[6]=c1; c1=0; mul_add_c(a[0],b[7],c2,c3,c1); mul_add_c(a[1],b[6],c2,c3,c1); mul_add_c(a[2],b[5],c2,c3,c1); mul_add_c(a[3],b[4],c2,c3,c1); mul_add_c(a[4],b[3],c2,c3,c1); mul_add_c(a[5],b[2],c2,c3,c1); mul_add_c(a[6],b[1],c2,c3,c1); mul_add_c(a[7],b[0],c2,c3,c1); r[7]=c2; c2=0; mul_add_c(a[7],b[1],c3,c1,c2); mul_add_c(a[6],b[2],c3,c1,c2); mul_add_c(a[5],b[3],c3,c1,c2); mul_add_c(a[4],b[4],c3,c1,c2); mul_add_c(a[3],b[5],c3,c1,c2); mul_add_c(a[2],b[6],c3,c1,c2); mul_add_c(a[1],b[7],c3,c1,c2); r[8]=c3; c3=0; mul_add_c(a[2],b[7],c1,c2,c3); mul_add_c(a[3],b[6],c1,c2,c3); mul_add_c(a[4],b[5],c1,c2,c3); mul_add_c(a[5],b[4],c1,c2,c3); mul_add_c(a[6],b[3],c1,c2,c3); mul_add_c(a[7],b[2],c1,c2,c3); r[9]=c1; c1=0; mul_add_c(a[7],b[3],c2,c3,c1); mul_add_c(a[6],b[4],c2,c3,c1); mul_add_c(a[5],b[5],c2,c3,c1); mul_add_c(a[4],b[6],c2,c3,c1); mul_add_c(a[3],b[7],c2,c3,c1); r[10]=c2; c2=0; mul_add_c(a[4],b[7],c3,c1,c2); mul_add_c(a[5],b[6],c3,c1,c2); mul_add_c(a[6],b[5],c3,c1,c2); mul_add_c(a[7],b[4],c3,c1,c2); r[11]=c3; c3=0; mul_add_c(a[7],b[5],c1,c2,c3); mul_add_c(a[6],b[6],c1,c2,c3); mul_add_c(a[5],b[7],c1,c2,c3); r[12]=c1; c1=0; mul_add_c(a[6],b[7],c2,c3,c1); mul_add_c(a[7],b[6],c2,c3,c1); r[13]=c2; c2=0; mul_add_c(a[7],b[7],c3,c1,c2); r[14]=c3; r[15]=c1; }
166,829
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: ext4_xattr_cache_insert(struct mb_cache *ext4_mb_cache, struct buffer_head *bh) { __u32 hash = le32_to_cpu(BHDR(bh)->h_hash); struct mb_cache_entry *ce; int error; ce = mb_cache_entry_alloc(ext4_mb_cache, GFP_NOFS); if (!ce) { ea_bdebug(bh, "out of memory"); return; } error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash); if (error) { mb_cache_entry_free(ce); if (error == -EBUSY) { ea_bdebug(bh, "already in cache"); error = 0; } } else { ea_bdebug(bh, "inserting [%x]", (int)hash); mb_cache_entry_release(ce); } } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
ext4_xattr_cache_insert(struct mb_cache *ext4_mb_cache, struct buffer_head *bh) ext4_xattr_cache_insert(struct mb2_cache *ext4_mb_cache, struct buffer_head *bh) { __u32 hash = le32_to_cpu(BHDR(bh)->h_hash); int error; error = mb2_cache_entry_create(ext4_mb_cache, GFP_NOFS, hash, bh->b_blocknr); if (error) { if (error == -EBUSY) ea_bdebug(bh, "already in cache"); } else ea_bdebug(bh, "inserting [%x]", (int)hash); }
169,992
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: ContentEncoding::ContentEncryption::ContentEncryption() : algo(0), key_id(NULL), key_id_len(0), signature(NULL), signature_len(0), sig_key_id(NULL), sig_key_id_len(0), sig_algo(0), sig_hash_algo(0) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
ContentEncoding::ContentEncryption::ContentEncryption() : algo(0), key_id(NULL), key_id_len(0), signature(NULL), signature_len(0), sig_key_id(NULL), sig_key_id_len(0), sig_algo(0),
174,252
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* H264SwDecMalloc(u32 size) { return malloc(size); } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119
void* H264SwDecMalloc(u32 size) void* H264SwDecMalloc(u32 size, u32 num) { if (size > UINT32_MAX / num) { return NULL; } return malloc(size * num); }
173,872
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 BrowserEventRouter::TabDetachedAt(TabContents* contents, int index) { if (!GetTabEntry(contents->web_contents())) { return; } scoped_ptr<ListValue> args(new ListValue()); args->Append(Value::CreateIntegerValue( ExtensionTabUtil::GetTabId(contents->web_contents()))); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kOldWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(contents->web_contents()))); object_args->Set(tab_keys::kOldPositionKey, Value::CreateIntegerValue( index)); args->Append(object_args); DispatchEvent(contents->profile(), events::kOnTabDetached, args.Pass(), EventRouter::USER_GESTURE_UNKNOWN); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserEventRouter::TabDetachedAt(TabContents* contents, int index) { void BrowserEventRouter::TabDetachedAt(WebContents* contents, int index) { if (!GetTabEntry(contents)) { return; } scoped_ptr<ListValue> args(new ListValue()); args->Append(Value::CreateIntegerValue(ExtensionTabUtil::GetTabId(contents))); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kOldWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(contents))); object_args->Set(tab_keys::kOldPositionKey, Value::CreateIntegerValue( index)); args->Append(object_args); Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); DispatchEvent(profile, events::kOnTabDetached, args.Pass(), EventRouter::USER_GESTURE_UNKNOWN); }
171,505
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 set_registers(rtl8150_t * dev, u16 indx, u16 size, void *data) { return usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0), RTL8150_REQ_SET_REGS, RTL8150_REQT_WRITE, indx, 0, data, size, 500); } Commit Message: rtl8150: Use heap buffers for all register access Allocating USB buffers on the stack is not portable, and no longer works on x86_64 (with VMAP_STACK enabled as per default). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Ben Hutchings <ben@decadent.org.uk> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
static int set_registers(rtl8150_t * dev, u16 indx, u16 size, void *data) static int set_registers(rtl8150_t * dev, u16 indx, u16 size, const void *data) { void *buf; int ret; buf = kmemdup(data, size, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0), RTL8150_REQ_SET_REGS, RTL8150_REQT_WRITE, indx, 0, buf, size, 500); kfree(buf); return ret; }
168,215
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; } #ifdef SO_NOSIGPIPE if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } #endif 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; } #ifdef SO_NOSIGPIPE if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } #endif 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; }
169,968
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 DocumentLoader::DetachFromFrame() { DCHECK(frame_); fetcher_->StopFetching(); if (frame_ && !SentDidFinishLoad()) LoadFailed(ResourceError::CancelledError(Url())); fetcher_->ClearContext(); if (!frame_) return; application_cache_host_->DetachFromDocumentLoader(); application_cache_host_.Clear(); service_worker_network_provider_ = nullptr; WeakIdentifierMap<DocumentLoader>::NotifyObjectDestroyed(this); ClearResource(); frame_ = nullptr; } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Nate Chapin <japhet@chromium.org> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362
void DocumentLoader::DetachFromFrame() { void DocumentLoader::StopLoading() { fetcher_->StopFetching(); if (frame_ && !SentDidFinishLoad()) LoadFailed(ResourceError::CancelledError(Url())); } void DocumentLoader::DetachFromFrame() { DCHECK(frame_); StopLoading(); fetcher_->ClearContext(); if (!frame_) return; application_cache_host_->DetachFromDocumentLoader(); application_cache_host_.Clear(); service_worker_network_provider_ = nullptr; WeakIdentifierMap<DocumentLoader>::NotifyObjectDestroyed(this); ClearResource(); frame_ = nullptr; }
171,851
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_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; png_structp png_ptr=*ptr_ptr; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_read_init() and should be" " recompiled."); break; #endif } } while (png_libpng_ver[i++]); png_debug(1, "in png_read_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); png_ptr = *ptr_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zstream.zalloc = png_zalloc; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_ptr->zstream.zalloc = png_zalloc; png_ptr->zstream.zfree = png_zfree; png_ptr->zstream.opaque = (voidpf)png_ptr; switch (inflateInit(&png_ptr->zstream)) { case Z_OK: /* Do nothing */ break; case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break; case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break; default: png_error(png_ptr, "Unknown zlib error"); } png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; png_structp png_ptr=*ptr_ptr; if (png_ptr == NULL) return; do { if (user_png_ver == NULL || user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_read_init() and should be" " recompiled."); break; #endif } } while (png_libpng_ver[i++]); png_debug(1, "in png_read_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); png_ptr = *ptr_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zstream.zalloc = png_zalloc; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_ptr->zstream.zalloc = png_zalloc; png_ptr->zstream.zfree = png_zfree; png_ptr->zstream.opaque = (voidpf)png_ptr; switch (inflateInit(&png_ptr->zstream)) { case Z_OK: /* Do nothing */ break; case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break; case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break; default: png_error(png_ptr, "Unknown zlib error"); } png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL); }
172,169
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 LELib_Create(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle) { ALOGV("LELib_Create()"); int ret; int i; if (pHandle == NULL || uuid == NULL) { return -EINVAL; } if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) { return -EINVAL; } LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext; pContext->mItfe = &gLEInterface; pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED; pContext->mCompressor = NULL; ret = LE_init(pContext); if (ret < 0) { ALOGW("LELib_Create() init failed"); delete pContext; return ret; } *pHandle = (effect_handle_t)pContext; pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED; ALOGV(" LELib_Create context is %p", pContext); return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int LELib_Create(const effect_uuid_t *uuid, int32_t sessionId __unused, int32_t ioId __unused, effect_handle_t *pHandle) { ALOGV("LELib_Create()"); int ret; int i; if (pHandle == NULL || uuid == NULL) { return -EINVAL; } if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) { return -EINVAL; } LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext; pContext->mItfe = &gLEInterface; pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED; pContext->mCompressor = NULL; ret = LE_init(pContext); if (ret < 0) { ALOGW("LELib_Create() init failed"); delete pContext; return ret; } *pHandle = (effect_handle_t)pContext; pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED; ALOGV(" LELib_Create context is %p", pContext); return 0; }
173,346
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 ReceiverWasAdded(const RtpTransceiverState& transceiver_state) { uintptr_t receiver_id = RTCRtpReceiver::getId( transceiver_state.receiver_state()->webrtc_receiver().get()); for (const auto& receiver : handler_->rtp_receivers_) { if (receiver->Id() == receiver_id) return false; } return true; } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <guidou@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#622945} CWE ID: CWE-416
bool ReceiverWasAdded(const RtpTransceiverState& transceiver_state) { DCHECK(handler_); uintptr_t receiver_id = RTCRtpReceiver::getId( transceiver_state.receiver_state()->webrtc_receiver().get()); for (const auto& receiver : handler_->rtp_receivers_) { if (receiver->Id() == receiver_id) return false; } return true; }
173,076
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: DataPipeProducerDispatcher::Deserialize(const void* data, size_t num_bytes, const ports::PortName* ports, size_t num_ports, PlatformHandle* handles, size_t num_handles) { if (num_ports != 1 || num_handles != 1 || num_bytes != sizeof(SerializedState)) { return nullptr; } const SerializedState* state = static_cast<const SerializedState*>(data); if (!state->options.capacity_num_bytes || !state->options.element_num_bytes || state->options.capacity_num_bytes < state->options.element_num_bytes) { return nullptr; } NodeController* node_controller = Core::Get()->GetNodeController(); ports::PortRef port; if (node_controller->node()->GetPort(ports[0], &port) != ports::OK) return nullptr; auto region_handle = CreateSharedMemoryRegionHandleFromPlatformHandles( std::move(handles[0]), PlatformHandle()); auto region = base::subtle::PlatformSharedMemoryRegion::Take( std::move(region_handle), base::subtle::PlatformSharedMemoryRegion::Mode::kUnsafe, state->options.capacity_num_bytes, base::UnguessableToken::Deserialize(state->buffer_guid_high, state->buffer_guid_low)); auto ring_buffer = base::UnsafeSharedMemoryRegion::Deserialize(std::move(region)); if (!ring_buffer.IsValid()) { DLOG(ERROR) << "Failed to deserialize shared buffer handle."; return nullptr; } scoped_refptr<DataPipeProducerDispatcher> dispatcher = new DataPipeProducerDispatcher(node_controller, port, std::move(ring_buffer), state->options, state->pipe_id); { base::AutoLock lock(dispatcher->lock_); dispatcher->write_offset_ = state->write_offset; dispatcher->available_capacity_ = state->available_capacity; dispatcher->peer_closed_ = state->flags & kFlagPeerClosed; if (!dispatcher->InitializeNoLock()) return nullptr; dispatcher->UpdateSignalsStateNoLock(); } return dispatcher; } Commit Message: [mojo-core] Validate data pipe endpoint metadata Ensures that we don't blindly trust specified buffer size and offset metadata when deserializing data pipe consumer and producer handles. Bug: 877182 Change-Id: I30f3eceafb5cee06284c2714d08357ef911d6fd9 Reviewed-on: https://chromium-review.googlesource.com/1192922 Reviewed-by: Reilly Grant <reillyg@chromium.org> Commit-Queue: Ken Rockot <rockot@chromium.org> Cr-Commit-Position: refs/heads/master@{#586704} CWE ID: CWE-20
DataPipeProducerDispatcher::Deserialize(const void* data, size_t num_bytes, const ports::PortName* ports, size_t num_ports, PlatformHandle* handles, size_t num_handles) { if (num_ports != 1 || num_handles != 1 || num_bytes != sizeof(SerializedState)) { return nullptr; } const SerializedState* state = static_cast<const SerializedState*>(data); if (!state->options.capacity_num_bytes || !state->options.element_num_bytes || state->options.capacity_num_bytes < state->options.element_num_bytes || state->write_offset >= state->options.capacity_num_bytes || state->available_capacity > state->options.capacity_num_bytes) { return nullptr; } NodeController* node_controller = Core::Get()->GetNodeController(); ports::PortRef port; if (node_controller->node()->GetPort(ports[0], &port) != ports::OK) return nullptr; auto region_handle = CreateSharedMemoryRegionHandleFromPlatformHandles( std::move(handles[0]), PlatformHandle()); auto region = base::subtle::PlatformSharedMemoryRegion::Take( std::move(region_handle), base::subtle::PlatformSharedMemoryRegion::Mode::kUnsafe, state->options.capacity_num_bytes, base::UnguessableToken::Deserialize(state->buffer_guid_high, state->buffer_guid_low)); auto ring_buffer = base::UnsafeSharedMemoryRegion::Deserialize(std::move(region)); if (!ring_buffer.IsValid()) { DLOG(ERROR) << "Failed to deserialize shared buffer handle."; return nullptr; } scoped_refptr<DataPipeProducerDispatcher> dispatcher = new DataPipeProducerDispatcher(node_controller, port, std::move(ring_buffer), state->options, state->pipe_id); { base::AutoLock lock(dispatcher->lock_); dispatcher->write_offset_ = state->write_offset; dispatcher->available_capacity_ = state->available_capacity; dispatcher->peer_closed_ = state->flags & kFlagPeerClosed; if (!dispatcher->InitializeNoLock()) return nullptr; if (state->options.capacity_num_bytes > dispatcher->ring_buffer_mapping_.mapped_size()) { return nullptr; } dispatcher->UpdateSignalsStateNoLock(); } return dispatcher; }
173,177
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 RuntimeCustomBindings::GetExtensionViews( const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 2) return; if (!args[0]->IsInt32() || !args[1]->IsString()) return; int browser_window_id = args[0]->Int32Value(); std::string view_type_string = base::ToUpperASCII(*v8::String::Utf8Value(args[1])); ViewType view_type = VIEW_TYPE_INVALID; if (view_type_string == kViewTypeBackgroundPage) { view_type = VIEW_TYPE_EXTENSION_BACKGROUND_PAGE; } else if (view_type_string == kViewTypeTabContents) { view_type = VIEW_TYPE_TAB_CONTENTS; } else if (view_type_string == kViewTypePopup) { view_type = VIEW_TYPE_EXTENSION_POPUP; } else if (view_type_string == kViewTypeExtensionDialog) { view_type = VIEW_TYPE_EXTENSION_DIALOG; } else if (view_type_string == kViewTypeAppWindow) { view_type = VIEW_TYPE_APP_WINDOW; } else if (view_type_string == kViewTypeLauncherPage) { view_type = VIEW_TYPE_LAUNCHER_PAGE; } else if (view_type_string == kViewTypePanel) { view_type = VIEW_TYPE_PANEL; } else if (view_type_string != kViewTypeAll) { return; } std::string extension_id = context()->GetExtensionID(); if (extension_id.empty()) return; std::vector<content::RenderFrame*> frames = ExtensionFrameHelper::GetExtensionFrames(extension_id, browser_window_id, view_type); v8::Local<v8::Array> v8_views = v8::Array::New(args.GetIsolate()); int v8_index = 0; for (content::RenderFrame* frame : frames) { if (frame->GetWebFrame()->top() != frame->GetWebFrame()) continue; v8::Local<v8::Context> context = frame->GetWebFrame()->mainWorldScriptContext(); if (!context.IsEmpty()) { v8::Local<v8::Value> window = context->Global(); DCHECK(!window.IsEmpty()); v8_views->Set(v8::Integer::New(args.GetIsolate(), v8_index++), window); } } args.GetReturnValue().Set(v8_views); } Commit Message: Create array of extension views without side effects BUG=608104 Review-Url: https://codereview.chromium.org/1935953002 Cr-Commit-Position: refs/heads/master@{#390961} CWE ID:
void RuntimeCustomBindings::GetExtensionViews( const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 2) return; if (!args[0]->IsInt32() || !args[1]->IsString()) return; int browser_window_id = args[0]->Int32Value(); std::string view_type_string = base::ToUpperASCII(*v8::String::Utf8Value(args[1])); ViewType view_type = VIEW_TYPE_INVALID; if (view_type_string == kViewTypeBackgroundPage) { view_type = VIEW_TYPE_EXTENSION_BACKGROUND_PAGE; } else if (view_type_string == kViewTypeTabContents) { view_type = VIEW_TYPE_TAB_CONTENTS; } else if (view_type_string == kViewTypePopup) { view_type = VIEW_TYPE_EXTENSION_POPUP; } else if (view_type_string == kViewTypeExtensionDialog) { view_type = VIEW_TYPE_EXTENSION_DIALOG; } else if (view_type_string == kViewTypeAppWindow) { view_type = VIEW_TYPE_APP_WINDOW; } else if (view_type_string == kViewTypeLauncherPage) { view_type = VIEW_TYPE_LAUNCHER_PAGE; } else if (view_type_string == kViewTypePanel) { view_type = VIEW_TYPE_PANEL; } else if (view_type_string != kViewTypeAll) { return; } std::string extension_id = context()->GetExtensionID(); if (extension_id.empty()) return; std::vector<content::RenderFrame*> frames = ExtensionFrameHelper::GetExtensionFrames(extension_id, browser_window_id, view_type); v8::Local<v8::Context> v8_context = args.GetIsolate()->GetCurrentContext(); v8::Local<v8::Array> v8_views = v8::Array::New(args.GetIsolate()); int v8_index = 0; for (content::RenderFrame* frame : frames) { if (frame->GetWebFrame()->top() != frame->GetWebFrame()) continue; v8::Local<v8::Context> context = frame->GetWebFrame()->mainWorldScriptContext(); if (!context.IsEmpty()) { v8::Local<v8::Value> window = context->Global(); DCHECK(!window.IsEmpty()); v8::Maybe<bool> maybe = v8_views->CreateDataProperty(v8_context, v8_index++, window); DCHECK(maybe.IsJust() && maybe.FromJust()); } } args.GetReturnValue().Set(v8_views); }
172,260
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 SoftMPEG2::setDecodeArgs( ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op, OMX_BUFFERHEADERTYPE *inHeader, OMX_BUFFERHEADERTYPE *outHeader, size_t timeStampIx) { size_t sizeY = outputBufferWidth() * outputBufferHeight(); size_t sizeUV; uint8_t *pBuf; ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE; /* When in flush and after EOS with zero byte input, * inHeader is set to zero. Hence check for non-null */ if (inHeader) { ps_dec_ip->u4_ts = timeStampIx; ps_dec_ip->pv_stream_buffer = inHeader->pBuffer + inHeader->nOffset; ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen; } else { ps_dec_ip->u4_ts = 0; ps_dec_ip->pv_stream_buffer = NULL; ps_dec_ip->u4_num_Bytes = 0; } if (outHeader) { pBuf = outHeader->pBuffer; } else { pBuf = mFlushOutBuffer; } sizeUV = sizeY / 4; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; ps_dec_ip->s_out_buffer.u4_num_bufs = 3; return; } Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec Bug: 27833616 Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738 (cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d) CWE ID: CWE-20
void SoftMPEG2::setDecodeArgs( bool SoftMPEG2::setDecodeArgs( ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op, OMX_BUFFERHEADERTYPE *inHeader, OMX_BUFFERHEADERTYPE *outHeader, size_t timeStampIx) { size_t sizeY = outputBufferWidth() * outputBufferHeight(); size_t sizeUV; ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE; /* When in flush and after EOS with zero byte input, * inHeader is set to zero. Hence check for non-null */ if (inHeader) { ps_dec_ip->u4_ts = timeStampIx; ps_dec_ip->pv_stream_buffer = inHeader->pBuffer + inHeader->nOffset; ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen; } else { ps_dec_ip->u4_ts = 0; ps_dec_ip->pv_stream_buffer = NULL; ps_dec_ip->u4_num_Bytes = 0; } sizeUV = sizeY / 4; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; uint8_t *pBuf; if (outHeader) { if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) { android_errorWriteLog(0x534e4554, "27569635"); return false; } pBuf = outHeader->pBuffer; } else { // mFlushOutBuffer always has the right size. pBuf = mFlushOutBuffer; } ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; ps_dec_ip->s_out_buffer.u4_num_bufs = 3; return true; }
174,184
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::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || 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; } uint32_t numSyncSamples = U32_AT(&header[4]); if (numSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } uint64_t allocSize = (uint64_t)numSyncSamples * sizeof(uint32_t); if (allocSize > kMaxTotalSize) { ALOGE("Sync sample table size too large."); return ERROR_OUT_OF_RANGE; } mTotalSize += allocSize; if (mTotalSize > kMaxTotalSize) { ALOGE("Sync sample table size would make sample table too large.\n" " Requested sync sample table size = %llu\n" " Eventual sample table size >= %llu\n" " Allowed sample table size = %llu\n", (unsigned long long)allocSize, (unsigned long long)mTotalSize, (unsigned long long)kMaxTotalSize); return ERROR_OUT_OF_RANGE; } mSyncSamples = new (std::nothrow) uint32_t[numSyncSamples]; if (!mSyncSamples) { ALOGE("Cannot allocate sync sample table with %llu entries.", (unsigned long long)numSyncSamples); return ERROR_OUT_OF_RANGE; } if (mDataSource->readAt(data_offset + 8, mSyncSamples, (size_t)allocSize) != (ssize_t)allocSize) { delete mSyncSamples; mSyncSamples = NULL; return ERROR_IO; } for (size_t i = 0; i < numSyncSamples; ++i) { if (mSyncSamples[i] == 0) { ALOGE("b/32423862, unexpected zero value in stss"); continue; } mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } mSyncSampleOffset = data_offset; mNumSyncSamples = numSyncSamples; return OK; } Commit Message: Fix 'potential memory leak' compiler warning. This CL fixes the following compiler warning: frameworks/av/media/libstagefright/SampleTable.cpp:569:9: warning: Memory allocated by 'new[]' should be deallocated by 'delete[]', not 'delete'. Bug: 33137046 Test: Compiled with change; no warning generated. Change-Id: I29abd90e02bf482fa840d1f7206ebbdacf7dfa37 (cherry picked from commit 158c197b668ad684f92829db6a31bee3aec794ba) (cherry picked from commit 37c428cd521351837fccb6864f509f996820b234) CWE ID: CWE-772
status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || 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; } uint32_t numSyncSamples = U32_AT(&header[4]); if (numSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } uint64_t allocSize = (uint64_t)numSyncSamples * sizeof(uint32_t); if (allocSize > kMaxTotalSize) { ALOGE("Sync sample table size too large."); return ERROR_OUT_OF_RANGE; } mTotalSize += allocSize; if (mTotalSize > kMaxTotalSize) { ALOGE("Sync sample table size would make sample table too large.\n" " Requested sync sample table size = %llu\n" " Eventual sample table size >= %llu\n" " Allowed sample table size = %llu\n", (unsigned long long)allocSize, (unsigned long long)mTotalSize, (unsigned long long)kMaxTotalSize); return ERROR_OUT_OF_RANGE; } mSyncSamples = new (std::nothrow) uint32_t[numSyncSamples]; if (!mSyncSamples) { ALOGE("Cannot allocate sync sample table with %llu entries.", (unsigned long long)numSyncSamples); return ERROR_OUT_OF_RANGE; } if (mDataSource->readAt(data_offset + 8, mSyncSamples, (size_t)allocSize) != (ssize_t)allocSize) { delete[] mSyncSamples; mSyncSamples = NULL; return ERROR_IO; } for (size_t i = 0; i < numSyncSamples; ++i) { if (mSyncSamples[i] == 0) { ALOGE("b/32423862, unexpected zero value in stss"); continue; } mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } mSyncSampleOffset = data_offset; mNumSyncSamples = numSyncSamples; return OK; }
173,992