instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void vrend_renderer_context_create_internal(uint32_t handle, uint32_t nlen, const char *debug_name) { struct vrend_decode_ctx *dctx; if (handle >= VREND_MAX_CTX) return; dctx = malloc(sizeof(struct vrend_decode_ctx)); if (!dctx) return; return; } Commit Message: CWE ID: CWE-399
void vrend_renderer_context_create_internal(uint32_t handle, uint32_t nlen, const char *debug_name) { struct vrend_decode_ctx *dctx; if (handle >= VREND_MAX_CTX) return; dctx = dec_ctx[handle]; if (dctx) return; dctx = malloc(sizeof(struct vrend_decode_ctx)); if (!dctx) return; return; }
165,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { MagickBooleanType status; int bit; register const PixelPacket *p; register ssize_t x; ssize_t y; unsigned char byte; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); if((image->columns > 255L) || (image->rows > 255L)) ThrowWriterException(ImageError,"Dimensions must be less than 255x255"); /* Write header (just the image dimensions) */ (void) WriteBlobByte(image,image->columns & 0xff); (void) WriteBlobByte(image,image->rows & 0xff); /* Convert MIFF to bit pixels. */ (void) SetImageType(image,BilevelType); x=0; y=0; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte>>=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x80; bit++; if (bit == 8) { /* Write a bitmap byte to the image file. */ (void) WriteBlobByte(image,byte); bit=0; byte=0; } p++; } if (bit != 0) (void) WriteBlobByte(image,byte); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) CloseBlob(image); return(MagickTrue); } Commit Message: Fix abort when writing to rgf format The rgf format (LEGO MINDSTORMS EV3 images) caused a software abort because exception == NULL. When WriteRGFImage is called from WriteImage, it is only passed two parameters, not three. So, removed the extra parameter and use image->exception instead as in other coders. CWE ID: CWE-19
static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image, static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; int bit; register const PixelPacket *p; register ssize_t x; ssize_t y; unsigned char byte; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); if((image->columns > 255L) || (image->rows > 255L)) ThrowWriterException(ImageError,"Dimensions must be less than 255x255"); /* Write header (just the image dimensions) */ (void) WriteBlobByte(image,image->columns & 0xff); (void) WriteBlobByte(image,image->rows & 0xff); /* Convert MIFF to bit pixels. */ (void) SetImageType(image,BilevelType); x=0; y=0; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte>>=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x80; bit++; if (bit == 8) { /* Write a bitmap byte to the image file. */ (void) WriteBlobByte(image,byte); bit=0; byte=0; } p++; } if (bit != 0) (void) WriteBlobByte(image,byte); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) CloseBlob(image); return(MagickTrue); }
168,786
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int verify_iovec(struct msghdr *m, struct iovec *iov, struct sockaddr_storage *address, int mode) { int size, ct, err; if (m->msg_namelen) { if (mode == VERIFY_READ) { void __user *namep; namep = (void __user __force *) m->msg_name; err = move_addr_to_kernel(namep, m->msg_namelen, address); if (err < 0) return err; } m->msg_name = address; } else { m->msg_name = NULL; } size = m->msg_iovlen * sizeof(struct iovec); if (copy_from_user(iov, (void __user __force *) m->msg_iov, size)) return -EFAULT; m->msg_iov = iov; err = 0; for (ct = 0; ct < m->msg_iovlen; ct++) { size_t len = iov[ct].iov_len; if (len > INT_MAX - err) { len = INT_MAX - err; iov[ct].iov_len = len; } err += len; } return err; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
int verify_iovec(struct msghdr *m, struct iovec *iov, struct sockaddr_storage *address, int mode) { int size, ct, err; if (m->msg_namelen) { if (mode == VERIFY_READ) { void __user *namep; namep = (void __user __force *) m->msg_name; err = move_addr_to_kernel(namep, m->msg_namelen, address); if (err < 0) return err; } if (m->msg_name) m->msg_name = address; } else { m->msg_name = NULL; } size = m->msg_iovlen * sizeof(struct iovec); if (copy_from_user(iov, (void __user __force *) m->msg_iov, size)) return -EFAULT; m->msg_iov = iov; err = 0; for (ct = 0; ct < m->msg_iovlen; ct++) { size_t len = iov[ct].iov_len; if (len > INT_MAX - err) { len = INT_MAX - err; iov[ct].iov_len = len; } err += len; } return err; }
166,499
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) { struct ip_options *sopt; unsigned char *sptr, *dptr; int soffset, doffset; int optlen; __be32 daddr; memset(dopt, 0, sizeof(struct ip_options)); sopt = &(IPCB(skb)->opt); if (sopt->optlen == 0) { dopt->optlen = 0; return 0; } sptr = skb_network_header(skb); dptr = dopt->__data; daddr = skb_rtable(skb)->rt_spec_dst; if (sopt->rr) { optlen = sptr[sopt->rr+1]; soffset = sptr[sopt->rr+2]; dopt->rr = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->rr, optlen); if (sopt->rr_needaddr && soffset <= optlen) { if (soffset + 3 > optlen) return -EINVAL; dptr[2] = soffset + 4; dopt->rr_needaddr = 1; } dptr += optlen; dopt->optlen += optlen; } if (sopt->ts) { optlen = sptr[sopt->ts+1]; soffset = sptr[sopt->ts+2]; dopt->ts = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->ts, optlen); if (soffset <= optlen) { if (sopt->ts_needaddr) { if (soffset + 3 > optlen) return -EINVAL; dopt->ts_needaddr = 1; soffset += 4; } if (sopt->ts_needtime) { if (soffset + 3 > optlen) return -EINVAL; if ((dptr[3]&0xF) != IPOPT_TS_PRESPEC) { dopt->ts_needtime = 1; soffset += 4; } else { dopt->ts_needtime = 0; if (soffset + 7 <= optlen) { __be32 addr; memcpy(&addr, dptr+soffset-1, 4); if (inet_addr_type(dev_net(skb_dst(skb)->dev), addr) != RTN_UNICAST) { dopt->ts_needtime = 1; soffset += 8; } } } } dptr[2] = soffset; } dptr += optlen; dopt->optlen += optlen; } if (sopt->srr) { unsigned char * start = sptr+sopt->srr; __be32 faddr; optlen = start[1]; soffset = start[2]; doffset = 0; if (soffset > optlen) soffset = optlen + 1; soffset -= 4; if (soffset > 3) { memcpy(&faddr, &start[soffset-1], 4); for (soffset-=4, doffset=4; soffset > 3; soffset-=4, doffset+=4) memcpy(&dptr[doffset-1], &start[soffset-1], 4); /* * RFC1812 requires to fix illegal source routes. */ if (memcmp(&ip_hdr(skb)->saddr, &start[soffset + 3], 4) == 0) doffset -= 4; } if (doffset > 3) { memcpy(&start[doffset-1], &daddr, 4); dopt->faddr = faddr; dptr[0] = start[0]; dptr[1] = doffset+3; dptr[2] = 4; dptr += doffset+3; dopt->srr = dopt->optlen + sizeof(struct iphdr); dopt->optlen += doffset+3; dopt->is_strictroute = sopt->is_strictroute; } } if (sopt->cipso) { optlen = sptr[sopt->cipso+1]; dopt->cipso = dopt->optlen+sizeof(struct iphdr); memcpy(dptr, sptr+sopt->cipso, optlen); dptr += optlen; dopt->optlen += optlen; } while (dopt->optlen & 3) { *dptr++ = IPOPT_END; dopt->optlen++; } return 0; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) int ip_options_echo(struct ip_options *dopt, struct sk_buff *skb) { const struct ip_options *sopt; unsigned char *sptr, *dptr; int soffset, doffset; int optlen; __be32 daddr; memset(dopt, 0, sizeof(struct ip_options)); sopt = &(IPCB(skb)->opt); if (sopt->optlen == 0) return 0; sptr = skb_network_header(skb); dptr = dopt->__data; daddr = skb_rtable(skb)->rt_spec_dst; if (sopt->rr) { optlen = sptr[sopt->rr+1]; soffset = sptr[sopt->rr+2]; dopt->rr = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->rr, optlen); if (sopt->rr_needaddr && soffset <= optlen) { if (soffset + 3 > optlen) return -EINVAL; dptr[2] = soffset + 4; dopt->rr_needaddr = 1; } dptr += optlen; dopt->optlen += optlen; } if (sopt->ts) { optlen = sptr[sopt->ts+1]; soffset = sptr[sopt->ts+2]; dopt->ts = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->ts, optlen); if (soffset <= optlen) { if (sopt->ts_needaddr) { if (soffset + 3 > optlen) return -EINVAL; dopt->ts_needaddr = 1; soffset += 4; } if (sopt->ts_needtime) { if (soffset + 3 > optlen) return -EINVAL; if ((dptr[3]&0xF) != IPOPT_TS_PRESPEC) { dopt->ts_needtime = 1; soffset += 4; } else { dopt->ts_needtime = 0; if (soffset + 7 <= optlen) { __be32 addr; memcpy(&addr, dptr+soffset-1, 4); if (inet_addr_type(dev_net(skb_dst(skb)->dev), addr) != RTN_UNICAST) { dopt->ts_needtime = 1; soffset += 8; } } } } dptr[2] = soffset; } dptr += optlen; dopt->optlen += optlen; } if (sopt->srr) { unsigned char *start = sptr+sopt->srr; __be32 faddr; optlen = start[1]; soffset = start[2]; doffset = 0; if (soffset > optlen) soffset = optlen + 1; soffset -= 4; if (soffset > 3) { memcpy(&faddr, &start[soffset-1], 4); for (soffset-=4, doffset=4; soffset > 3; soffset-=4, doffset+=4) memcpy(&dptr[doffset-1], &start[soffset-1], 4); /* * RFC1812 requires to fix illegal source routes. */ if (memcmp(&ip_hdr(skb)->saddr, &start[soffset + 3], 4) == 0) doffset -= 4; } if (doffset > 3) { memcpy(&start[doffset-1], &daddr, 4); dopt->faddr = faddr; dptr[0] = start[0]; dptr[1] = doffset+3; dptr[2] = 4; dptr += doffset+3; dopt->srr = dopt->optlen + sizeof(struct iphdr); dopt->optlen += doffset+3; dopt->is_strictroute = sopt->is_strictroute; } } if (sopt->cipso) { optlen = sptr[sopt->cipso+1]; dopt->cipso = dopt->optlen+sizeof(struct iphdr); memcpy(dptr, sptr+sopt->cipso, optlen); dptr += optlen; dopt->optlen += optlen; } while (dopt->optlen & 3) { *dptr++ = IPOPT_END; dopt->optlen++; } return 0; }
165,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RTCPeerConnection::createOffer(PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback, const Dictionary& mediaConstraints, ExceptionCode& ec) { if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) { ec = INVALID_STATE_ERR; return; } if (!successCallback) { ec = TYPE_MISMATCH_ERR; return; } RefPtr<MediaConstraints> constraints = MediaConstraintsImpl::create(mediaConstraints, ec); if (ec) return; RefPtr<RTCSessionDescriptionRequestImpl> request = RTCSessionDescriptionRequestImpl::create(scriptExecutionContext(), successCallback, errorCallback); m_peerHandler->createOffer(request.release(), constraints); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
void RTCPeerConnection::createOffer(PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback, const Dictionary& mediaConstraints, ExceptionCode& ec) { if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) { ec = INVALID_STATE_ERR; return; } if (!successCallback) { ec = TYPE_MISMATCH_ERR; return; } RefPtr<MediaConstraints> constraints = MediaConstraintsImpl::create(mediaConstraints, ec); if (ec) return; RefPtr<RTCSessionDescriptionRequestImpl> request = RTCSessionDescriptionRequestImpl::create(scriptExecutionContext(), successCallback, errorCallback, this); m_peerHandler->createOffer(request.release(), constraints); }
170,335
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void testInspectorDefault(InspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector); g_assert(inspectorView.get()); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get())); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->showAndWaitUntilFinished(true); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Closed); test->m_events.clear(); } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void testInspectorDefault(InspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector); g_assert(inspectorView.get()); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get())); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->showAndWaitUntilFinished(true); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), >=, InspectorTest::gMinimumAttachedInspectorHeight); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Closed); test->m_events.clear(); }
171,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, size_t nbytes) { union { int32_t l; char c[sizeof (int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } if (S_ISREG(st.st_mode) || st.st_size != 0) fsize = st.st_size; else fsize = SIZE_UNKNOWN; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, size_t nbytes) { union { int32_t l; char c[sizeof (int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum, notecount; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } if (S_ISREG(st.st_mode) || st.st_size != 0) fsize = st.st_size; else fsize = SIZE_UNKNOWN; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; }
166,780
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewMessageHandler::OnMetafileReadyForPrinting( const PrintHostMsg_DidPreviewDocument_Params& params) { StopWorker(params.document_cookie); if (params.expected_pages_count <= 0) { NOTREACHED(); 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); if (!data_bytes || !data_bytes->size()) return; print_preview_ui->SetPrintPreviewDataForIndex(COMPLETE_PREVIEW_DOCUMENT_INDEX, std::move(data_bytes)); print_preview_ui->OnPreviewDataIsAvailable( params.expected_pages_count, 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. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
void PrintPreviewMessageHandler::OnMetafileReadyForPrinting( const PrintHostMsg_DidPreviewDocument_Params& params) { StopWorker(params.document_cookie); if (params.expected_pages_count <= 0) { NOTREACHED(); 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); client->DoComposite( params.metafile_data_handle, params.data_size, base::BindOnce(&PrintPreviewMessageHandler::OnCompositePdfDocumentDone, weak_ptr_factory_.GetWeakPtr(), params.expected_pages_count, params.preview_request_id)); } else { NotifyUIPreviewDocumentReady( params.expected_pages_count, params.preview_request_id, GetDataFromHandle(params.metafile_data_handle, params.data_size)); } }
171,890
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int udhcpd_main(int argc UNUSED_PARAM, char **argv) { int server_socket = -1, retval; uint8_t *state; unsigned timeout_end; unsigned num_ips; unsigned opt; struct option_set *option; char *str_I = str_I; const char *str_a = "2000"; unsigned arpping_ms; IF_FEATURE_UDHCP_PORT(char *str_P;) setup_common_bufsiz(); IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;) IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;) opt = getopt32(argv, "^" "fSI:va:"IF_FEATURE_UDHCP_PORT("P:") "\0" #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1 "vv" #endif , &str_I , &str_a IF_FEATURE_UDHCP_PORT(, &str_P) IF_UDHCP_VERBOSE(, &dhcp_verbose) ); if (!(opt & 1)) { /* no -f */ bb_daemonize_or_rexec(0, argv); logmode = LOGMODE_NONE; } /* update argv after the possible vfork+exec in daemonize */ argv += optind; if (opt & 2) { /* -S */ openlog(applet_name, LOG_PID, LOG_DAEMON); logmode |= LOGMODE_SYSLOG; } if (opt & 4) { /* -I */ len_and_sockaddr *lsa = xhost_and_af2sockaddr(str_I, 0, AF_INET); server_config.server_nip = lsa->u.sin.sin_addr.s_addr; free(lsa); } #if ENABLE_FEATURE_UDHCP_PORT if (opt & 32) { /* -P */ SERVER_PORT = xatou16(str_P); CLIENT_PORT = SERVER_PORT + 1; } #endif arpping_ms = xatou(str_a); /* Would rather not do read_config before daemonization - * otherwise NOMMU machines will parse config twice */ read_config(argv[0] ? argv[0] : DHCPD_CONF_FILE); /* prevent poll timeout overflow */ if (server_config.auto_time > INT_MAX / 1000) server_config.auto_time = INT_MAX / 1000; /* Make sure fd 0,1,2 are open */ bb_sanitize_stdio(); /* Create pidfile */ write_pidfile(server_config.pidfile); /* if (!..) bb_perror_msg("can't create pidfile %s", pidfile); */ bb_error_msg("started, v"BB_VER); option = udhcp_find_option(server_config.options, DHCP_LEASE_TIME); server_config.max_lease_sec = DEFAULT_LEASE_TIME; if (option) { move_from_unaligned32(server_config.max_lease_sec, option->data + OPT_DATA); server_config.max_lease_sec = ntohl(server_config.max_lease_sec); } /* Sanity check */ num_ips = server_config.end_ip - server_config.start_ip + 1; if (server_config.max_leases > num_ips) { bb_error_msg("max_leases=%u is too big, setting to %u", (unsigned)server_config.max_leases, num_ips); server_config.max_leases = num_ips; } /* this sets g_leases */ SET_PTR_TO_GLOBALS(xzalloc(server_config.max_leases * sizeof(g_leases[0]))); read_leases(server_config.lease_file); if (udhcp_read_interface(server_config.interface, &server_config.ifindex, (server_config.server_nip == 0 ? &server_config.server_nip : NULL), server_config.server_mac) ) { retval = 1; goto ret; } /* Setup the signal pipe */ udhcp_sp_setup(); continue_with_autotime: timeout_end = monotonic_sec() + server_config.auto_time; while (1) { /* loop until universe collapses */ struct pollfd pfds[2]; struct dhcp_packet packet; int bytes; int tv; uint8_t *server_id_opt; uint8_t *requested_ip_opt; uint32_t requested_nip = requested_nip; /* for compiler */ uint32_t static_lease_nip; struct dyn_lease *lease, fake_lease; if (server_socket < 0) { server_socket = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT, server_config.interface); } udhcp_sp_fd_set(pfds, server_socket); new_tv: tv = -1; if (server_config.auto_time) { tv = timeout_end - monotonic_sec(); if (tv <= 0) { write_leases: write_leases(); goto continue_with_autotime; } tv *= 1000; } /* Block here waiting for either signal or packet */ retval = poll(pfds, 2, tv); if (retval <= 0) { if (retval == 0) goto write_leases; if (errno == EINTR) goto new_tv; /* < 0 and not EINTR: should not happen */ bb_perror_msg_and_die("poll"); } if (pfds[0].revents) switch (udhcp_sp_read()) { case SIGUSR1: bb_error_msg("received %s", "SIGUSR1"); write_leases(); /* why not just reset the timeout, eh */ goto continue_with_autotime; case SIGTERM: bb_error_msg("received %s", "SIGTERM"); write_leases(); goto ret0; } /* Is it a packet? */ if (!pfds[1].revents) continue; /* no */ /* Note: we do not block here, we block on poll() instead. * Blocking here would prevent SIGTERM from working: * socket read inside this call is restarted on caught signals. */ bytes = udhcp_recv_kernel_packet(&packet, server_socket); if (bytes < 0) { /* bytes can also be -2 ("bad packet data") */ if (bytes == -1 && errno != EINTR) { log1("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO); close(server_socket); server_socket = -1; } continue; } if (packet.hlen != 6) { bb_error_msg("MAC length != 6, ignoring packet"); continue; } if (packet.op != BOOTREQUEST) { bb_error_msg("not a REQUEST, ignoring packet"); continue; } state = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE); if (state == NULL || state[0] < DHCP_MINTYPE || state[0] > DHCP_MAXTYPE) { bb_error_msg("no or bad message type option, ignoring packet"); continue; } /* Get SERVER_ID if present */ server_id_opt = udhcp_get_option(&packet, DHCP_SERVER_ID); if (server_id_opt) { uint32_t server_id_network_order; move_from_unaligned32(server_id_network_order, server_id_opt); if (server_id_network_order != server_config.server_nip) { /* client talks to somebody else */ log1("server ID doesn't match, ignoring"); continue; } } /* Look for a static/dynamic lease */ static_lease_nip = get_static_nip_by_mac(server_config.static_leases, &packet.chaddr); if (static_lease_nip) { bb_error_msg("found static lease: %x", static_lease_nip); memcpy(&fake_lease.lease_mac, &packet.chaddr, 6); fake_lease.lease_nip = static_lease_nip; fake_lease.expires = 0; lease = &fake_lease; } else { lease = find_lease_by_mac(packet.chaddr); } /* Get REQUESTED_IP if present */ requested_ip_opt = udhcp_get_option(&packet, DHCP_REQUESTED_IP); if (requested_ip_opt) { move_from_unaligned32(requested_nip, requested_ip_opt); } switch (state[0]) { case DHCPDISCOVER: log1("received %s", "DISCOVER"); send_offer(&packet, static_lease_nip, lease, requested_ip_opt, arpping_ms); break; case DHCPREQUEST: log1("received %s", "REQUEST"); /* RFC 2131: o DHCPREQUEST generated during SELECTING state: Client inserts the address of the selected server in 'server identifier', 'ciaddr' MUST be zero, 'requested IP address' MUST be filled in with the yiaddr value from the chosen DHCPOFFER. Note that the client may choose to collect several DHCPOFFER messages and select the "best" offer. The client indicates its selection by identifying the offering server in the DHCPREQUEST message. If the client receives no acceptable offers, the client may choose to try another DHCPDISCOVER message. Therefore, the servers may not receive a specific DHCPREQUEST from which they can decide whether or not the client has accepted the offer. o DHCPREQUEST generated during INIT-REBOOT state: 'server identifier' MUST NOT be filled in, 'requested IP address' option MUST be filled in with client's notion of its previously assigned address. 'ciaddr' MUST be zero. The client is seeking to verify a previously allocated, cached configuration. Server SHOULD send a DHCPNAK message to the client if the 'requested IP address' is incorrect, or is on the wrong network. Determining whether a client in the INIT-REBOOT state is on the correct network is done by examining the contents of 'giaddr', the 'requested IP address' option, and a database lookup. If the DHCP server detects that the client is on the wrong net (i.e., the result of applying the local subnet mask or remote subnet mask (if 'giaddr' is not zero) to 'requested IP address' option value doesn't match reality), then the server SHOULD send a DHCPNAK message to the client. If the network is correct, then the DHCP server should check if the client's notion of its IP address is correct. If not, then the server SHOULD send a DHCPNAK message to the client. If the DHCP server has no record of this client, then it MUST remain silent, and MAY output a warning to the network administrator. This behavior is necessary for peaceful coexistence of non- communicating DHCP servers on the same wire. If 'giaddr' is 0x0 in the DHCPREQUEST message, the client is on the same subnet as the server. The server MUST broadcast the DHCPNAK message to the 0xffffffff broadcast address because the client may not have a correct network address or subnet mask, and the client may not be answering ARP requests. If 'giaddr' is set in the DHCPREQUEST message, the client is on a different subnet. The server MUST set the broadcast bit in the DHCPNAK, so that the relay agent will broadcast the DHCPNAK to the client, because the client may not have a correct network address or subnet mask, and the client may not be answering ARP requests. o DHCPREQUEST generated during RENEWING state: 'server identifier' MUST NOT be filled in, 'requested IP address' option MUST NOT be filled in, 'ciaddr' MUST be filled in with client's IP address. In this situation, the client is completely configured, and is trying to extend its lease. This message will be unicast, so no relay agents will be involved in its transmission. Because 'giaddr' is therefore not filled in, the DHCP server will trust the value in 'ciaddr', and use it when replying to the client. A client MAY choose to renew or extend its lease prior to T1. The server may choose not to extend the lease (as a policy decision by the network administrator), but should return a DHCPACK message regardless. o DHCPREQUEST generated during REBINDING state: 'server identifier' MUST NOT be filled in, 'requested IP address' option MUST NOT be filled in, 'ciaddr' MUST be filled in with client's IP address. In this situation, the client is completely configured, and is trying to extend its lease. This message MUST be broadcast to the 0xffffffff IP broadcast address. The DHCP server SHOULD check 'ciaddr' for correctness before replying to the DHCPREQUEST. The DHCPREQUEST from a REBINDING client is intended to accommodate sites that have multiple DHCP servers and a mechanism for maintaining consistency among leases managed by multiple servers. A DHCP server MAY extend a client's lease only if it has local administrative authority to do so. */ if (!requested_ip_opt) { requested_nip = packet.ciaddr; if (requested_nip == 0) { log1("no requested IP and no ciaddr, ignoring"); break; } } if (lease && requested_nip == lease->lease_nip) { /* client requested or configured IP matches the lease. * ACK it, and bump lease expiration time. */ send_ACK(&packet, lease->lease_nip); break; } /* No lease for this MAC, or lease IP != requested IP */ if (server_id_opt /* client is in SELECTING state */ || requested_ip_opt /* client is in INIT-REBOOT state */ ) { /* "No, we don't have this IP for you" */ send_NAK(&packet); } /* else: client is in RENEWING or REBINDING, do not answer */ break; case DHCPDECLINE: /* RFC 2131: * "If the server receives a DHCPDECLINE message, * the client has discovered through some other means * that the suggested network address is already * in use. The server MUST mark the network address * as not available and SHOULD notify the local * sysadmin of a possible configuration problem." * * SERVER_ID must be present, * REQUESTED_IP must be present, * chaddr must be filled in, * ciaddr must be 0 (we do not check this) */ log1("received %s", "DECLINE"); if (server_id_opt && requested_ip_opt && lease /* chaddr matches this lease */ && requested_nip == lease->lease_nip ) { memset(lease->lease_mac, 0, sizeof(lease->lease_mac)); lease->expires = time(NULL) + server_config.decline_time; } break; case DHCPRELEASE: /* "Upon receipt of a DHCPRELEASE message, the server * marks the network address as not allocated." * * SERVER_ID must be present, * REQUESTED_IP must not be present (we do not check this), * chaddr must be filled in, * ciaddr must be filled in */ log1("received %s", "RELEASE"); if (server_id_opt && lease /* chaddr matches this lease */ && packet.ciaddr == lease->lease_nip ) { lease->expires = time(NULL); } break; case DHCPINFORM: log1("received %s", "INFORM"); send_inform(&packet); break; } } ret0: retval = 0; ret: /*if (server_config.pidfile) - server_config.pidfile is never NULL */ remove_pidfile(server_config.pidfile); return retval; } Commit Message: CWE ID: CWE-125
int udhcpd_main(int argc UNUSED_PARAM, char **argv) { int server_socket = -1, retval; uint8_t *state; unsigned timeout_end; unsigned num_ips; unsigned opt; struct option_set *option; char *str_I = str_I; const char *str_a = "2000"; unsigned arpping_ms; IF_FEATURE_UDHCP_PORT(char *str_P;) setup_common_bufsiz(); IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;) IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;) opt = getopt32(argv, "^" "fSI:va:"IF_FEATURE_UDHCP_PORT("P:") "\0" #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1 "vv" #endif , &str_I , &str_a IF_FEATURE_UDHCP_PORT(, &str_P) IF_UDHCP_VERBOSE(, &dhcp_verbose) ); if (!(opt & 1)) { /* no -f */ bb_daemonize_or_rexec(0, argv); logmode = LOGMODE_NONE; } /* update argv after the possible vfork+exec in daemonize */ argv += optind; if (opt & 2) { /* -S */ openlog(applet_name, LOG_PID, LOG_DAEMON); logmode |= LOGMODE_SYSLOG; } if (opt & 4) { /* -I */ len_and_sockaddr *lsa = xhost_and_af2sockaddr(str_I, 0, AF_INET); server_config.server_nip = lsa->u.sin.sin_addr.s_addr; free(lsa); } #if ENABLE_FEATURE_UDHCP_PORT if (opt & 32) { /* -P */ SERVER_PORT = xatou16(str_P); CLIENT_PORT = SERVER_PORT + 1; } #endif arpping_ms = xatou(str_a); /* Would rather not do read_config before daemonization - * otherwise NOMMU machines will parse config twice */ read_config(argv[0] ? argv[0] : DHCPD_CONF_FILE); /* prevent poll timeout overflow */ if (server_config.auto_time > INT_MAX / 1000) server_config.auto_time = INT_MAX / 1000; /* Make sure fd 0,1,2 are open */ bb_sanitize_stdio(); /* Create pidfile */ write_pidfile(server_config.pidfile); /* if (!..) bb_perror_msg("can't create pidfile %s", pidfile); */ bb_error_msg("started, v"BB_VER); option = udhcp_find_option(server_config.options, DHCP_LEASE_TIME); server_config.max_lease_sec = DEFAULT_LEASE_TIME; if (option) { move_from_unaligned32(server_config.max_lease_sec, option->data + OPT_DATA); server_config.max_lease_sec = ntohl(server_config.max_lease_sec); } /* Sanity check */ num_ips = server_config.end_ip - server_config.start_ip + 1; if (server_config.max_leases > num_ips) { bb_error_msg("max_leases=%u is too big, setting to %u", (unsigned)server_config.max_leases, num_ips); server_config.max_leases = num_ips; } /* this sets g_leases */ SET_PTR_TO_GLOBALS(xzalloc(server_config.max_leases * sizeof(g_leases[0]))); read_leases(server_config.lease_file); if (udhcp_read_interface(server_config.interface, &server_config.ifindex, (server_config.server_nip == 0 ? &server_config.server_nip : NULL), server_config.server_mac) ) { retval = 1; goto ret; } /* Setup the signal pipe */ udhcp_sp_setup(); continue_with_autotime: timeout_end = monotonic_sec() + server_config.auto_time; while (1) { /* loop until universe collapses */ struct pollfd pfds[2]; struct dhcp_packet packet; int bytes; int tv; uint8_t *server_id_opt; uint8_t *requested_ip_opt; uint32_t requested_nip = requested_nip; /* for compiler */ uint32_t static_lease_nip; struct dyn_lease *lease, fake_lease; if (server_socket < 0) { server_socket = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT, server_config.interface); } udhcp_sp_fd_set(pfds, server_socket); new_tv: tv = -1; if (server_config.auto_time) { tv = timeout_end - monotonic_sec(); if (tv <= 0) { write_leases: write_leases(); goto continue_with_autotime; } tv *= 1000; } /* Block here waiting for either signal or packet */ retval = poll(pfds, 2, tv); if (retval <= 0) { if (retval == 0) goto write_leases; if (errno == EINTR) goto new_tv; /* < 0 and not EINTR: should not happen */ bb_perror_msg_and_die("poll"); } if (pfds[0].revents) switch (udhcp_sp_read()) { case SIGUSR1: bb_error_msg("received %s", "SIGUSR1"); write_leases(); /* why not just reset the timeout, eh */ goto continue_with_autotime; case SIGTERM: bb_error_msg("received %s", "SIGTERM"); write_leases(); goto ret0; } /* Is it a packet? */ if (!pfds[1].revents) continue; /* no */ /* Note: we do not block here, we block on poll() instead. * Blocking here would prevent SIGTERM from working: * socket read inside this call is restarted on caught signals. */ bytes = udhcp_recv_kernel_packet(&packet, server_socket); if (bytes < 0) { /* bytes can also be -2 ("bad packet data") */ if (bytes == -1 && errno != EINTR) { log1("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO); close(server_socket); server_socket = -1; } continue; } if (packet.hlen != 6) { bb_error_msg("MAC length != 6, ignoring packet"); continue; } if (packet.op != BOOTREQUEST) { bb_error_msg("not a REQUEST, ignoring packet"); continue; } state = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE); if (state == NULL || state[0] < DHCP_MINTYPE || state[0] > DHCP_MAXTYPE) { bb_error_msg("no or bad message type option, ignoring packet"); continue; } /* Get SERVER_ID if present */ server_id_opt = udhcp_get_option32(&packet, DHCP_SERVER_ID); if (server_id_opt) { uint32_t server_id_network_order; move_from_unaligned32(server_id_network_order, server_id_opt); if (server_id_network_order != server_config.server_nip) { /* client talks to somebody else */ log1("server ID doesn't match, ignoring"); continue; } } /* Look for a static/dynamic lease */ static_lease_nip = get_static_nip_by_mac(server_config.static_leases, &packet.chaddr); if (static_lease_nip) { bb_error_msg("found static lease: %x", static_lease_nip); memcpy(&fake_lease.lease_mac, &packet.chaddr, 6); fake_lease.lease_nip = static_lease_nip; fake_lease.expires = 0; lease = &fake_lease; } else { lease = find_lease_by_mac(packet.chaddr); } /* Get REQUESTED_IP if present */ requested_ip_opt = udhcp_get_option32(&packet, DHCP_REQUESTED_IP); if (requested_ip_opt) { move_from_unaligned32(requested_nip, requested_ip_opt); } switch (state[0]) { case DHCPDISCOVER: log1("received %s", "DISCOVER"); send_offer(&packet, static_lease_nip, lease, requested_ip_opt, arpping_ms); break; case DHCPREQUEST: log1("received %s", "REQUEST"); /* RFC 2131: o DHCPREQUEST generated during SELECTING state: Client inserts the address of the selected server in 'server identifier', 'ciaddr' MUST be zero, 'requested IP address' MUST be filled in with the yiaddr value from the chosen DHCPOFFER. Note that the client may choose to collect several DHCPOFFER messages and select the "best" offer. The client indicates its selection by identifying the offering server in the DHCPREQUEST message. If the client receives no acceptable offers, the client may choose to try another DHCPDISCOVER message. Therefore, the servers may not receive a specific DHCPREQUEST from which they can decide whether or not the client has accepted the offer. o DHCPREQUEST generated during INIT-REBOOT state: 'server identifier' MUST NOT be filled in, 'requested IP address' option MUST be filled in with client's notion of its previously assigned address. 'ciaddr' MUST be zero. The client is seeking to verify a previously allocated, cached configuration. Server SHOULD send a DHCPNAK message to the client if the 'requested IP address' is incorrect, or is on the wrong network. Determining whether a client in the INIT-REBOOT state is on the correct network is done by examining the contents of 'giaddr', the 'requested IP address' option, and a database lookup. If the DHCP server detects that the client is on the wrong net (i.e., the result of applying the local subnet mask or remote subnet mask (if 'giaddr' is not zero) to 'requested IP address' option value doesn't match reality), then the server SHOULD send a DHCPNAK message to the client. If the network is correct, then the DHCP server should check if the client's notion of its IP address is correct. If not, then the server SHOULD send a DHCPNAK message to the client. If the DHCP server has no record of this client, then it MUST remain silent, and MAY output a warning to the network administrator. This behavior is necessary for peaceful coexistence of non- communicating DHCP servers on the same wire. If 'giaddr' is 0x0 in the DHCPREQUEST message, the client is on the same subnet as the server. The server MUST broadcast the DHCPNAK message to the 0xffffffff broadcast address because the client may not have a correct network address or subnet mask, and the client may not be answering ARP requests. If 'giaddr' is set in the DHCPREQUEST message, the client is on a different subnet. The server MUST set the broadcast bit in the DHCPNAK, so that the relay agent will broadcast the DHCPNAK to the client, because the client may not have a correct network address or subnet mask, and the client may not be answering ARP requests. o DHCPREQUEST generated during RENEWING state: 'server identifier' MUST NOT be filled in, 'requested IP address' option MUST NOT be filled in, 'ciaddr' MUST be filled in with client's IP address. In this situation, the client is completely configured, and is trying to extend its lease. This message will be unicast, so no relay agents will be involved in its transmission. Because 'giaddr' is therefore not filled in, the DHCP server will trust the value in 'ciaddr', and use it when replying to the client. A client MAY choose to renew or extend its lease prior to T1. The server may choose not to extend the lease (as a policy decision by the network administrator), but should return a DHCPACK message regardless. o DHCPREQUEST generated during REBINDING state: 'server identifier' MUST NOT be filled in, 'requested IP address' option MUST NOT be filled in, 'ciaddr' MUST be filled in with client's IP address. In this situation, the client is completely configured, and is trying to extend its lease. This message MUST be broadcast to the 0xffffffff IP broadcast address. The DHCP server SHOULD check 'ciaddr' for correctness before replying to the DHCPREQUEST. The DHCPREQUEST from a REBINDING client is intended to accommodate sites that have multiple DHCP servers and a mechanism for maintaining consistency among leases managed by multiple servers. A DHCP server MAY extend a client's lease only if it has local administrative authority to do so. */ if (!requested_ip_opt) { requested_nip = packet.ciaddr; if (requested_nip == 0) { log1("no requested IP and no ciaddr, ignoring"); break; } } if (lease && requested_nip == lease->lease_nip) { /* client requested or configured IP matches the lease. * ACK it, and bump lease expiration time. */ send_ACK(&packet, lease->lease_nip); break; } /* No lease for this MAC, or lease IP != requested IP */ if (server_id_opt /* client is in SELECTING state */ || requested_ip_opt /* client is in INIT-REBOOT state */ ) { /* "No, we don't have this IP for you" */ send_NAK(&packet); } /* else: client is in RENEWING or REBINDING, do not answer */ break; case DHCPDECLINE: /* RFC 2131: * "If the server receives a DHCPDECLINE message, * the client has discovered through some other means * that the suggested network address is already * in use. The server MUST mark the network address * as not available and SHOULD notify the local * sysadmin of a possible configuration problem." * * SERVER_ID must be present, * REQUESTED_IP must be present, * chaddr must be filled in, * ciaddr must be 0 (we do not check this) */ log1("received %s", "DECLINE"); if (server_id_opt && requested_ip_opt && lease /* chaddr matches this lease */ && requested_nip == lease->lease_nip ) { memset(lease->lease_mac, 0, sizeof(lease->lease_mac)); lease->expires = time(NULL) + server_config.decline_time; } break; case DHCPRELEASE: /* "Upon receipt of a DHCPRELEASE message, the server * marks the network address as not allocated." * * SERVER_ID must be present, * REQUESTED_IP must not be present (we do not check this), * chaddr must be filled in, * ciaddr must be filled in */ log1("received %s", "RELEASE"); if (server_id_opt && lease /* chaddr matches this lease */ && packet.ciaddr == lease->lease_nip ) { lease->expires = time(NULL); } break; case DHCPINFORM: log1("received %s", "INFORM"); send_inform(&packet); break; } } ret0: retval = 0; ret: /*if (server_config.pidfile) - server_config.pidfile is never NULL */ remove_pidfile(server_config.pidfile); return retval; }
165,226
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sample_hbp_handler(struct perf_event *bp, int nmi, struct perf_sample_data *data, struct pt_regs *regs) { printk(KERN_INFO "%s value is changed\n", ksym_name); dump_stack(); printk(KERN_INFO "Dump stack from sample_hbp_handler\n"); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static void sample_hbp_handler(struct perf_event *bp, int nmi, static void sample_hbp_handler(struct perf_event *bp, struct perf_sample_data *data, struct pt_regs *regs) { printk(KERN_INFO "%s value is changed\n", ksym_name); dump_stack(); printk(KERN_INFO "Dump stack from sample_hbp_handler\n"); }
165,845
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: char * exif_dump_data(int *dump_free, int format, int components, int length, int motorola_intel, char *value_ptr TSRMLS_DC) /* {{{ */ { char *dump; int len; *dump_free = 0; if (format == TAG_FMT_STRING) { return value_ptr ? value_ptr : "<no data>"; } if (format == TAG_FMT_UNDEFINED) { return "<undefined>\n"; } if (format == TAG_FMT_IFD) { return ""; } if (format == TAG_FMT_SINGLE || format == TAG_FMT_DOUBLE) { return "<not implemented>"; } *dump_free = 1; if (components > 1) { len = spprintf(&dump, 0, "(%d,%d) {", components, length); } else { len = spprintf(&dump, 0, "{"); } while(components > 0) { switch(format) { case TAG_FMT_BYTE: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: case TAG_FMT_SBYTE: dump = erealloc(dump, len + 4 + 1); snprintf(dump + len, 4 + 1, "0x%02X", *value_ptr); len += 4; value_ptr++; break; case TAG_FMT_USHORT: case TAG_FMT_SSHORT: dump = erealloc(dump, len + 6 + 1); snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get16s(value_ptr, motorola_intel)); len += 6; value_ptr += 2; break; case TAG_FMT_ULONG: case TAG_FMT_SLONG: dump = erealloc(dump, len + 6 + 1); snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get32s(value_ptr, motorola_intel)); len += 6; value_ptr += 4; break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: dump = erealloc(dump, len + 13 + 1); snprintf(dump + len, 13 + 1, "0x%04X/0x%04X", php_ifd_get32s(value_ptr, motorola_intel), php_ifd_get32s(value_ptr+4, motorola_intel)); len += 13; value_ptr += 8; break; } if (components > 0) { dump = erealloc(dump, len + 2 + 1); snprintf(dump + len, 2 + 1, ", "); len += 2; components--; } else{ break; } } dump = erealloc(dump, len + 1 + 1); snprintf(dump + len, 1 + 1, "}"); return dump; } /* }}} */ #endif /* {{{ exif_convert_any_format * Evaluate number, be it int, rational, or float from directory. */ static double exif_convert_any_format(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return (double)php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (double)php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return (signed short)php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (double)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return *(double *)value; } return 0; } /* }}} */ /* {{{ exif_convert_any_to_int * Evaluate number, be it int, rational, or float from directory. */ static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (size_t)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return (size_t)*(double *)value; } return 0; } /* }}} */ /* {{{ struct image_info_value, image_info_list */ #ifndef WORD #define WORD unsigned short #endif #ifndef DWORD #define DWORD unsigned int #endif typedef struct { int num; int den; } signed_rational; typedef struct { unsigned int num; unsigned int den; } unsigned_rational; typedef union _image_info_value { char *s; unsigned u; int i; float f; double d; signed_rational sr; unsigned_rational ur; union _image_info_value *list; } image_info_value; typedef struct { WORD tag; WORD format; DWORD length; DWORD dummy; /* value ptr of tiff directory entry */ char *name; image_info_value value; } image_info_data; typedef struct { int count; image_info_data *list; } image_info_list; /* }}} */ /* {{{ exif_get_sectionname Returns the name of a section */ #define SECTION_FILE 0 #define SECTION_COMPUTED 1 #define SECTION_ANY_TAG 2 #define SECTION_IFD0 3 #define SECTION_THUMBNAIL 4 #define SECTION_COMMENT 5 #define SECTION_APP0 6 #define SECTION_EXIF 7 #define SECTION_FPIX 8 #define SECTION_GPS 9 #define SECTION_INTEROP 10 #define SECTION_APP12 11 #define SECTION_WINXP 12 #define SECTION_MAKERNOTE 13 #define SECTION_COUNT 14 #define FOUND_FILE (1<<SECTION_FILE) #define FOUND_COMPUTED (1<<SECTION_COMPUTED) #define FOUND_ANY_TAG (1<<SECTION_ANY_TAG) #define FOUND_IFD0 (1<<SECTION_IFD0) #define FOUND_THUMBNAIL (1<<SECTION_THUMBNAIL) #define FOUND_COMMENT (1<<SECTION_COMMENT) #define FOUND_APP0 (1<<SECTION_APP0) #define FOUND_EXIF (1<<SECTION_EXIF) #define FOUND_FPIX (1<<SECTION_FPIX) #define FOUND_GPS (1<<SECTION_GPS) #define FOUND_INTEROP (1<<SECTION_INTEROP) #define FOUND_APP12 (1<<SECTION_APP12) #define FOUND_WINXP (1<<SECTION_WINXP) #define FOUND_MAKERNOTE (1<<SECTION_MAKERNOTE) static char *exif_get_sectionname(int section) { switch(section) { case SECTION_FILE: return "FILE"; case SECTION_COMPUTED: return "COMPUTED"; case SECTION_ANY_TAG: return "ANY_TAG"; case SECTION_IFD0: return "IFD0"; case SECTION_THUMBNAIL: return "THUMBNAIL"; case SECTION_COMMENT: return "COMMENT"; case SECTION_APP0: return "APP0"; case SECTION_EXIF: return "EXIF"; case SECTION_FPIX: return "FPIX"; case SECTION_GPS: return "GPS"; case SECTION_INTEROP: return "INTEROP"; case SECTION_APP12: return "APP12"; case SECTION_WINXP: return "WINXP"; case SECTION_MAKERNOTE: return "MAKERNOTE"; } return ""; } static tag_table_type exif_get_tag_table(int section) { switch(section) { case SECTION_FILE: return &tag_table_IFD[0]; case SECTION_COMPUTED: return &tag_table_IFD[0]; case SECTION_ANY_TAG: return &tag_table_IFD[0]; case SECTION_IFD0: return &tag_table_IFD[0]; case SECTION_THUMBNAIL: return &tag_table_IFD[0]; case SECTION_COMMENT: return &tag_table_IFD[0]; case SECTION_APP0: return &tag_table_IFD[0]; case SECTION_EXIF: return &tag_table_IFD[0]; case SECTION_FPIX: return &tag_table_IFD[0]; case SECTION_GPS: return &tag_table_GPS[0]; case SECTION_INTEROP: return &tag_table_IOP[0]; case SECTION_APP12: return &tag_table_IFD[0]; case SECTION_WINXP: return &tag_table_IFD[0]; } return &tag_table_IFD[0]; } /* }}} */ /* {{{ exif_get_sectionlist Return list of sectionnames specified by sectionlist. Return value must be freed */ static char *exif_get_sectionlist(int sectionlist TSRMLS_DC) { int i, len, ml = 0; char *sections; for(i=0; i<SECTION_COUNT; i++) { ml += strlen(exif_get_sectionname(i))+2; } sections = safe_emalloc(ml, 1, 1); sections[0] = '\0'; len = 0; for(i=0; i<SECTION_COUNT; i++) { if (sectionlist&(1<<i)) { snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i)); len = strlen(sections); } } if (len>2) sections[len-2] = '\0'; return sections; } /* }}} */ /* {{{ struct image_info_type This structure stores Exif header image elements in a simple manner Used to store camera data as extracted from the various ways that it can be stored in a nexif header */ typedef struct { int type; size_t size; uchar *data; } file_section; typedef struct { int count; file_section *list; } file_section_list; typedef struct { image_filetype filetype; size_t width, height; size_t size; size_t offset; char *data; } thumbnail_data; typedef struct { char *value; size_t size; int tag; } xp_field_type; typedef struct { int count; xp_field_type *list; } xp_field_list; /* This structure is used to store a section of a Jpeg file. */ typedef struct { php_stream *infile; char *FileName; time_t FileDateTime; size_t FileSize; image_filetype FileType; int Height, Width; int IsColor; char *make; char *model; float ApertureFNumber; float ExposureTime; double FocalplaneUnits; float CCDWidth; double FocalplaneXRes; size_t ExifImageWidth; float FocalLength; float Distance; int motorola_intel; /* 1 Motorola; 0 Intel */ char *UserComment; int UserCommentLength; char *UserCommentEncoding; char *encode_unicode; char *decode_unicode_be; char *decode_unicode_le; char *encode_jis; char *decode_jis_be; char *decode_jis_le; char *Copyright;/* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */ char *CopyrightPhotographer; char *CopyrightEditor; xp_field_list xp_fields; thumbnail_data Thumbnail; /* other */ int sections_found; /* FOUND_<marker> */ image_info_list info_list[SECTION_COUNT]; /* for parsing */ int read_thumbnail; int read_all; int ifd_nesting_level; /* internal */ file_section_list file; } image_info_type; /* }}} */ /* {{{ exif_error_docref */ static void exif_error_docref(const char *docref EXIFERR_DC, const image_info_type *ImageInfo, int type, const char *format, ...) { va_list args; va_start(args, format); #ifdef EXIF_DEBUG { char *buf; spprintf(&buf, 0, "%s(%d): %s", _file, _line, format); php_verror(docref, ImageInfo->FileName?ImageInfo->FileName:"", type, buf, args TSRMLS_CC); efree(buf); } #else php_verror(docref, ImageInfo->FileName?ImageInfo->FileName:"", type, format, args TSRMLS_CC); #endif va_end(args); } /* }}} */ /* {{{ jpeg_sof_info */ typedef struct { int bits_per_sample; size_t width; size_t height; int num_components; } jpeg_sof_info; /* }}} */ /* {{{ exif_file_sections_add Add a file_section to image_info returns the used block or -1. if size>0 and data == NULL buffer of size is allocated */ static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, uchar *data) { file_section *tmp; int count = ImageInfo->file.count; tmp = safe_erealloc(ImageInfo->file.list, (count+1), sizeof(file_section), 0); ImageInfo->file.list = tmp; ImageInfo->file.list[count].type = 0xFFFF; ImageInfo->file.list[count].data = NULL; ImageInfo->file.list[count].size = 0; ImageInfo->file.count = count+1; if (!size) { data = NULL; } else if (data == NULL) { data = safe_emalloc(size, 1, 0); } ImageInfo->file.list[count].type = type; ImageInfo->file.list[count].data = data; ImageInfo->file.list[count].size = size; return count; } /* }}} */ /* {{{ exif_file_sections_realloc Reallocate a file section returns 0 on success and -1 on failure */ static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size TSRMLS_DC) { void *tmp; /* This is not a malloc/realloc check. It is a plausibility check for the * function parameters (requirements engineering). */ if (section_index >= ImageInfo->file.count) { EXIF_ERRLOG_FSREALLOC(ImageInfo) return -1; } tmp = safe_erealloc(ImageInfo->file.list[section_index].data, 1, size, 0); ImageInfo->file.list[section_index].data = tmp; ImageInfo->file.list[section_index].size = size; return 0; } /* }}} */ /* {{{ exif_file_section_free Discard all file_sections in ImageInfo */ static int exif_file_sections_free(image_info_type *ImageInfo) { int i; if (ImageInfo->file.count) { for (i=0; i<ImageInfo->file.count; i++) { EFREE_IF(ImageInfo->file.list[i].data); } } EFREE_IF(ImageInfo->file.list); ImageInfo->file.count = 0; return TRUE; } /* }}} */ /* {{{ exif_iif_add_value Add a value to image_info */ static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel TSRMLS_DC) { size_t idex; void *vptr; image_info_value *info_value; image_info_data *info_data; image_info_data *list; if (length < 0) { return; } list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = tag; info_data->format = format; info_data->length = length; info_data->name = estrdup(name); info_value = &info_data->value; switch (format) { case TAG_FMT_STRING: if (value) { length = php_strnlen(value, length); info_value->s = estrndup(value, length); info_data->length = length; } else { info_data->length = 0; info_value->s = estrdup(""); } break; default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */ case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */ if (!length) break; case TAG_FMT_UNDEFINED: if (value) { /* do not recompute length here */ info_value->s = estrndup(value, length); info_data->length = length; } else { info_data->length = 0; info_value->s = estrdup(""); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: if (length==0) { break; } else if (length>1) { info_value->list = safe_emalloc(length, sizeof(image_info_value), 0); } else { info_value = &info_data->value; } for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) { if (length>1) { info_value = &info_data->value.list[idex]; } switch (format) { case TAG_FMT_USHORT: info_value->u = php_ifd_get16u(vptr, motorola_intel); break; case TAG_FMT_ULONG: info_value->u = php_ifd_get32u(vptr, motorola_intel); break; case TAG_FMT_URATIONAL: info_value->ur.num = php_ifd_get32u(vptr, motorola_intel); info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SSHORT: info_value->i = php_ifd_get16s(vptr, motorola_intel); break; case TAG_FMT_SLONG: info_value->i = php_ifd_get32s(vptr, motorola_intel); break; case TAG_FMT_SRATIONAL: info_value->sr.num = php_ifd_get32u(vptr, motorola_intel); info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type single"); #endif info_value->f = *(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type double"); #endif info_value->d = *(double *)value; break; } } } image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* }}} */ /* {{{ exif_iif_add_tag Add a tag from IFD to image_info */ static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value TSRMLS_DC) { exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, image_info->motorola_intel TSRMLS_CC); } /* }}} */ /* {{{ exif_iif_add_int Add an int value to image_info */ static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_SLONG; info_data->length = 1; info_data->name = estrdup(name); info_data->value.i = value; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* }}} */ /* {{{ exif_iif_add_str Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; if (value) { list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_STRING; info_data->length = 1; info_data->name = estrdup(name); info_data->value.s = estrdup(value); image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* }}} */ /* {{{ exif_iif_add_fmt Add a format string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name TSRMLS_DC, char *value, ...) { char *tmp; va_list arglist; va_start(arglist, value); if (value) { vspprintf(&tmp, 0, value, arglist); exif_iif_add_str(image_info, section_index, name, tmp TSRMLS_CC); efree(tmp); } va_end(arglist); } /* }}} */ /* {{{ exif_iif_add_str Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; if (value) { list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_UNDEFINED; info_data->length = length; info_data->name = estrdup(name); info_data->value.s = safe_emalloc(length, 1, 1); memcpy(info_data->value.s, value, length); info_data->value.s[length] = 0; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* }}} */ /* {{{ exif_iif_free Free memory allocated for image_info */ static void exif_iif_free(image_info_type *image_info, int section_index) { int i; void *f; /* faster */ if (image_info->info_list[section_index].count) { for (i=0; i < image_info->info_list[section_index].count; i++) { if ((f=image_info->info_list[section_index].list[i].name) != NULL) { efree(f); } switch(image_info->info_list[section_index].list[i].format) { case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */ if (image_info->info_list[section_index].list[i].length<1) break; default: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: if ((f=image_info->info_list[section_index].list[i].value.s) != NULL) { efree(f); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: /* nothing to do here */ if (image_info->info_list[section_index].list[i].length > 1) { if ((f=image_info->info_list[section_index].list[i].value.list) != NULL) { efree(f); } } break; } } } EFREE_IF(image_info->info_list[section_index].list); } /* }}} */ /* {{{ add_assoc_image_info * Add image_info to associative array value. */ static void add_assoc_image_info(zval *value, int sub_array, image_info_type *image_info, int section_index TSRMLS_DC) { char buffer[64], *val, *name, uname[64]; int i, ap, l, b, idx=0, unknown=0; #ifdef EXIF_DEBUG int info_tag; #endif image_info_value *info_value; image_info_data *info_data; zval *tmpi, *array = NULL; #ifdef EXIF_DEBUG /* php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Adding %d infos from section %s", image_info->info_list[section_index].count, exif_get_sectionname(section_index));*/ #endif if (image_info->info_list[section_index].count) { if (sub_array) { MAKE_STD_ZVAL(tmpi); array_init(tmpi); } else { tmpi = value; } for(i=0; i<image_info->info_list[section_index].count; i++) { info_data = &image_info->info_list[section_index].list[i]; #ifdef EXIF_DEBUG info_tag = info_data->tag; /* conversion */ #endif info_value = &info_data->value; if (!(name = info_data->name)) { snprintf(uname, sizeof(uname), "%d", unknown++); name = uname; } #ifdef EXIF_DEBUG /* php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Adding infos: tag(0x%04X,%12s,L=0x%04X): %s", info_tag, exif_get_tagname(info_tag, buffer, -12, exif_get_tag_table(section_index) TSRMLS_CC), info_data->length, info_data->format==TAG_FMT_STRING?(info_value&&info_value->s?info_value->s:"<no data>"):exif_get_tagformat(info_data->format));*/ #endif if (info_data->length==0) { add_assoc_null(tmpi, name); } else { switch (info_data->format) { default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ case TAG_FMT_BYTE: case TAG_FMT_SBYTE: case TAG_FMT_UNDEFINED: if (!info_value->s) { add_assoc_stringl(tmpi, name, "", 0, 1); } else { add_assoc_stringl(tmpi, name, info_value->s, info_data->length, 1); } break; case TAG_FMT_STRING: if (!(val = info_value->s)) { val = ""; } if (section_index==SECTION_COMMENT) { add_index_string(tmpi, idx++, val, 1); } else { add_assoc_string(tmpi, name, val, 1); } break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: /*case TAG_FMT_BYTE: case TAG_FMT_SBYTE:*/ case TAG_FMT_USHORT: case TAG_FMT_SSHORT: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: case TAG_FMT_ULONG: case TAG_FMT_SLONG: /* now the rest, first see if it becomes an array */ if ((l = info_data->length) > 1) { array = NULL; MAKE_STD_ZVAL(array); array_init(array); } for(ap=0; ap<l; ap++) { if (l>1) { info_value = &info_data->value.list[ap]; } switch (info_data->format) { case TAG_FMT_BYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { add_index_long(array, b, (int)(info_value->s[b])); } break; } case TAG_FMT_USHORT: case TAG_FMT_ULONG: if (l==1) { add_assoc_long(tmpi, name, (int)info_value->u); } else { add_index_long(array, ap, (int)info_value->u); } break; case TAG_FMT_URATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->ur.num, info_value->ur.den); if (l==1) { add_assoc_string(tmpi, name, buffer, 1); } else { add_index_string(array, ap, buffer, 1); } break; case TAG_FMT_SBYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { add_index_long(array, ap, (int)info_value->s[b]); } break; } case TAG_FMT_SSHORT: case TAG_FMT_SLONG: if (l==1) { add_assoc_long(tmpi, name, info_value->i); } else { add_index_long(array, ap, info_value->i); } break; case TAG_FMT_SRATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den); if (l==1) { add_assoc_string(tmpi, name, buffer, 1); } else { add_index_string(array, ap, buffer, 1); } break; case TAG_FMT_SINGLE: if (l==1) { add_assoc_double(tmpi, name, info_value->f); } else { add_index_double(array, ap, info_value->f); } break; case TAG_FMT_DOUBLE: if (l==1) { add_assoc_double(tmpi, name, info_value->d); } else { add_index_double(array, ap, info_value->d); } break; } info_value = &info_data->value.list[ap]; } if (l>1) { add_assoc_zval(tmpi, name, array); } break; } } } if (sub_array) { add_assoc_zval(value, exif_get_sectionname(section_index), tmpi); } } } /* }}} */ /* {{{ Markers JPEG markers consist of one or more 0xFF bytes, followed by a marker code byte (which is not an FF). Here are the marker codes of interest in this program. (See jdmarker.c for a more complete list.) */ #define M_TEM 0x01 /* temp for arithmetic coding */ #define M_RES 0x02 /* reserved */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_DHT 0xC4 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_JPEG 0x08 /* reserved for extensions */ #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_DAC 0xCC /* arithmetic table */ #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_RST0 0xD0 /* restart segment */ #define M_RST1 0xD1 #define M_RST2 0xD2 #define M_RST3 0xD3 #define M_RST4 0xD4 #define M_RST5 0xD5 #define M_RST6 0xD6 #define M_RST7 0xD7 #define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */ #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_DQT 0xDB #define M_DNL 0xDC #define M_DRI 0xDD #define M_DHP 0xDE #define M_EXP 0xDF #define M_APP0 0xE0 /* JPEG: 'JFIFF' AND (additional 'JFXX') */ #define M_EXIF 0xE1 /* Exif Attribute Information */ #define M_APP2 0xE2 /* Flash Pix Extension Data? */ #define M_APP3 0xE3 #define M_APP4 0xE4 #define M_APP5 0xE5 #define M_APP6 0xE6 #define M_APP7 0xE7 #define M_APP8 0xE8 #define M_APP9 0xE9 #define M_APP10 0xEA #define M_APP11 0xEB #define M_APP12 0xEC #define M_APP13 0xED /* IPTC International Press Telecommunications Council */ #define M_APP14 0xEE /* Software, Copyright? */ #define M_APP15 0xEF #define M_JPG0 0xF0 #define M_JPG1 0xF1 #define M_JPG2 0xF2 #define M_JPG3 0xF3 #define M_JPG4 0xF4 #define M_JPG5 0xF5 #define M_JPG6 0xF6 #define M_JPG7 0xF7 #define M_JPG8 0xF8 #define M_JPG9 0xF9 #define M_JPG10 0xFA #define M_JPG11 0xFB #define M_JPG12 0xFC #define M_JPG13 0xFD #define M_COM 0xFE /* COMment */ #define M_PSEUDO 0x123 /* Extra value. */ /* }}} */ /* {{{ jpeg2000 markers */ /* Markers x30 - x3F do not have a segment */ /* Markers x00, x01, xFE, xC0 - xDF ISO/IEC 10918-1 -> M_<xx> */ /* Markers xF0 - xF7 ISO/IEC 10918-3 */ /* Markers xF7 - xF8 ISO/IEC 14495-1 */ /* XY=Main/Tile-header:(R:required, N:not_allowed, O:optional, L:last_marker) */ #define JC_SOC 0x4F /* NN, Start of codestream */ #define JC_SIZ 0x51 /* RN, Image and tile size */ #define JC_COD 0x52 /* RO, Codeing style defaulte */ #define JC_COC 0x53 /* OO, Coding style component */ #define JC_TLM 0x55 /* ON, Tile part length main header */ #define JC_PLM 0x57 /* ON, Packet length main header */ #define JC_PLT 0x58 /* NO, Packet length tile part header */ #define JC_QCD 0x5C /* RO, Quantization default */ #define JC_QCC 0x5D /* OO, Quantization component */ #define JC_RGN 0x5E /* OO, Region of interest */ #define JC_POD 0x5F /* OO, Progression order default */ #define JC_PPM 0x60 /* ON, Packed packet headers main header */ #define JC_PPT 0x61 /* NO, Packet packet headers tile part header */ #define JC_CME 0x64 /* OO, Comment: "LL E <text>" E=0:binary, E=1:ascii */ #define JC_SOT 0x90 /* NR, Start of tile */ #define JC_SOP 0x91 /* NO, Start of packeter default */ #define JC_EPH 0x92 /* NO, End of packet header */ #define JC_SOD 0x93 /* NL, Start of data */ #define JC_EOC 0xD9 /* NN, End of codestream */ /* }}} */ /* {{{ exif_process_COM Process a COM marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ static void exif_process_COM (image_info_type *image_info, char *value, size_t length TSRMLS_DC) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2 TSRMLS_CC); } /* }}} */ /* {{{ exif_process_CME Process a CME marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ #ifdef EXIF_JPEG2000 static void exif_process_CME (image_info_type *image_info, char *value, size_t length TSRMLS_DC) { if (length>3) { switch(value[2]) { case 0: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, length, value TSRMLS_CC); break; case 1: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length, value); break; default: php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Undefined JPEG2000 comment encoding"); break; } } else { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, 0, NULL); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "JPEG2000 comment section too small"); } } #endif /* }}} */ /* {{{ exif_process_SOFn * Process a SOFn marker. This is useful for the image dimensions */ static void exif_process_SOFn (uchar *Data, int marker, jpeg_sof_info *result) { /* 0xFF SOSn SectLen(2) Bits(1) Height(2) Width(2) Channels(1) 3*Channels (1) */ result->bits_per_sample = Data[2]; result->height = php_jpg_get16(Data+3); result->width = php_jpg_get16(Data+5); result->num_components = Data[7]; /* switch (marker) { case M_SOF0: process = "Baseline"; break; case M_SOF1: process = "Extended sequential"; break; case M_SOF2: process = "Progressive"; break; case M_SOF3: process = "Lossless"; break; case M_SOF5: process = "Differential sequential"; break; case M_SOF6: process = "Differential progressive"; break; case M_SOF7: process = "Differential lossless"; break; case M_SOF9: process = "Extended sequential, arithmetic coding"; break; case M_SOF10: process = "Progressive, arithmetic coding"; break; case M_SOF11: process = "Lossless, arithmetic coding"; break; case M_SOF13: process = "Differential sequential, arithmetic coding"; break; case M_SOF14: process = "Differential progressive, arithmetic coding"; break; case M_SOF15: process = "Differential lossless, arithmetic coding"; break; default: process = "Unknown"; break; }*/ } /* }}} */ /* forward declarations */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC); static int exif_process_IFD_TAG( image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC); /* {{{ exif_get_markername Get name of marker */ #ifdef EXIF_DEBUG static char * exif_get_markername(int marker) { switch(marker) { case 0xC0: return "SOF0"; case 0xC1: return "SOF1"; case 0xC2: return "SOF2"; case 0xC3: return "SOF3"; case 0xC4: return "DHT"; case 0xC5: return "SOF5"; case 0xC6: return "SOF6"; case 0xC7: return "SOF7"; case 0xC9: return "SOF9"; case 0xCA: return "SOF10"; case 0xCB: return "SOF11"; case 0xCD: return "SOF13"; case 0xCE: return "SOF14"; case 0xCF: return "SOF15"; case 0xD8: return "SOI"; case 0xD9: return "EOI"; case 0xDA: return "SOS"; case 0xDB: return "DQT"; case 0xDC: return "DNL"; case 0xDD: return "DRI"; case 0xDE: return "DHP"; case 0xDF: return "EXP"; case 0xE0: return "APP0"; case 0xE1: return "EXIF"; case 0xE2: return "FPIX"; case 0xE3: return "APP3"; case 0xE4: return "APP4"; case 0xE5: return "APP5"; case 0xE6: return "APP6"; case 0xE7: return "APP7"; case 0xE8: return "APP8"; case 0xE9: return "APP9"; case 0xEA: return "APP10"; case 0xEB: return "APP11"; case 0xEC: return "APP12"; case 0xED: return "APP13"; case 0xEE: return "APP14"; case 0xEF: return "APP15"; case 0xF0: return "JPG0"; case 0xFD: return "JPG13"; case 0xFE: return "COM"; case 0x01: return "TEM"; } return "Unknown"; } #endif /* }}} */ /* {{{ proto string exif_tagname(index) Get headername for index or false if not defined */ PHP_FUNCTION(exif_tagname) { long tag; char *szTemp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &tag) == FAILURE) { return; } szTemp = exif_get_tagname(tag, NULL, 0, tag_table_IFD TSRMLS_CC); if (tag < 0 || !szTemp || !szTemp[0]) { RETURN_FALSE; } RETURN_STRING(szTemp, 1) } /* }}} */ /* {{{ exif_ifd_make_value * Create a value for an ifd from an info_data pointer */ static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel TSRMLS_DC) { size_t byte_count; char *value_ptr, *data_ptr; size_t i; image_info_value *info_value; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; value_ptr = safe_emalloc(max(byte_count, 4), 1, 0); memset(value_ptr, 0, 4); if (!info_data->length) { return value_ptr; } if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE)) ) { memmove(value_ptr, info_data->value.s, byte_count); return value_ptr; } else if (info_data->format == TAG_FMT_BYTE) { *value_ptr = info_data->value.u; return value_ptr; } else if (info_data->format == TAG_FMT_SBYTE) { *value_ptr = info_data->value.i; return value_ptr; } else { data_ptr = value_ptr; for(i=0; i<info_data->length; i++) { if (info_data->length==1) { info_value = &info_data->value; } else { info_value = &info_data->value.list[i]; } switch(info_data->format) { case TAG_FMT_USHORT: php_ifd_set16u(data_ptr, info_value->u, motorola_intel); data_ptr += 2; break; case TAG_FMT_ULONG: php_ifd_set32u(data_ptr, info_value->u, motorola_intel); data_ptr += 4; break; case TAG_FMT_SSHORT: php_ifd_set16u(data_ptr, info_value->i, motorola_intel); data_ptr += 2; break; case TAG_FMT_SLONG: php_ifd_set32u(data_ptr, info_value->i, motorola_intel); data_ptr += 4; break; case TAG_FMT_URATIONAL: php_ifd_set32u(data_ptr, info_value->sr.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SRATIONAL: php_ifd_set32u(data_ptr, info_value->ur.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SINGLE: memmove(data_ptr, &info_value->f, 4); data_ptr += 4; break; case TAG_FMT_DOUBLE: memmove(data_ptr, &info_value->d, 8); data_ptr += 8; break; } } } return value_ptr; } /* }}} */ /* {{{ exif_thumbnail_build * Check and build thumbnail */ static void exif_thumbnail_build(image_info_type *ImageInfo TSRMLS_DC) { size_t new_size, new_move, new_value; char *new_data; void *value_ptr; int i, byte_count; image_info_list *info_list; image_info_data *info_data; #ifdef EXIF_DEBUG char tagname[64]; #endif if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) { return; /* ignore this call */ } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: filetype = %d", ImageInfo->Thumbnail.filetype); #endif switch(ImageInfo->Thumbnail.filetype) { default: case IMAGE_FILETYPE_JPEG: /* done */ break; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: info_list = &ImageInfo->info_list[SECTION_THUMBNAIL]; new_size = 8 + 2 + info_list->count * 12 + 4; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size of signature + directory(%d): 0x%02X", info_list->count, new_size); #endif new_value= new_size; /* offset for ifd values outside ifd directory */ for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; if (byte_count > 4) { new_size += byte_count; } } new_move = new_size; new_data = safe_erealloc(ImageInfo->Thumbnail.data, 1, ImageInfo->Thumbnail.size, new_size); ImageInfo->Thumbnail.data = new_data; memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size); ImageInfo->Thumbnail.size += new_size; /* fill in data */ if (ImageInfo->motorola_intel) { memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8); } else { memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8); } new_data += 8; php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel); new_data += 2; for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process tag(x%04X=%s): %s%s (%d bytes)", info_data->tag, exif_get_tagname(info_data->tag, tagname, -12, tag_table_IFD TSRMLS_CC), (info_data->length>1)&&info_data->format!=TAG_FMT_UNDEFINED&&info_data->format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(info_data->format), byte_count); #endif if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, TAG_FMT_ULONG, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, 1, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 8, new_move, ImageInfo->motorola_intel); } else { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel); value_ptr = exif_ifd_make_value(info_data, ImageInfo->motorola_intel TSRMLS_CC); if (byte_count <= 4) { memmove(new_data+8, value_ptr, 4); } else { php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: writing with value offset: 0x%04X + 0x%02X", new_value, byte_count); #endif memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count); new_value += byte_count; } efree(value_ptr); } new_data += 12; } memset(new_data, 0, 4); /* next ifd pointer */ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: created"); #endif break; } } /* }}} */ /* {{{ exif_thumbnail_extract * Grab the thumbnail, corrected */ static void exif_thumbnail_extract(image_info_type *ImageInfo, char *offset, size_t length TSRMLS_DC) { if (ImageInfo->Thumbnail.data) { exif_error_docref("exif_read_data#error_mult_thumb" EXIFERR_CC, ImageInfo, E_WARNING, "Multiple possible thumbnails"); return; /* Should not happen */ } if (!ImageInfo->read_thumbnail) { return; /* ignore this call */ } /* according to exif2.1, the thumbnail is not supposed to be greater than 64K */ if (ImageInfo->Thumbnail.size >= 65536 || ImageInfo->Thumbnail.size <= 0 || ImageInfo->Thumbnail.offset <= 0 ) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Illegal thumbnail size/offset"); return; } /* Check to make sure we are not going to go past the ExifLength */ if ((ImageInfo->Thumbnail.offset + ImageInfo->Thumbnail.size) > length) { EXIF_ERRLOG_THUMBEOF(ImageInfo) return; } ImageInfo->Thumbnail.data = estrndup(offset + ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size); exif_thumbnail_build(ImageInfo TSRMLS_CC); } /* }}} */ /* {{{ exif_process_undefined * Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */ static int exif_process_undefined(char **result, char *value, size_t byte_count TSRMLS_DC) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. * estrndup does not return length */ if (byte_count) { (*result) = estrndup(value, byte_count); /* NULL @ byte_count!!! */ return byte_count+1; } return 0; } /* }}} */ /* {{{ exif_process_string_raw * Copy a string in Exif header to a character string returns length of allocated buffer if any. */ static int exif_process_string_raw(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ if (byte_count) { (*result) = safe_emalloc(byte_count, 1, 1); memcpy(*result, value, byte_count); (*result)[byte_count] = '\0'; return byte_count+1; } return 0; } /* }}} */ /* {{{ exif_process_string * Copy a string in Exif header to a character string and return length of allocated buffer if any. * In contrast to exif_process_string this function does always return a string buffer */ static int exif_process_string(char **result, char *value, size_t byte_count TSRMLS_DC) { /* we cannot use strlcpy - here the problem is that we cannot use strlen to * determin length of string and we cannot use strlcpy with len=byte_count+1 * because then we might get into an EXCEPTION if we exceed an allocated * memory page...so we use php_strnlen in conjunction with memcpy and add the NUL * char. * estrdup would sometimes allocate more memory and does not return length */ if ((byte_count=php_strnlen(value, byte_count)) > 0) { return exif_process_undefined(result, value, byte_count TSRMLS_CC); } (*result) = estrndup("", 1); /* force empty string */ return byte_count+1; } /* }}} */ /* {{{ exif_process_user_comment * Process UserComment in IFD. */ static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount TSRMLS_DC) { int a; char *decode; size_t len;; *pszEncoding = NULL; /* Copy the comment */ if (ByteCount>=8) { if (!memcmp(szValuePtr, "UNICODE\0", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, "\xFE\xFF", 2)) { decode = "UCS-2BE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) { decode = "UCS-2LE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), zend_multibyte_fetch_encoding(decode TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) { /* JIS should be tanslated to MB or we leave it to the user - leave it to the user */ *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_jis TSRMLS_CC), zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) { /* 8 NULL means undefined and should be ASCII... */ *pszEncoding = estrdup("UNDEFINED"); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount TSRMLS_CC); return strlen(*pszInfoPtr); } /* }}} */ /* {{{ exif_process_unicode * Process unicode field in IFD. */ static int exif_process_unicode(image_info_type *ImageInfo, xp_field_type *xp_field, int tag, char *szValuePtr, int ByteCount TSRMLS_DC) { xp_field->tag = tag; xp_field->value = NULL; /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)&xp_field->value, &xp_field->size, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_unicode_be : ImageInfo->decode_unicode_le TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount); } return xp_field->size; } /* }}} */ /* {{{ exif_process_IFD_in_MAKERNOTE * Process nested IFDs directories in Maker Note. */ static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement TSRMLS_DC) { int de, i=0, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) return FALSE; maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; break; case MN_OFFSET_GUESS: offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif offset_base = value_ptr + offset_diff; break; default: case MN_OFFSET_NORMAL: break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + x%04X*12 = x%04X > x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, IFDlength, displacement, section_index, 0, maker_note->tag_table TSRMLS_CC)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; } /* }}} */ /* {{{ exif_process_IFD_TAG * Process one of the nested IFDs directories. */ static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=NULL; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; #ifdef EXIF_DEBUG char *dump_data; int dump_free; #endif /* EXIF_DEBUG */ /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached"); return FALSE; } ImageInfo->ifd_nesting_level++; tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components); return FALSE; } byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format]; if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC)); return FALSE; } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; /* dir_entry is ImageInfo->file.list[sn].data+2+i*12 offset_base is ImageInfo->file.list[sn].data-dir_offset dir_entry - offset_base is dir_offset+2+i*12 */ if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* It is important to check for IMAGE_FILETYPE_TIFF * JPEG does not use absolute pointers instead its pointers are * relative to the start of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength); } return FALSE; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = safe_emalloc(byte_count, 1, 0); outside = value_ptr; } else { /* In most cases we only access a small range so * it is faster to use a static buffer there * BUT it offers also the possibility to have * pointers read without the need to free them * explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = php_stream_tell(ImageInfo->infile); php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET); fgot = php_stream_tell(ImageInfo->infile); if (fgot!=offset_val) { EFREE_IF(outside); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val); return FALSE; } fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count); php_stream_seek(ImageInfo->infile, fpos, SEEK_SET); if (fgot<byte_count) { EFREE_IF(outside); EXIF_ERRLOG_FILEEOF(ImageInfo) return FALSE; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; #ifdef EXIF_DEBUG dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data); if (dump_free) { efree(dump_data); } #endif if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ ImageInfo->CopyrightPhotographer = estrdup(value_ptr); ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1); spprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, value_ptr+length+1); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { ImageInfo->Copyright = estrndup(value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC); break; case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD"); } break; case TAG_MAKE: ImageInfo->make = estrndup(value_ptr, byte_count); break; case TAG_MODEL: ImageInfo->model = estrndup(value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF"); #endif ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS"); #endif ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY"); #endif ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer"); return FALSE; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) { return FALSE; } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index)); #endif } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC); EFREE_IF(outside); return TRUE; } /* }}} */ /* {{{ exif_process_IFD_in_JPEG * Process one of the nested IFDs directories. */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC) { int de; int NumDirEntries; int NextDirOffset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), IFDlength, IFDlength); #endif ImageInfo->sections_found |= FOUND_IFD0; NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index) TSRMLS_CC)) { return FALSE; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return TRUE; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size); #endif if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail ) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength TSRMLS_CC); } return TRUE; } else { return FALSE; } } return TRUE; } /* }}} */ /* {{{ exif_process_TIFF_in_JPEG Process a TIFF header in a JPEG file */ static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement TSRMLS_DC) { unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF alignment marker"); return; } /* Check the next two values for correctness. */ exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } } /* Check the next two values for correctness. */ exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } /* }}} */ Commit Message: CWE ID: CWE-119
char * exif_dump_data(int *dump_free, int format, int components, int length, int motorola_intel, char *value_ptr TSRMLS_DC) /* {{{ */ { char *dump; int len; *dump_free = 0; if (format == TAG_FMT_STRING) { return value_ptr ? value_ptr : "<no data>"; } if (format == TAG_FMT_UNDEFINED) { return "<undefined>\n"; } if (format == TAG_FMT_IFD) { return ""; } if (format == TAG_FMT_SINGLE || format == TAG_FMT_DOUBLE) { return "<not implemented>"; } *dump_free = 1; if (components > 1) { len = spprintf(&dump, 0, "(%d,%d) {", components, length); } else { len = spprintf(&dump, 0, "{"); } while(components > 0) { switch(format) { case TAG_FMT_BYTE: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: case TAG_FMT_SBYTE: dump = erealloc(dump, len + 4 + 1); snprintf(dump + len, 4 + 1, "0x%02X", *value_ptr); len += 4; value_ptr++; break; case TAG_FMT_USHORT: case TAG_FMT_SSHORT: dump = erealloc(dump, len + 6 + 1); snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get16s(value_ptr, motorola_intel)); len += 6; value_ptr += 2; break; case TAG_FMT_ULONG: case TAG_FMT_SLONG: dump = erealloc(dump, len + 6 + 1); snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get32s(value_ptr, motorola_intel)); len += 6; value_ptr += 4; break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: dump = erealloc(dump, len + 13 + 1); snprintf(dump + len, 13 + 1, "0x%04X/0x%04X", php_ifd_get32s(value_ptr, motorola_intel), php_ifd_get32s(value_ptr+4, motorola_intel)); len += 13; value_ptr += 8; break; } if (components > 0) { dump = erealloc(dump, len + 2 + 1); snprintf(dump + len, 2 + 1, ", "); len += 2; components--; } else{ break; } } dump = erealloc(dump, len + 1 + 1); snprintf(dump + len, 1 + 1, "}"); return dump; } /* }}} */ #endif /* {{{ exif_convert_any_format * Evaluate number, be it int, rational, or float from directory. */ static double exif_convert_any_format(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return (double)php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (double)php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return (signed short)php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (double)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return *(double *)value; } return 0; } /* }}} */ /* {{{ exif_convert_any_to_int * Evaluate number, be it int, rational, or float from directory. */ static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (size_t)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return (size_t)*(double *)value; } return 0; } /* }}} */ /* {{{ struct image_info_value, image_info_list */ #ifndef WORD #define WORD unsigned short #endif #ifndef DWORD #define DWORD unsigned int #endif typedef struct { int num; int den; } signed_rational; typedef struct { unsigned int num; unsigned int den; } unsigned_rational; typedef union _image_info_value { char *s; unsigned u; int i; float f; double d; signed_rational sr; unsigned_rational ur; union _image_info_value *list; } image_info_value; typedef struct { WORD tag; WORD format; DWORD length; DWORD dummy; /* value ptr of tiff directory entry */ char *name; image_info_value value; } image_info_data; typedef struct { int count; image_info_data *list; } image_info_list; /* }}} */ /* {{{ exif_get_sectionname Returns the name of a section */ #define SECTION_FILE 0 #define SECTION_COMPUTED 1 #define SECTION_ANY_TAG 2 #define SECTION_IFD0 3 #define SECTION_THUMBNAIL 4 #define SECTION_COMMENT 5 #define SECTION_APP0 6 #define SECTION_EXIF 7 #define SECTION_FPIX 8 #define SECTION_GPS 9 #define SECTION_INTEROP 10 #define SECTION_APP12 11 #define SECTION_WINXP 12 #define SECTION_MAKERNOTE 13 #define SECTION_COUNT 14 #define FOUND_FILE (1<<SECTION_FILE) #define FOUND_COMPUTED (1<<SECTION_COMPUTED) #define FOUND_ANY_TAG (1<<SECTION_ANY_TAG) #define FOUND_IFD0 (1<<SECTION_IFD0) #define FOUND_THUMBNAIL (1<<SECTION_THUMBNAIL) #define FOUND_COMMENT (1<<SECTION_COMMENT) #define FOUND_APP0 (1<<SECTION_APP0) #define FOUND_EXIF (1<<SECTION_EXIF) #define FOUND_FPIX (1<<SECTION_FPIX) #define FOUND_GPS (1<<SECTION_GPS) #define FOUND_INTEROP (1<<SECTION_INTEROP) #define FOUND_APP12 (1<<SECTION_APP12) #define FOUND_WINXP (1<<SECTION_WINXP) #define FOUND_MAKERNOTE (1<<SECTION_MAKERNOTE) static char *exif_get_sectionname(int section) { switch(section) { case SECTION_FILE: return "FILE"; case SECTION_COMPUTED: return "COMPUTED"; case SECTION_ANY_TAG: return "ANY_TAG"; case SECTION_IFD0: return "IFD0"; case SECTION_THUMBNAIL: return "THUMBNAIL"; case SECTION_COMMENT: return "COMMENT"; case SECTION_APP0: return "APP0"; case SECTION_EXIF: return "EXIF"; case SECTION_FPIX: return "FPIX"; case SECTION_GPS: return "GPS"; case SECTION_INTEROP: return "INTEROP"; case SECTION_APP12: return "APP12"; case SECTION_WINXP: return "WINXP"; case SECTION_MAKERNOTE: return "MAKERNOTE"; } return ""; } static tag_table_type exif_get_tag_table(int section) { switch(section) { case SECTION_FILE: return &tag_table_IFD[0]; case SECTION_COMPUTED: return &tag_table_IFD[0]; case SECTION_ANY_TAG: return &tag_table_IFD[0]; case SECTION_IFD0: return &tag_table_IFD[0]; case SECTION_THUMBNAIL: return &tag_table_IFD[0]; case SECTION_COMMENT: return &tag_table_IFD[0]; case SECTION_APP0: return &tag_table_IFD[0]; case SECTION_EXIF: return &tag_table_IFD[0]; case SECTION_FPIX: return &tag_table_IFD[0]; case SECTION_GPS: return &tag_table_GPS[0]; case SECTION_INTEROP: return &tag_table_IOP[0]; case SECTION_APP12: return &tag_table_IFD[0]; case SECTION_WINXP: return &tag_table_IFD[0]; } return &tag_table_IFD[0]; } /* }}} */ /* {{{ exif_get_sectionlist Return list of sectionnames specified by sectionlist. Return value must be freed */ static char *exif_get_sectionlist(int sectionlist TSRMLS_DC) { int i, len, ml = 0; char *sections; for(i=0; i<SECTION_COUNT; i++) { ml += strlen(exif_get_sectionname(i))+2; } sections = safe_emalloc(ml, 1, 1); sections[0] = '\0'; len = 0; for(i=0; i<SECTION_COUNT; i++) { if (sectionlist&(1<<i)) { snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i)); len = strlen(sections); } } if (len>2) sections[len-2] = '\0'; return sections; } /* }}} */ /* {{{ struct image_info_type This structure stores Exif header image elements in a simple manner Used to store camera data as extracted from the various ways that it can be stored in a nexif header */ typedef struct { int type; size_t size; uchar *data; } file_section; typedef struct { int count; file_section *list; } file_section_list; typedef struct { image_filetype filetype; size_t width, height; size_t size; size_t offset; char *data; } thumbnail_data; typedef struct { char *value; size_t size; int tag; } xp_field_type; typedef struct { int count; xp_field_type *list; } xp_field_list; /* This structure is used to store a section of a Jpeg file. */ typedef struct { php_stream *infile; char *FileName; time_t FileDateTime; size_t FileSize; image_filetype FileType; int Height, Width; int IsColor; char *make; char *model; float ApertureFNumber; float ExposureTime; double FocalplaneUnits; float CCDWidth; double FocalplaneXRes; size_t ExifImageWidth; float FocalLength; float Distance; int motorola_intel; /* 1 Motorola; 0 Intel */ char *UserComment; int UserCommentLength; char *UserCommentEncoding; char *encode_unicode; char *decode_unicode_be; char *decode_unicode_le; char *encode_jis; char *decode_jis_be; char *decode_jis_le; char *Copyright;/* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */ char *CopyrightPhotographer; char *CopyrightEditor; xp_field_list xp_fields; thumbnail_data Thumbnail; /* other */ int sections_found; /* FOUND_<marker> */ image_info_list info_list[SECTION_COUNT]; /* for parsing */ int read_thumbnail; int read_all; int ifd_nesting_level; /* internal */ file_section_list file; } image_info_type; /* }}} */ /* {{{ exif_error_docref */ static void exif_error_docref(const char *docref EXIFERR_DC, const image_info_type *ImageInfo, int type, const char *format, ...) { va_list args; va_start(args, format); #ifdef EXIF_DEBUG { char *buf; spprintf(&buf, 0, "%s(%d): %s", _file, _line, format); php_verror(docref, ImageInfo->FileName?ImageInfo->FileName:"", type, buf, args TSRMLS_CC); efree(buf); } #else php_verror(docref, ImageInfo->FileName?ImageInfo->FileName:"", type, format, args TSRMLS_CC); #endif va_end(args); } /* }}} */ /* {{{ jpeg_sof_info */ typedef struct { int bits_per_sample; size_t width; size_t height; int num_components; } jpeg_sof_info; /* }}} */ /* {{{ exif_file_sections_add Add a file_section to image_info returns the used block or -1. if size>0 and data == NULL buffer of size is allocated */ static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, uchar *data) { file_section *tmp; int count = ImageInfo->file.count; tmp = safe_erealloc(ImageInfo->file.list, (count+1), sizeof(file_section), 0); ImageInfo->file.list = tmp; ImageInfo->file.list[count].type = 0xFFFF; ImageInfo->file.list[count].data = NULL; ImageInfo->file.list[count].size = 0; ImageInfo->file.count = count+1; if (!size) { data = NULL; } else if (data == NULL) { data = safe_emalloc(size, 1, 0); } ImageInfo->file.list[count].type = type; ImageInfo->file.list[count].data = data; ImageInfo->file.list[count].size = size; return count; } /* }}} */ /* {{{ exif_file_sections_realloc Reallocate a file section returns 0 on success and -1 on failure */ static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size TSRMLS_DC) { void *tmp; /* This is not a malloc/realloc check. It is a plausibility check for the * function parameters (requirements engineering). */ if (section_index >= ImageInfo->file.count) { EXIF_ERRLOG_FSREALLOC(ImageInfo) return -1; } tmp = safe_erealloc(ImageInfo->file.list[section_index].data, 1, size, 0); ImageInfo->file.list[section_index].data = tmp; ImageInfo->file.list[section_index].size = size; return 0; } /* }}} */ /* {{{ exif_file_section_free Discard all file_sections in ImageInfo */ static int exif_file_sections_free(image_info_type *ImageInfo) { int i; if (ImageInfo->file.count) { for (i=0; i<ImageInfo->file.count; i++) { EFREE_IF(ImageInfo->file.list[i].data); } } EFREE_IF(ImageInfo->file.list); ImageInfo->file.count = 0; return TRUE; } /* }}} */ /* {{{ exif_iif_add_value Add a value to image_info */ static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel TSRMLS_DC) { size_t idex; void *vptr; image_info_value *info_value; image_info_data *info_data; image_info_data *list; if (length < 0) { return; } list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = tag; info_data->format = format; info_data->length = length; info_data->name = estrdup(name); info_value = &info_data->value; switch (format) { case TAG_FMT_STRING: if (value) { length = php_strnlen(value, length); info_value->s = estrndup(value, length); info_data->length = length; } else { info_data->length = 0; info_value->s = estrdup(""); } break; default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */ case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */ if (!length) break; case TAG_FMT_UNDEFINED: if (value) { /* do not recompute length here */ info_value->s = estrndup(value, length); info_data->length = length; } else { info_data->length = 0; info_value->s = estrdup(""); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: if (length==0) { break; } else if (length>1) { info_value->list = safe_emalloc(length, sizeof(image_info_value), 0); } else { info_value = &info_data->value; } for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) { if (length>1) { info_value = &info_data->value.list[idex]; } switch (format) { case TAG_FMT_USHORT: info_value->u = php_ifd_get16u(vptr, motorola_intel); break; case TAG_FMT_ULONG: info_value->u = php_ifd_get32u(vptr, motorola_intel); break; case TAG_FMT_URATIONAL: info_value->ur.num = php_ifd_get32u(vptr, motorola_intel); info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SSHORT: info_value->i = php_ifd_get16s(vptr, motorola_intel); break; case TAG_FMT_SLONG: info_value->i = php_ifd_get32s(vptr, motorola_intel); break; case TAG_FMT_SRATIONAL: info_value->sr.num = php_ifd_get32u(vptr, motorola_intel); info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type single"); #endif info_value->f = *(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type double"); #endif info_value->d = *(double *)value; break; } } } image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* }}} */ /* {{{ exif_iif_add_tag Add a tag from IFD to image_info */ static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value TSRMLS_DC) { exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, image_info->motorola_intel TSRMLS_CC); } /* }}} */ /* {{{ exif_iif_add_int Add an int value to image_info */ static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_SLONG; info_data->length = 1; info_data->name = estrdup(name); info_data->value.i = value; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* }}} */ /* {{{ exif_iif_add_str Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; if (value) { list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_STRING; info_data->length = 1; info_data->name = estrdup(name); info_data->value.s = estrdup(value); image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* }}} */ /* {{{ exif_iif_add_fmt Add a format string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name TSRMLS_DC, char *value, ...) { char *tmp; va_list arglist; va_start(arglist, value); if (value) { vspprintf(&tmp, 0, value, arglist); exif_iif_add_str(image_info, section_index, name, tmp TSRMLS_CC); efree(tmp); } va_end(arglist); } /* }}} */ /* {{{ exif_iif_add_str Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; if (value) { list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_UNDEFINED; info_data->length = length; info_data->name = estrdup(name); info_data->value.s = safe_emalloc(length, 1, 1); memcpy(info_data->value.s, value, length); info_data->value.s[length] = 0; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* }}} */ /* {{{ exif_iif_free Free memory allocated for image_info */ static void exif_iif_free(image_info_type *image_info, int section_index) { int i; void *f; /* faster */ if (image_info->info_list[section_index].count) { for (i=0; i < image_info->info_list[section_index].count; i++) { if ((f=image_info->info_list[section_index].list[i].name) != NULL) { efree(f); } switch(image_info->info_list[section_index].list[i].format) { case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */ if (image_info->info_list[section_index].list[i].length<1) break; default: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: if ((f=image_info->info_list[section_index].list[i].value.s) != NULL) { efree(f); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: /* nothing to do here */ if (image_info->info_list[section_index].list[i].length > 1) { if ((f=image_info->info_list[section_index].list[i].value.list) != NULL) { efree(f); } } break; } } } EFREE_IF(image_info->info_list[section_index].list); } /* }}} */ /* {{{ add_assoc_image_info * Add image_info to associative array value. */ static void add_assoc_image_info(zval *value, int sub_array, image_info_type *image_info, int section_index TSRMLS_DC) { char buffer[64], *val, *name, uname[64]; int i, ap, l, b, idx=0, unknown=0; #ifdef EXIF_DEBUG int info_tag; #endif image_info_value *info_value; image_info_data *info_data; zval *tmpi, *array = NULL; #ifdef EXIF_DEBUG /* php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Adding %d infos from section %s", image_info->info_list[section_index].count, exif_get_sectionname(section_index));*/ #endif if (image_info->info_list[section_index].count) { if (sub_array) { MAKE_STD_ZVAL(tmpi); array_init(tmpi); } else { tmpi = value; } for(i=0; i<image_info->info_list[section_index].count; i++) { info_data = &image_info->info_list[section_index].list[i]; #ifdef EXIF_DEBUG info_tag = info_data->tag; /* conversion */ #endif info_value = &info_data->value; if (!(name = info_data->name)) { snprintf(uname, sizeof(uname), "%d", unknown++); name = uname; } #ifdef EXIF_DEBUG /* php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Adding infos: tag(0x%04X,%12s,L=0x%04X): %s", info_tag, exif_get_tagname(info_tag, buffer, -12, exif_get_tag_table(section_index) TSRMLS_CC), info_data->length, info_data->format==TAG_FMT_STRING?(info_value&&info_value->s?info_value->s:"<no data>"):exif_get_tagformat(info_data->format));*/ #endif if (info_data->length==0) { add_assoc_null(tmpi, name); } else { switch (info_data->format) { default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ case TAG_FMT_BYTE: case TAG_FMT_SBYTE: case TAG_FMT_UNDEFINED: if (!info_value->s) { add_assoc_stringl(tmpi, name, "", 0, 1); } else { add_assoc_stringl(tmpi, name, info_value->s, info_data->length, 1); } break; case TAG_FMT_STRING: if (!(val = info_value->s)) { val = ""; } if (section_index==SECTION_COMMENT) { add_index_string(tmpi, idx++, val, 1); } else { add_assoc_string(tmpi, name, val, 1); } break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: /*case TAG_FMT_BYTE: case TAG_FMT_SBYTE:*/ case TAG_FMT_USHORT: case TAG_FMT_SSHORT: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: case TAG_FMT_ULONG: case TAG_FMT_SLONG: /* now the rest, first see if it becomes an array */ if ((l = info_data->length) > 1) { array = NULL; MAKE_STD_ZVAL(array); array_init(array); } for(ap=0; ap<l; ap++) { if (l>1) { info_value = &info_data->value.list[ap]; } switch (info_data->format) { case TAG_FMT_BYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { add_index_long(array, b, (int)(info_value->s[b])); } break; } case TAG_FMT_USHORT: case TAG_FMT_ULONG: if (l==1) { add_assoc_long(tmpi, name, (int)info_value->u); } else { add_index_long(array, ap, (int)info_value->u); } break; case TAG_FMT_URATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->ur.num, info_value->ur.den); if (l==1) { add_assoc_string(tmpi, name, buffer, 1); } else { add_index_string(array, ap, buffer, 1); } break; case TAG_FMT_SBYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { add_index_long(array, ap, (int)info_value->s[b]); } break; } case TAG_FMT_SSHORT: case TAG_FMT_SLONG: if (l==1) { add_assoc_long(tmpi, name, info_value->i); } else { add_index_long(array, ap, info_value->i); } break; case TAG_FMT_SRATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den); if (l==1) { add_assoc_string(tmpi, name, buffer, 1); } else { add_index_string(array, ap, buffer, 1); } break; case TAG_FMT_SINGLE: if (l==1) { add_assoc_double(tmpi, name, info_value->f); } else { add_index_double(array, ap, info_value->f); } break; case TAG_FMT_DOUBLE: if (l==1) { add_assoc_double(tmpi, name, info_value->d); } else { add_index_double(array, ap, info_value->d); } break; } info_value = &info_data->value.list[ap]; } if (l>1) { add_assoc_zval(tmpi, name, array); } break; } } } if (sub_array) { add_assoc_zval(value, exif_get_sectionname(section_index), tmpi); } } } /* }}} */ /* {{{ Markers JPEG markers consist of one or more 0xFF bytes, followed by a marker code byte (which is not an FF). Here are the marker codes of interest in this program. (See jdmarker.c for a more complete list.) */ #define M_TEM 0x01 /* temp for arithmetic coding */ #define M_RES 0x02 /* reserved */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_DHT 0xC4 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_JPEG 0x08 /* reserved for extensions */ #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_DAC 0xCC /* arithmetic table */ #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_RST0 0xD0 /* restart segment */ #define M_RST1 0xD1 #define M_RST2 0xD2 #define M_RST3 0xD3 #define M_RST4 0xD4 #define M_RST5 0xD5 #define M_RST6 0xD6 #define M_RST7 0xD7 #define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */ #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_DQT 0xDB #define M_DNL 0xDC #define M_DRI 0xDD #define M_DHP 0xDE #define M_EXP 0xDF #define M_APP0 0xE0 /* JPEG: 'JFIFF' AND (additional 'JFXX') */ #define M_EXIF 0xE1 /* Exif Attribute Information */ #define M_APP2 0xE2 /* Flash Pix Extension Data? */ #define M_APP3 0xE3 #define M_APP4 0xE4 #define M_APP5 0xE5 #define M_APP6 0xE6 #define M_APP7 0xE7 #define M_APP8 0xE8 #define M_APP9 0xE9 #define M_APP10 0xEA #define M_APP11 0xEB #define M_APP12 0xEC #define M_APP13 0xED /* IPTC International Press Telecommunications Council */ #define M_APP14 0xEE /* Software, Copyright? */ #define M_APP15 0xEF #define M_JPG0 0xF0 #define M_JPG1 0xF1 #define M_JPG2 0xF2 #define M_JPG3 0xF3 #define M_JPG4 0xF4 #define M_JPG5 0xF5 #define M_JPG6 0xF6 #define M_JPG7 0xF7 #define M_JPG8 0xF8 #define M_JPG9 0xF9 #define M_JPG10 0xFA #define M_JPG11 0xFB #define M_JPG12 0xFC #define M_JPG13 0xFD #define M_COM 0xFE /* COMment */ #define M_PSEUDO 0x123 /* Extra value. */ /* }}} */ /* {{{ jpeg2000 markers */ /* Markers x30 - x3F do not have a segment */ /* Markers x00, x01, xFE, xC0 - xDF ISO/IEC 10918-1 -> M_<xx> */ /* Markers xF0 - xF7 ISO/IEC 10918-3 */ /* Markers xF7 - xF8 ISO/IEC 14495-1 */ /* XY=Main/Tile-header:(R:required, N:not_allowed, O:optional, L:last_marker) */ #define JC_SOC 0x4F /* NN, Start of codestream */ #define JC_SIZ 0x51 /* RN, Image and tile size */ #define JC_COD 0x52 /* RO, Codeing style defaulte */ #define JC_COC 0x53 /* OO, Coding style component */ #define JC_TLM 0x55 /* ON, Tile part length main header */ #define JC_PLM 0x57 /* ON, Packet length main header */ #define JC_PLT 0x58 /* NO, Packet length tile part header */ #define JC_QCD 0x5C /* RO, Quantization default */ #define JC_QCC 0x5D /* OO, Quantization component */ #define JC_RGN 0x5E /* OO, Region of interest */ #define JC_POD 0x5F /* OO, Progression order default */ #define JC_PPM 0x60 /* ON, Packed packet headers main header */ #define JC_PPT 0x61 /* NO, Packet packet headers tile part header */ #define JC_CME 0x64 /* OO, Comment: "LL E <text>" E=0:binary, E=1:ascii */ #define JC_SOT 0x90 /* NR, Start of tile */ #define JC_SOP 0x91 /* NO, Start of packeter default */ #define JC_EPH 0x92 /* NO, End of packet header */ #define JC_SOD 0x93 /* NL, Start of data */ #define JC_EOC 0xD9 /* NN, End of codestream */ /* }}} */ /* {{{ exif_process_COM Process a COM marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ static void exif_process_COM (image_info_type *image_info, char *value, size_t length TSRMLS_DC) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2 TSRMLS_CC); } /* }}} */ /* {{{ exif_process_CME Process a CME marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ #ifdef EXIF_JPEG2000 static void exif_process_CME (image_info_type *image_info, char *value, size_t length TSRMLS_DC) { if (length>3) { switch(value[2]) { case 0: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, length, value TSRMLS_CC); break; case 1: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length, value); break; default: php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Undefined JPEG2000 comment encoding"); break; } } else { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, 0, NULL); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "JPEG2000 comment section too small"); } } #endif /* }}} */ /* {{{ exif_process_SOFn * Process a SOFn marker. This is useful for the image dimensions */ static void exif_process_SOFn (uchar *Data, int marker, jpeg_sof_info *result) { /* 0xFF SOSn SectLen(2) Bits(1) Height(2) Width(2) Channels(1) 3*Channels (1) */ result->bits_per_sample = Data[2]; result->height = php_jpg_get16(Data+3); result->width = php_jpg_get16(Data+5); result->num_components = Data[7]; /* switch (marker) { case M_SOF0: process = "Baseline"; break; case M_SOF1: process = "Extended sequential"; break; case M_SOF2: process = "Progressive"; break; case M_SOF3: process = "Lossless"; break; case M_SOF5: process = "Differential sequential"; break; case M_SOF6: process = "Differential progressive"; break; case M_SOF7: process = "Differential lossless"; break; case M_SOF9: process = "Extended sequential, arithmetic coding"; break; case M_SOF10: process = "Progressive, arithmetic coding"; break; case M_SOF11: process = "Lossless, arithmetic coding"; break; case M_SOF13: process = "Differential sequential, arithmetic coding"; break; case M_SOF14: process = "Differential progressive, arithmetic coding"; break; case M_SOF15: process = "Differential lossless, arithmetic coding"; break; default: process = "Unknown"; break; }*/ } /* }}} */ /* forward declarations */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC); static int exif_process_IFD_TAG( image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC); /* {{{ exif_get_markername Get name of marker */ #ifdef EXIF_DEBUG static char * exif_get_markername(int marker) { switch(marker) { case 0xC0: return "SOF0"; case 0xC1: return "SOF1"; case 0xC2: return "SOF2"; case 0xC3: return "SOF3"; case 0xC4: return "DHT"; case 0xC5: return "SOF5"; case 0xC6: return "SOF6"; case 0xC7: return "SOF7"; case 0xC9: return "SOF9"; case 0xCA: return "SOF10"; case 0xCB: return "SOF11"; case 0xCD: return "SOF13"; case 0xCE: return "SOF14"; case 0xCF: return "SOF15"; case 0xD8: return "SOI"; case 0xD9: return "EOI"; case 0xDA: return "SOS"; case 0xDB: return "DQT"; case 0xDC: return "DNL"; case 0xDD: return "DRI"; case 0xDE: return "DHP"; case 0xDF: return "EXP"; case 0xE0: return "APP0"; case 0xE1: return "EXIF"; case 0xE2: return "FPIX"; case 0xE3: return "APP3"; case 0xE4: return "APP4"; case 0xE5: return "APP5"; case 0xE6: return "APP6"; case 0xE7: return "APP7"; case 0xE8: return "APP8"; case 0xE9: return "APP9"; case 0xEA: return "APP10"; case 0xEB: return "APP11"; case 0xEC: return "APP12"; case 0xED: return "APP13"; case 0xEE: return "APP14"; case 0xEF: return "APP15"; case 0xF0: return "JPG0"; case 0xFD: return "JPG13"; case 0xFE: return "COM"; case 0x01: return "TEM"; } return "Unknown"; } #endif /* }}} */ /* {{{ proto string exif_tagname(index) Get headername for index or false if not defined */ PHP_FUNCTION(exif_tagname) { long tag; char *szTemp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &tag) == FAILURE) { return; } szTemp = exif_get_tagname(tag, NULL, 0, tag_table_IFD TSRMLS_CC); if (tag < 0 || !szTemp || !szTemp[0]) { RETURN_FALSE; } RETURN_STRING(szTemp, 1) } /* }}} */ /* {{{ exif_ifd_make_value * Create a value for an ifd from an info_data pointer */ static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel TSRMLS_DC) { size_t byte_count; char *value_ptr, *data_ptr; size_t i; image_info_value *info_value; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; value_ptr = safe_emalloc(max(byte_count, 4), 1, 0); memset(value_ptr, 0, 4); if (!info_data->length) { return value_ptr; } if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE)) ) { memmove(value_ptr, info_data->value.s, byte_count); return value_ptr; } else if (info_data->format == TAG_FMT_BYTE) { *value_ptr = info_data->value.u; return value_ptr; } else if (info_data->format == TAG_FMT_SBYTE) { *value_ptr = info_data->value.i; return value_ptr; } else { data_ptr = value_ptr; for(i=0; i<info_data->length; i++) { if (info_data->length==1) { info_value = &info_data->value; } else { info_value = &info_data->value.list[i]; } switch(info_data->format) { case TAG_FMT_USHORT: php_ifd_set16u(data_ptr, info_value->u, motorola_intel); data_ptr += 2; break; case TAG_FMT_ULONG: php_ifd_set32u(data_ptr, info_value->u, motorola_intel); data_ptr += 4; break; case TAG_FMT_SSHORT: php_ifd_set16u(data_ptr, info_value->i, motorola_intel); data_ptr += 2; break; case TAG_FMT_SLONG: php_ifd_set32u(data_ptr, info_value->i, motorola_intel); data_ptr += 4; break; case TAG_FMT_URATIONAL: php_ifd_set32u(data_ptr, info_value->sr.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SRATIONAL: php_ifd_set32u(data_ptr, info_value->ur.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SINGLE: memmove(data_ptr, &info_value->f, 4); data_ptr += 4; break; case TAG_FMT_DOUBLE: memmove(data_ptr, &info_value->d, 8); data_ptr += 8; break; } } } return value_ptr; } /* }}} */ /* {{{ exif_thumbnail_build * Check and build thumbnail */ static void exif_thumbnail_build(image_info_type *ImageInfo TSRMLS_DC) { size_t new_size, new_move, new_value; char *new_data; void *value_ptr; int i, byte_count; image_info_list *info_list; image_info_data *info_data; #ifdef EXIF_DEBUG char tagname[64]; #endif if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) { return; /* ignore this call */ } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: filetype = %d", ImageInfo->Thumbnail.filetype); #endif switch(ImageInfo->Thumbnail.filetype) { default: case IMAGE_FILETYPE_JPEG: /* done */ break; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: info_list = &ImageInfo->info_list[SECTION_THUMBNAIL]; new_size = 8 + 2 + info_list->count * 12 + 4; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size of signature + directory(%d): 0x%02X", info_list->count, new_size); #endif new_value= new_size; /* offset for ifd values outside ifd directory */ for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; if (byte_count > 4) { new_size += byte_count; } } new_move = new_size; new_data = safe_erealloc(ImageInfo->Thumbnail.data, 1, ImageInfo->Thumbnail.size, new_size); ImageInfo->Thumbnail.data = new_data; memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size); ImageInfo->Thumbnail.size += new_size; /* fill in data */ if (ImageInfo->motorola_intel) { memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8); } else { memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8); } new_data += 8; php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel); new_data += 2; for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process tag(x%04X=%s): %s%s (%d bytes)", info_data->tag, exif_get_tagname(info_data->tag, tagname, -12, tag_table_IFD TSRMLS_CC), (info_data->length>1)&&info_data->format!=TAG_FMT_UNDEFINED&&info_data->format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(info_data->format), byte_count); #endif if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, TAG_FMT_ULONG, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, 1, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 8, new_move, ImageInfo->motorola_intel); } else { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel); value_ptr = exif_ifd_make_value(info_data, ImageInfo->motorola_intel TSRMLS_CC); if (byte_count <= 4) { memmove(new_data+8, value_ptr, 4); } else { php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: writing with value offset: 0x%04X + 0x%02X", new_value, byte_count); #endif memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count); new_value += byte_count; } efree(value_ptr); } new_data += 12; } memset(new_data, 0, 4); /* next ifd pointer */ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: created"); #endif break; } } /* }}} */ /* {{{ exif_thumbnail_extract * Grab the thumbnail, corrected */ static void exif_thumbnail_extract(image_info_type *ImageInfo, char *offset, size_t length TSRMLS_DC) { if (ImageInfo->Thumbnail.data) { exif_error_docref("exif_read_data#error_mult_thumb" EXIFERR_CC, ImageInfo, E_WARNING, "Multiple possible thumbnails"); return; /* Should not happen */ } if (!ImageInfo->read_thumbnail) { return; /* ignore this call */ } /* according to exif2.1, the thumbnail is not supposed to be greater than 64K */ if (ImageInfo->Thumbnail.size >= 65536 || ImageInfo->Thumbnail.size <= 0 || ImageInfo->Thumbnail.offset <= 0 ) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Illegal thumbnail size/offset"); return; } /* Check to make sure we are not going to go past the ExifLength */ if ((ImageInfo->Thumbnail.offset + ImageInfo->Thumbnail.size) > length) { EXIF_ERRLOG_THUMBEOF(ImageInfo) return; } ImageInfo->Thumbnail.data = estrndup(offset + ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size); exif_thumbnail_build(ImageInfo TSRMLS_CC); } /* }}} */ /* {{{ exif_process_undefined * Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */ static int exif_process_undefined(char **result, char *value, size_t byte_count TSRMLS_DC) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. * estrndup does not return length */ if (byte_count) { (*result) = estrndup(value, byte_count); /* NULL @ byte_count!!! */ return byte_count+1; } return 0; } /* }}} */ /* {{{ exif_process_string_raw * Copy a string in Exif header to a character string returns length of allocated buffer if any. */ static int exif_process_string_raw(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ if (byte_count) { (*result) = safe_emalloc(byte_count, 1, 1); memcpy(*result, value, byte_count); (*result)[byte_count] = '\0'; return byte_count+1; } return 0; } /* }}} */ /* {{{ exif_process_string * Copy a string in Exif header to a character string and return length of allocated buffer if any. * In contrast to exif_process_string this function does always return a string buffer */ static int exif_process_string(char **result, char *value, size_t byte_count TSRMLS_DC) { /* we cannot use strlcpy - here the problem is that we cannot use strlen to * determin length of string and we cannot use strlcpy with len=byte_count+1 * because then we might get into an EXCEPTION if we exceed an allocated * memory page...so we use php_strnlen in conjunction with memcpy and add the NUL * char. * estrdup would sometimes allocate more memory and does not return length */ if ((byte_count=php_strnlen(value, byte_count)) > 0) { return exif_process_undefined(result, value, byte_count TSRMLS_CC); } (*result) = estrndup("", 1); /* force empty string */ return byte_count+1; } /* }}} */ /* {{{ exif_process_user_comment * Process UserComment in IFD. */ static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount TSRMLS_DC) { int a; char *decode; size_t len;; *pszEncoding = NULL; /* Copy the comment */ if (ByteCount>=8) { if (!memcmp(szValuePtr, "UNICODE\0", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, "\xFE\xFF", 2)) { decode = "UCS-2BE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) { decode = "UCS-2LE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), zend_multibyte_fetch_encoding(decode TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) { /* JIS should be tanslated to MB or we leave it to the user - leave it to the user */ *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_jis TSRMLS_CC), zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) { /* 8 NULL means undefined and should be ASCII... */ *pszEncoding = estrdup("UNDEFINED"); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount TSRMLS_CC); return strlen(*pszInfoPtr); } /* }}} */ /* {{{ exif_process_unicode * Process unicode field in IFD. */ static int exif_process_unicode(image_info_type *ImageInfo, xp_field_type *xp_field, int tag, char *szValuePtr, int ByteCount TSRMLS_DC) { xp_field->tag = tag; xp_field->value = NULL; /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)&xp_field->value, &xp_field->size, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_unicode_be : ImageInfo->decode_unicode_le TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount); } return xp_field->size; } /* }}} */ /* {{{ exif_process_IFD_in_MAKERNOTE * Process nested IFDs directories in Maker Note. */ static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement TSRMLS_DC) { int de, i=0, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) return FALSE; maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; break; case MN_OFFSET_GUESS: offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif offset_base = value_ptr + offset_diff; break; default: case MN_OFFSET_NORMAL: break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + x%04X*12 = x%04X > x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, IFDlength, displacement, section_index, 0, maker_note->tag_table TSRMLS_CC)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; } /* }}} */ /* {{{ exif_process_IFD_TAG * Process one of the nested IFDs directories. */ static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=NULL; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; #ifdef EXIF_DEBUG char *dump_data; int dump_free; #endif /* EXIF_DEBUG */ /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached"); return FALSE; } ImageInfo->ifd_nesting_level++; tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components); return FALSE; } byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format]; if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC)); return FALSE; } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; /* dir_entry is ImageInfo->file.list[sn].data+2+i*12 offset_base is ImageInfo->file.list[sn].data-dir_offset dir_entry - offset_base is dir_offset+2+i*12 */ if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* It is important to check for IMAGE_FILETYPE_TIFF * JPEG does not use absolute pointers instead its pointers are * relative to the start of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength); } return FALSE; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = safe_emalloc(byte_count, 1, 0); outside = value_ptr; } else { /* In most cases we only access a small range so * it is faster to use a static buffer there * BUT it offers also the possibility to have * pointers read without the need to free them * explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = php_stream_tell(ImageInfo->infile); php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET); fgot = php_stream_tell(ImageInfo->infile); if (fgot!=offset_val) { EFREE_IF(outside); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val); return FALSE; } fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count); php_stream_seek(ImageInfo->infile, fpos, SEEK_SET); if (fgot<byte_count) { EFREE_IF(outside); EXIF_ERRLOG_FILEEOF(ImageInfo) return FALSE; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; #ifdef EXIF_DEBUG dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data); if (dump_free) { efree(dump_data); } #endif if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ ImageInfo->CopyrightPhotographer = estrdup(value_ptr); ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1); spprintf(&ImageInfo->Copyright, 0, "%s, %s", ImageInfo->CopyrightPhotographer, ImageInfo->CopyrightEditor); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { ImageInfo->Copyright = estrndup(value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC); break; case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD"); } break; case TAG_MAKE: ImageInfo->make = estrndup(value_ptr, byte_count); break; case TAG_MODEL: ImageInfo->model = estrndup(value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF"); #endif ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS"); #endif ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY"); #endif ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer"); return FALSE; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) { return FALSE; } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index)); #endif } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC); EFREE_IF(outside); return TRUE; } /* }}} */ /* {{{ exif_process_IFD_in_JPEG * Process one of the nested IFDs directories. */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC) { int de; int NumDirEntries; int NextDirOffset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), IFDlength, IFDlength); #endif ImageInfo->sections_found |= FOUND_IFD0; if ((dir_start + 2) >= (offset_base+IFDlength)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size"); return FALSE; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index) TSRMLS_CC)) { return FALSE; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return TRUE; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ if ((dir_start+2+12*de + 4) >= (offset_base+IFDlength)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size"); return FALSE; } NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size); #endif if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail ) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength TSRMLS_CC); } return TRUE; } else { return FALSE; } } return TRUE; } /* }}} */ /* {{{ exif_process_TIFF_in_JPEG Process a TIFF header in a JPEG file */ static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement TSRMLS_DC) { unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF alignment marker"); return; } /* Check the next two values for correctness. */ exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } } /* Check the next two values for correctness. */ if (length < 8) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if (exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } /* }}} */
165,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: tgs_make_reply(krb5_context context, krb5_kdc_configuration *config, KDC_REQ_BODY *b, krb5_const_principal tgt_name, const EncTicketPart *tgt, const krb5_keyblock *replykey, int rk_is_subkey, const EncryptionKey *serverkey, const krb5_keyblock *sessionkey, krb5_kvno kvno, AuthorizationData *auth_data, hdb_entry_ex *server, krb5_principal server_principal, const char *server_name, hdb_entry_ex *client, krb5_principal client_principal, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, krb5_principals spp, const krb5_data *rspac, const METHOD_DATA *enc_pa_data, const char **e_text, krb5_data *reply) { KDC_REP rep; EncKDCRepPart ek; EncTicketPart et; KDCOptions f = b->kdc_options; krb5_error_code ret; int is_weak = 0; memset(&rep, 0, sizeof(rep)); memset(&et, 0, sizeof(et)); memset(&ek, 0, sizeof(ek)); rep.pvno = 5; rep.msg_type = krb_tgs_rep; et.authtime = tgt->authtime; _kdc_fix_time(&b->till); et.endtime = min(tgt->endtime, *b->till); ALLOC(et.starttime); *et.starttime = kdc_time; ret = check_tgs_flags(context, config, b, tgt, &et); if(ret) goto out; /* We should check the transited encoding if: 1) the request doesn't ask not to be checked 2) globally enforcing a check 3) principal requires checking 4) we allow non-check per-principal, but principal isn't marked as allowing this 5) we don't globally allow this */ #define GLOBAL_FORCE_TRANSITED_CHECK \ (config->trpolicy == TRPOLICY_ALWAYS_CHECK) #define GLOBAL_ALLOW_PER_PRINCIPAL \ (config->trpolicy == TRPOLICY_ALLOW_PER_PRINCIPAL) #define GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK \ (config->trpolicy == TRPOLICY_ALWAYS_HONOUR_REQUEST) /* these will consult the database in future release */ #define PRINCIPAL_FORCE_TRANSITED_CHECK(P) 0 #define PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(P) 0 ret = fix_transited_encoding(context, config, !f.disable_transited_check || GLOBAL_FORCE_TRANSITED_CHECK || PRINCIPAL_FORCE_TRANSITED_CHECK(server) || !((GLOBAL_ALLOW_PER_PRINCIPAL && PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(server)) || GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK), &tgt->transited, &et, krb5_principal_get_realm(context, client_principal), krb5_principal_get_realm(context, server->entry.principal), krb5_principal_get_realm(context, krbtgt->entry.principal)); if(ret) goto out; copy_Realm(&server_principal->realm, &rep.ticket.realm); _krb5_principal2principalname(&rep.ticket.sname, server_principal); copy_Realm(&tgt_name->realm, &rep.crealm); /* if (f.request_anonymous) _kdc_make_anonymous_principalname (&rep.cname); else */ copy_PrincipalName(&tgt_name->name, &rep.cname); rep.ticket.tkt_vno = 5; ek.caddr = et.caddr; { time_t life; life = et.endtime - *et.starttime; if(client && client->entry.max_life) life = min(life, *client->entry.max_life); if(server->entry.max_life) life = min(life, *server->entry.max_life); et.endtime = *et.starttime + life; } if(f.renewable_ok && tgt->flags.renewable && et.renew_till == NULL && et.endtime < *b->till && tgt->renew_till != NULL) { et.flags.renewable = 1; ALLOC(et.renew_till); *et.renew_till = *b->till; } if(et.renew_till){ time_t renew; renew = *et.renew_till - *et.starttime; if(client && client->entry.max_renew) renew = min(renew, *client->entry.max_renew); if(server->entry.max_renew) renew = min(renew, *server->entry.max_renew); *et.renew_till = *et.starttime + renew; } if(et.renew_till){ *et.renew_till = min(*et.renew_till, *tgt->renew_till); *et.starttime = min(*et.starttime, *et.renew_till); et.endtime = min(et.endtime, *et.renew_till); } *et.starttime = min(*et.starttime, et.endtime); if(*et.starttime == et.endtime){ ret = KRB5KDC_ERR_NEVER_VALID; goto out; } if(et.renew_till && et.endtime == *et.renew_till){ free(et.renew_till); et.renew_till = NULL; et.flags.renewable = 0; } et.flags.pre_authent = tgt->flags.pre_authent; et.flags.hw_authent = tgt->flags.hw_authent; et.flags.anonymous = tgt->flags.anonymous; et.flags.ok_as_delegate = server->entry.flags.ok_as_delegate; if(rspac->length) { /* * No not need to filter out the any PAC from the * auth_data since it's signed by the KDC. */ ret = _kdc_tkt_add_if_relevant_ad(context, &et, KRB5_AUTHDATA_WIN2K_PAC, rspac); if (ret) goto out; } if (auth_data) { unsigned int i = 0; /* XXX check authdata */ if (et.authorization_data == NULL) { et.authorization_data = calloc(1, sizeof(*et.authorization_data)); if (et.authorization_data == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } for(i = 0; i < auth_data->len ; i++) { ret = add_AuthorizationData(et.authorization_data, &auth_data->val[i]); if (ret) { krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } /* Filter out type KRB5SignedPath */ ret = find_KRB5SignedPath(context, et.authorization_data, NULL); if (ret == 0) { if (et.authorization_data->len == 1) { free_AuthorizationData(et.authorization_data); free(et.authorization_data); et.authorization_data = NULL; } else { AuthorizationData *ad = et.authorization_data; free_AuthorizationDataElement(&ad->val[ad->len - 1]); ad->len--; } } } ret = krb5_copy_keyblock_contents(context, sessionkey, &et.key); if (ret) goto out; et.crealm = tgt_name->realm; et.cname = tgt_name->name; ek.key = et.key; /* MIT must have at least one last_req */ ek.last_req.val = calloc(1, sizeof(*ek.last_req.val)); if (ek.last_req.val == NULL) { ret = ENOMEM; goto out; } ek.last_req.len = 1; /* set after alloc to avoid null deref on cleanup */ ek.nonce = b->nonce; ek.flags = et.flags; ek.authtime = et.authtime; ek.starttime = et.starttime; ek.endtime = et.endtime; ek.renew_till = et.renew_till; ek.srealm = rep.ticket.realm; ek.sname = rep.ticket.sname; _kdc_log_timestamp(context, config, "TGS-REQ", et.authtime, et.starttime, et.endtime, et.renew_till); /* Don't sign cross realm tickets, they can't be checked anyway */ { char *r = get_krbtgt_realm(&ek.sname); if (r == NULL || strcmp(r, ek.srealm) == 0) { ret = _kdc_add_KRB5SignedPath(context, config, krbtgt, krbtgt_etype, client_principal, NULL, spp, &et); if (ret) goto out; } } if (enc_pa_data->len) { rep.padata = calloc(1, sizeof(*rep.padata)); if (rep.padata == NULL) { ret = ENOMEM; goto out; } ret = copy_METHOD_DATA(enc_pa_data, rep.padata); if (ret) goto out; } if (krb5_enctype_valid(context, serverkey->keytype) != 0 && _kdc_is_weak_exception(server->entry.principal, serverkey->keytype)) { krb5_enctype_enable(context, serverkey->keytype); is_weak = 1; } /* It is somewhat unclear where the etype in the following encryption should come from. What we have is a session key in the passed tgt, and a list of preferred etypes *for the new ticket*. Should we pick the best possible etype, given the keytype in the tgt, or should we look at the etype list here as well? What if the tgt session key is DES3 and we want a ticket with a (say) CAST session key. Should the DES3 etype be added to the etype list, even if we don't want a session key with DES3? */ ret = _kdc_encode_reply(context, config, NULL, 0, &rep, &et, &ek, serverkey->keytype, kvno, serverkey, 0, replykey, rk_is_subkey, e_text, reply); if (is_weak) krb5_enctype_disable(context, serverkey->keytype); out: free_TGS_REP(&rep); free_TransitedEncoding(&et.transited); if(et.starttime) free(et.starttime); if(et.renew_till) free(et.renew_till); if(et.authorization_data) { free_AuthorizationData(et.authorization_data); free(et.authorization_data); } free_LastReq(&ek.last_req); memset(et.key.keyvalue.data, 0, et.key.keyvalue.length); free_EncryptionKey(&et.key); return ret; } Commit Message: Fix transit path validation CVE-2017-6594 Commit f469fc6 (2010-10-02) inadvertently caused the previous hop realm to not be added to the transit path of issued tickets. This may, in some cases, enable bypass of capath policy in Heimdal versions 1.5 through 7.2. Note, this may break sites that rely on the bug. With the bug some incomplete [capaths] worked, that should not have. These may now break authentication in some cross-realm configurations. CWE ID: CWE-295
tgs_make_reply(krb5_context context, krb5_kdc_configuration *config, KDC_REQ_BODY *b, krb5_const_principal tgt_name, const EncTicketPart *tgt, const krb5_keyblock *replykey, int rk_is_subkey, const EncryptionKey *serverkey, const krb5_keyblock *sessionkey, krb5_kvno kvno, AuthorizationData *auth_data, hdb_entry_ex *server, krb5_principal server_principal, const char *server_name, hdb_entry_ex *client, krb5_principal client_principal, const char *tgt_realm, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, krb5_principals spp, const krb5_data *rspac, const METHOD_DATA *enc_pa_data, const char **e_text, krb5_data *reply) { KDC_REP rep; EncKDCRepPart ek; EncTicketPart et; KDCOptions f = b->kdc_options; krb5_error_code ret; int is_weak = 0; memset(&rep, 0, sizeof(rep)); memset(&et, 0, sizeof(et)); memset(&ek, 0, sizeof(ek)); rep.pvno = 5; rep.msg_type = krb_tgs_rep; et.authtime = tgt->authtime; _kdc_fix_time(&b->till); et.endtime = min(tgt->endtime, *b->till); ALLOC(et.starttime); *et.starttime = kdc_time; ret = check_tgs_flags(context, config, b, tgt, &et); if(ret) goto out; /* We should check the transited encoding if: 1) the request doesn't ask not to be checked 2) globally enforcing a check 3) principal requires checking 4) we allow non-check per-principal, but principal isn't marked as allowing this 5) we don't globally allow this */ #define GLOBAL_FORCE_TRANSITED_CHECK \ (config->trpolicy == TRPOLICY_ALWAYS_CHECK) #define GLOBAL_ALLOW_PER_PRINCIPAL \ (config->trpolicy == TRPOLICY_ALLOW_PER_PRINCIPAL) #define GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK \ (config->trpolicy == TRPOLICY_ALWAYS_HONOUR_REQUEST) /* these will consult the database in future release */ #define PRINCIPAL_FORCE_TRANSITED_CHECK(P) 0 #define PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(P) 0 ret = fix_transited_encoding(context, config, !f.disable_transited_check || GLOBAL_FORCE_TRANSITED_CHECK || PRINCIPAL_FORCE_TRANSITED_CHECK(server) || !((GLOBAL_ALLOW_PER_PRINCIPAL && PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(server)) || GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK), &tgt->transited, &et, krb5_principal_get_realm(context, client_principal), krb5_principal_get_realm(context, server->entry.principal), tgt_realm); if(ret) goto out; copy_Realm(&server_principal->realm, &rep.ticket.realm); _krb5_principal2principalname(&rep.ticket.sname, server_principal); copy_Realm(&tgt_name->realm, &rep.crealm); /* if (f.request_anonymous) _kdc_make_anonymous_principalname (&rep.cname); else */ copy_PrincipalName(&tgt_name->name, &rep.cname); rep.ticket.tkt_vno = 5; ek.caddr = et.caddr; { time_t life; life = et.endtime - *et.starttime; if(client && client->entry.max_life) life = min(life, *client->entry.max_life); if(server->entry.max_life) life = min(life, *server->entry.max_life); et.endtime = *et.starttime + life; } if(f.renewable_ok && tgt->flags.renewable && et.renew_till == NULL && et.endtime < *b->till && tgt->renew_till != NULL) { et.flags.renewable = 1; ALLOC(et.renew_till); *et.renew_till = *b->till; } if(et.renew_till){ time_t renew; renew = *et.renew_till - *et.starttime; if(client && client->entry.max_renew) renew = min(renew, *client->entry.max_renew); if(server->entry.max_renew) renew = min(renew, *server->entry.max_renew); *et.renew_till = *et.starttime + renew; } if(et.renew_till){ *et.renew_till = min(*et.renew_till, *tgt->renew_till); *et.starttime = min(*et.starttime, *et.renew_till); et.endtime = min(et.endtime, *et.renew_till); } *et.starttime = min(*et.starttime, et.endtime); if(*et.starttime == et.endtime){ ret = KRB5KDC_ERR_NEVER_VALID; goto out; } if(et.renew_till && et.endtime == *et.renew_till){ free(et.renew_till); et.renew_till = NULL; et.flags.renewable = 0; } et.flags.pre_authent = tgt->flags.pre_authent; et.flags.hw_authent = tgt->flags.hw_authent; et.flags.anonymous = tgt->flags.anonymous; et.flags.ok_as_delegate = server->entry.flags.ok_as_delegate; if(rspac->length) { /* * No not need to filter out the any PAC from the * auth_data since it's signed by the KDC. */ ret = _kdc_tkt_add_if_relevant_ad(context, &et, KRB5_AUTHDATA_WIN2K_PAC, rspac); if (ret) goto out; } if (auth_data) { unsigned int i = 0; /* XXX check authdata */ if (et.authorization_data == NULL) { et.authorization_data = calloc(1, sizeof(*et.authorization_data)); if (et.authorization_data == NULL) { ret = ENOMEM; krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } for(i = 0; i < auth_data->len ; i++) { ret = add_AuthorizationData(et.authorization_data, &auth_data->val[i]); if (ret) { krb5_set_error_message(context, ret, "malloc: out of memory"); goto out; } } /* Filter out type KRB5SignedPath */ ret = find_KRB5SignedPath(context, et.authorization_data, NULL); if (ret == 0) { if (et.authorization_data->len == 1) { free_AuthorizationData(et.authorization_data); free(et.authorization_data); et.authorization_data = NULL; } else { AuthorizationData *ad = et.authorization_data; free_AuthorizationDataElement(&ad->val[ad->len - 1]); ad->len--; } } } ret = krb5_copy_keyblock_contents(context, sessionkey, &et.key); if (ret) goto out; et.crealm = tgt_name->realm; et.cname = tgt_name->name; ek.key = et.key; /* MIT must have at least one last_req */ ek.last_req.val = calloc(1, sizeof(*ek.last_req.val)); if (ek.last_req.val == NULL) { ret = ENOMEM; goto out; } ek.last_req.len = 1; /* set after alloc to avoid null deref on cleanup */ ek.nonce = b->nonce; ek.flags = et.flags; ek.authtime = et.authtime; ek.starttime = et.starttime; ek.endtime = et.endtime; ek.renew_till = et.renew_till; ek.srealm = rep.ticket.realm; ek.sname = rep.ticket.sname; _kdc_log_timestamp(context, config, "TGS-REQ", et.authtime, et.starttime, et.endtime, et.renew_till); /* Don't sign cross realm tickets, they can't be checked anyway */ { char *r = get_krbtgt_realm(&ek.sname); if (r == NULL || strcmp(r, ek.srealm) == 0) { ret = _kdc_add_KRB5SignedPath(context, config, krbtgt, krbtgt_etype, client_principal, NULL, spp, &et); if (ret) goto out; } } if (enc_pa_data->len) { rep.padata = calloc(1, sizeof(*rep.padata)); if (rep.padata == NULL) { ret = ENOMEM; goto out; } ret = copy_METHOD_DATA(enc_pa_data, rep.padata); if (ret) goto out; } if (krb5_enctype_valid(context, serverkey->keytype) != 0 && _kdc_is_weak_exception(server->entry.principal, serverkey->keytype)) { krb5_enctype_enable(context, serverkey->keytype); is_weak = 1; } /* It is somewhat unclear where the etype in the following encryption should come from. What we have is a session key in the passed tgt, and a list of preferred etypes *for the new ticket*. Should we pick the best possible etype, given the keytype in the tgt, or should we look at the etype list here as well? What if the tgt session key is DES3 and we want a ticket with a (say) CAST session key. Should the DES3 etype be added to the etype list, even if we don't want a session key with DES3? */ ret = _kdc_encode_reply(context, config, NULL, 0, &rep, &et, &ek, serverkey->keytype, kvno, serverkey, 0, replykey, rk_is_subkey, e_text, reply); if (is_weak) krb5_enctype_disable(context, serverkey->keytype); out: free_TGS_REP(&rep); free_TransitedEncoding(&et.transited); if(et.starttime) free(et.starttime); if(et.renew_till) free(et.renew_till); if(et.authorization_data) { free_AuthorizationData(et.authorization_data); free(et.authorization_data); } free_LastReq(&ek.last_req); memset(et.key.keyvalue.data, 0, et.key.keyvalue.length); free_EncryptionKey(&et.key); return ret; }
168,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothOptionsHandler::GenerateFakeDeviceList() { GenerateFakeDiscoveredDevice( "Fake Wireless Keyboard", "01-02-03-04-05-06", "input-keyboard", true, true); GenerateFakeDiscoveredDevice( "Fake Wireless Mouse", "02-03-04-05-06-01", "input-mouse", true, false); GenerateFakeDiscoveredDevice( "Fake Wireless Headset", "03-04-05-06-01-02", "headset", false, false); GenerateFakePairing( "Fake Connecting Keyboard", "04-05-06-01-02-03", "input-keyboard", "bluetoothRemotePasskey"); GenerateFakePairing( "Fake Connecting Phone", "05-06-01-02-03-04", "phone", "bluetoothConfirmPasskey"); GenerateFakePairing( "Fake Connecting Headset", "06-01-02-03-04-05", "headset", "bluetoothEnterPasskey"); web_ui_->CallJavascriptFunction( "options.SystemOptions.notifyBluetoothSearchComplete"); } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::GenerateFakeDeviceList() { GenerateFakeDevice( "Fake Wireless Keyboard", "01-02-03-04-05-06", "input-keyboard", true, true, ""); GenerateFakeDevice( "Fake Wireless Mouse", "02-03-04-05-06-01", "input-mouse", true, false, ""); GenerateFakeDevice( "Fake Wireless Headset", "03-04-05-06-01-02", "headset", false, false, ""); GenerateFakeDevice( "Fake Connecting Keyboard", "04-05-06-01-02-03", "input-keyboard", false, false, "bluetoothRemotePasskey"); GenerateFakeDevice( "Fake Connecting Phone", "05-06-01-02-03-04", "phone", false, false, "bluetoothConfirmPasskey"); GenerateFakeDevice( "Fake Connecting Headset", "06-01-02-03-04-05", "headset", false, false, "bluetoothEnterPasskey"); web_ui_->CallJavascriptFunction( "options.SystemOptions.notifyBluetoothSearchComplete"); }
170,968
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int m88rs2000_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[] = { 0x51 }; u8 ibuf[] = { 0 }; if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); d->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, d->fe_adap[0].fe, &dw2104_ts2020_config, &d->dev->i2c_adap)) { info("Attached RS2000/TS2020!"); return 0; } info("Failed to attach RS2000/TS2020!"); return -EIO; } Commit Message: [media] dw2102: don't do DMA on stack On Kernel 4.9, WARNINGs about doing DMA on stack are hit at the dw2102 driver: one in su3000_power_ctrl() and the other in tt_s2_4600_frontend_attach(). Both were due to the use of buffers on the stack as parameters to dvb_usb_generic_rw() and the resulting attempt to do DMA with them. The device was non-functional as a result. So, switch this driver over to use a buffer within the device state structure, as has been done with other DVB-USB drivers. Tested with TechnoTrend TT-connect S2-4600. [[email protected]: fixed a warning at su3000_i2c_transfer() that state var were dereferenced before check 'd'] Signed-off-by: Jonathan McDowell <[email protected]> Cc: <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
static int m88rs2000_frontend_attach(struct dvb_usb_adapter *d) static int m88rs2000_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; mutex_lock(&d->data_mutex); state->data[0] = 0x51; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) err("command 0x51 transfer failed."); mutex_unlock(&d->data_mutex); adap->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config, &d->i2c_adap); if (adap->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, adap->fe_adap[0].fe, &dw2104_ts2020_config, &d->i2c_adap)) { info("Attached RS2000/TS2020!"); return 0; } info("Failed to attach RS2000/TS2020!"); return -EIO; }
168,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_venc::set_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_IN OMX_PTR configData) { (void)hComp; if (configData == NULL) { DEBUG_PRINT_ERROR("ERROR: param is null"); return OMX_ErrorBadParameter; } if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: config called in Invalid state"); return OMX_ErrorIncorrectStateOperation; } switch ((int)configIndex) { case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData); DEBUG_PRINT_HIGH("set_config(): OMX_IndexConfigVideoBitrate (%u)", (unsigned int)pParam->nEncodeBitrate); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_config(configData, OMX_IndexConfigVideoBitrate) != true) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigVideoBitrate failed"); return OMX_ErrorUnsupportedSetting; } m_sConfigBitrate.nEncodeBitrate = pParam->nEncodeBitrate; m_sParamBitrate.nTargetBitrate = pParam->nEncodeBitrate; m_sOutPortDef.format.video.nBitrate = pParam->nEncodeBitrate; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexConfigVideoFramerate: { OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData); DEBUG_PRINT_HIGH("set_config(): OMX_IndexConfigVideoFramerate (0x%x)", (unsigned int)pParam->xEncodeFramerate); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_config(configData, OMX_IndexConfigVideoFramerate) != true) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigVideoFramerate failed"); return OMX_ErrorUnsupportedSetting; } m_sConfigFramerate.xEncodeFramerate = pParam->xEncodeFramerate; m_sOutPortDef.format.video.xFramerate = pParam->xEncodeFramerate; m_sOutPortFormat.xFramerate = pParam->xEncodeFramerate; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case QOMX_IndexConfigVideoIntraperiod: { QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData); DEBUG_PRINT_HIGH("set_config(): QOMX_IndexConfigVideoIntraperiod"); if (pParam->nPortIndex == PORT_INDEX_OUT) { #ifdef MAX_RES_720P if (pParam->nBFrames > 0) { DEBUG_PRINT_ERROR("B frames not supported"); return OMX_ErrorUnsupportedSetting; } #endif DEBUG_PRINT_HIGH("Old: P/B frames = %u/%u, New: P/B frames = %u/%u", (unsigned int)m_sIntraperiod.nPFrames, (unsigned int)m_sIntraperiod.nBFrames, (unsigned int)pParam->nPFrames, (unsigned int)pParam->nBFrames); if (m_sIntraperiod.nBFrames != pParam->nBFrames) { if(hier_b_enabled && m_state == OMX_StateLoaded) { DEBUG_PRINT_INFO("B-frames setting is supported if HierB is enabled"); } else { DEBUG_PRINT_HIGH("Dynamically changing B-frames not supported"); return OMX_ErrorUnsupportedSetting; } } if (handle->venc_set_config(configData, (OMX_INDEXTYPE) QOMX_IndexConfigVideoIntraperiod) != true) { DEBUG_PRINT_ERROR("ERROR: Setting QOMX_IndexConfigVideoIntraperiod failed"); return OMX_ErrorUnsupportedSetting; } m_sIntraperiod.nPFrames = pParam->nPFrames; m_sIntraperiod.nBFrames = pParam->nBFrames; m_sIntraperiod.nIDRPeriod = pParam->nIDRPeriod; if (m_sOutPortFormat.eCompressionFormat == OMX_VIDEO_CodingMPEG4) { m_sParamMPEG4.nPFrames = pParam->nPFrames; if (m_sParamMPEG4.eProfile != OMX_VIDEO_MPEG4ProfileSimple) m_sParamMPEG4.nBFrames = pParam->nBFrames; else m_sParamMPEG4.nBFrames = 0; } else if (m_sOutPortFormat.eCompressionFormat == OMX_VIDEO_CodingH263) { m_sParamH263.nPFrames = pParam->nPFrames; } else { m_sParamAVC.nPFrames = pParam->nPFrames; if ((m_sParamAVC.eProfile != OMX_VIDEO_AVCProfileBaseline) && (m_sParamAVC.eProfile != (OMX_VIDEO_AVCPROFILETYPE) QOMX_VIDEO_AVCProfileConstrainedBaseline)) m_sParamAVC.nBFrames = pParam->nBFrames; else m_sParamAVC.nBFrames = 0; } } else { DEBUG_PRINT_ERROR("ERROR: (QOMX_IndexConfigVideoIntraperiod) Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE* pParam = reinterpret_cast<OMX_CONFIG_INTRAREFRESHVOPTYPE*>(configData); DEBUG_PRINT_HIGH("set_config(): OMX_IndexConfigVideoIntraVOPRefresh"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_config(configData, OMX_IndexConfigVideoIntraVOPRefresh) != true) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigVideoIntraVOPRefresh failed"); return OMX_ErrorUnsupportedSetting; } m_sConfigIntraRefreshVOP.IntraRefreshVOP = pParam->IntraRefreshVOP; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexConfigCommonRotate: { OMX_CONFIG_ROTATIONTYPE *pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData); OMX_S32 nRotation; if (pParam->nPortIndex != PORT_INDEX_OUT) { DEBUG_PRINT_ERROR("ERROR: Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } if ( pParam->nRotation == 0 || pParam->nRotation == 90 || pParam->nRotation == 180 || pParam->nRotation == 270 ) { DEBUG_PRINT_HIGH("set_config: Rotation Angle %u", (unsigned int)pParam->nRotation); } else { DEBUG_PRINT_ERROR("ERROR: un supported Rotation %u", (unsigned int)pParam->nRotation); return OMX_ErrorUnsupportedSetting; } nRotation = pParam->nRotation - m_sConfigFrameRotation.nRotation; if (nRotation < 0) nRotation = -nRotation; if (nRotation == 90 || nRotation == 270) { DEBUG_PRINT_HIGH("set_config: updating device Dims"); if (handle->venc_set_config(configData, OMX_IndexConfigCommonRotate) != true) { DEBUG_PRINT_ERROR("ERROR: Set OMX_IndexConfigCommonRotate failed"); return OMX_ErrorUnsupportedSetting; } else { OMX_U32 nFrameWidth; OMX_U32 nFrameHeight; DEBUG_PRINT_HIGH("set_config: updating port Dims"); nFrameWidth = m_sOutPortDef.format.video.nFrameWidth; nFrameHeight = m_sOutPortDef.format.video.nFrameHeight; m_sOutPortDef.format.video.nFrameWidth = nFrameHeight; m_sOutPortDef.format.video.nFrameHeight = nFrameWidth; m_sConfigFrameRotation.nRotation = pParam->nRotation; } } else { m_sConfigFrameRotation.nRotation = pParam->nRotation; } break; } case OMX_QcomIndexConfigVideoFramePackingArrangement: { DEBUG_PRINT_HIGH("set_config(): OMX_QcomIndexConfigVideoFramePackingArrangement"); if (m_sOutPortFormat.eCompressionFormat == OMX_VIDEO_CodingAVC) { OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; extra_data_handle.set_frame_pack_data(configFmt); } else { DEBUG_PRINT_ERROR("ERROR: FramePackingData not supported for non AVC compression"); } break; } case QOMX_IndexConfigVideoLTRPeriod: { QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE* pParam = (QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE*)configData; if (!handle->venc_set_config(configData, (OMX_INDEXTYPE)QOMX_IndexConfigVideoLTRPeriod)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR period failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigLTRPeriod, pParam, sizeof(m_sConfigLTRPeriod)); break; } case OMX_IndexConfigVideoVp8ReferenceFrame: { OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam = (OMX_VIDEO_VP8REFERENCEFRAMETYPE*) configData; if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE) OMX_IndexConfigVideoVp8ReferenceFrame)) { DEBUG_PRINT_ERROR("ERROR: Setting VP8 reference frame"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigVp8ReferenceFrame, pParam, sizeof(m_sConfigVp8ReferenceFrame)); break; } case QOMX_IndexConfigVideoLTRUse: { QOMX_VIDEO_CONFIG_LTRUSE_TYPE* pParam = (QOMX_VIDEO_CONFIG_LTRUSE_TYPE*)configData; if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)QOMX_IndexConfigVideoLTRUse)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR use failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigLTRUse, pParam, sizeof(m_sConfigLTRUse)); break; } case QOMX_IndexConfigVideoLTRMark: { QOMX_VIDEO_CONFIG_LTRMARK_TYPE* pParam = (QOMX_VIDEO_CONFIG_LTRMARK_TYPE*)configData; if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)QOMX_IndexConfigVideoLTRMark)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR mark failed"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexConfigVideoAVCIntraPeriod: { OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam = (OMX_VIDEO_CONFIG_AVCINTRAPERIOD*) configData; DEBUG_PRINT_LOW("set_config: OMX_IndexConfigVideoAVCIntraPeriod"); if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)OMX_IndexConfigVideoAVCIntraPeriod)) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigVideoAVCIntraPeriod failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigAVCIDRPeriod, pParam, sizeof(m_sConfigAVCIDRPeriod)); break; } case OMX_IndexConfigCommonDeinterlace: { OMX_VIDEO_CONFIG_DEINTERLACE *pParam = (OMX_VIDEO_CONFIG_DEINTERLACE*) configData; DEBUG_PRINT_LOW("set_config: OMX_IndexConfigCommonDeinterlace"); if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)OMX_IndexConfigCommonDeinterlace)) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigCommonDeinterlace failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigDeinterlace, pParam, sizeof(m_sConfigDeinterlace)); break; } case OMX_QcomIndexConfigVideoVencPerfMode: { QOMX_EXTNINDEX_VIDEO_PERFMODE* pParam = (QOMX_EXTNINDEX_VIDEO_PERFMODE*)configData; if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)OMX_QcomIndexConfigVideoVencPerfMode)) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_QcomIndexConfigVideoVencPerfMode failed"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexConfigPriority: { if (!handle->venc_set_config(configData, (OMX_INDEXTYPE)OMX_IndexConfigPriority)) { DEBUG_PRINT_ERROR("Failed to set OMX_IndexConfigPriority"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexConfigOperatingRate: { if (!handle->venc_set_config(configData, (OMX_INDEXTYPE)OMX_IndexConfigOperatingRate)) { DEBUG_PRINT_ERROR("Failed to set OMX_IndexConfigOperatingRate"); return handle->hw_overload ? OMX_ErrorInsufficientResources : OMX_ErrorUnsupportedSetting; } break; } default: DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex); break; } return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
OMX_ERRORTYPE omx_venc::set_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_IN OMX_PTR configData) { (void)hComp; if (configData == NULL) { DEBUG_PRINT_ERROR("ERROR: param is null"); return OMX_ErrorBadParameter; } if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: config called in Invalid state"); return OMX_ErrorIncorrectStateOperation; } switch ((int)configIndex) { case OMX_IndexConfigVideoBitrate: { VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_BITRATETYPE); OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData); DEBUG_PRINT_HIGH("set_config(): OMX_IndexConfigVideoBitrate (%u)", (unsigned int)pParam->nEncodeBitrate); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_config(configData, OMX_IndexConfigVideoBitrate) != true) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigVideoBitrate failed"); return OMX_ErrorUnsupportedSetting; } m_sConfigBitrate.nEncodeBitrate = pParam->nEncodeBitrate; m_sParamBitrate.nTargetBitrate = pParam->nEncodeBitrate; m_sOutPortDef.format.video.nBitrate = pParam->nEncodeBitrate; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexConfigVideoFramerate: { VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_FRAMERATETYPE); OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData); DEBUG_PRINT_HIGH("set_config(): OMX_IndexConfigVideoFramerate (0x%x)", (unsigned int)pParam->xEncodeFramerate); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_config(configData, OMX_IndexConfigVideoFramerate) != true) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigVideoFramerate failed"); return OMX_ErrorUnsupportedSetting; } m_sConfigFramerate.xEncodeFramerate = pParam->xEncodeFramerate; m_sOutPortDef.format.video.xFramerate = pParam->xEncodeFramerate; m_sOutPortFormat.xFramerate = pParam->xEncodeFramerate; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case QOMX_IndexConfigVideoIntraperiod: { VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_INTRAPERIODTYPE); QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData); DEBUG_PRINT_HIGH("set_config(): QOMX_IndexConfigVideoIntraperiod"); if (pParam->nPortIndex == PORT_INDEX_OUT) { #ifdef MAX_RES_720P if (pParam->nBFrames > 0) { DEBUG_PRINT_ERROR("B frames not supported"); return OMX_ErrorUnsupportedSetting; } #endif DEBUG_PRINT_HIGH("Old: P/B frames = %u/%u, New: P/B frames = %u/%u", (unsigned int)m_sIntraperiod.nPFrames, (unsigned int)m_sIntraperiod.nBFrames, (unsigned int)pParam->nPFrames, (unsigned int)pParam->nBFrames); if (m_sIntraperiod.nBFrames != pParam->nBFrames) { if(hier_b_enabled && m_state == OMX_StateLoaded) { DEBUG_PRINT_INFO("B-frames setting is supported if HierB is enabled"); } else { DEBUG_PRINT_HIGH("Dynamically changing B-frames not supported"); return OMX_ErrorUnsupportedSetting; } } if (handle->venc_set_config(configData, (OMX_INDEXTYPE) QOMX_IndexConfigVideoIntraperiod) != true) { DEBUG_PRINT_ERROR("ERROR: Setting QOMX_IndexConfigVideoIntraperiod failed"); return OMX_ErrorUnsupportedSetting; } m_sIntraperiod.nPFrames = pParam->nPFrames; m_sIntraperiod.nBFrames = pParam->nBFrames; m_sIntraperiod.nIDRPeriod = pParam->nIDRPeriod; if (m_sOutPortFormat.eCompressionFormat == OMX_VIDEO_CodingMPEG4) { m_sParamMPEG4.nPFrames = pParam->nPFrames; if (m_sParamMPEG4.eProfile != OMX_VIDEO_MPEG4ProfileSimple) m_sParamMPEG4.nBFrames = pParam->nBFrames; else m_sParamMPEG4.nBFrames = 0; } else if (m_sOutPortFormat.eCompressionFormat == OMX_VIDEO_CodingH263) { m_sParamH263.nPFrames = pParam->nPFrames; } else { m_sParamAVC.nPFrames = pParam->nPFrames; if ((m_sParamAVC.eProfile != OMX_VIDEO_AVCProfileBaseline) && (m_sParamAVC.eProfile != (OMX_VIDEO_AVCPROFILETYPE) QOMX_VIDEO_AVCProfileConstrainedBaseline)) m_sParamAVC.nBFrames = pParam->nBFrames; else m_sParamAVC.nBFrames = 0; } } else { DEBUG_PRINT_ERROR("ERROR: (QOMX_IndexConfigVideoIntraperiod) Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexConfigVideoIntraVOPRefresh: { VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_INTRAREFRESHVOPTYPE); OMX_CONFIG_INTRAREFRESHVOPTYPE* pParam = reinterpret_cast<OMX_CONFIG_INTRAREFRESHVOPTYPE*>(configData); DEBUG_PRINT_HIGH("set_config(): OMX_IndexConfigVideoIntraVOPRefresh"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_config(configData, OMX_IndexConfigVideoIntraVOPRefresh) != true) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigVideoIntraVOPRefresh failed"); return OMX_ErrorUnsupportedSetting; } m_sConfigIntraRefreshVOP.IntraRefreshVOP = pParam->IntraRefreshVOP; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexConfigCommonRotate: { VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_ROTATIONTYPE); OMX_CONFIG_ROTATIONTYPE *pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData); OMX_S32 nRotation; if (pParam->nPortIndex != PORT_INDEX_OUT) { DEBUG_PRINT_ERROR("ERROR: Unsupported port index: %u", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } if ( pParam->nRotation == 0 || pParam->nRotation == 90 || pParam->nRotation == 180 || pParam->nRotation == 270 ) { DEBUG_PRINT_HIGH("set_config: Rotation Angle %u", (unsigned int)pParam->nRotation); } else { DEBUG_PRINT_ERROR("ERROR: un supported Rotation %u", (unsigned int)pParam->nRotation); return OMX_ErrorUnsupportedSetting; } nRotation = pParam->nRotation - m_sConfigFrameRotation.nRotation; if (nRotation < 0) nRotation = -nRotation; if (nRotation == 90 || nRotation == 270) { DEBUG_PRINT_HIGH("set_config: updating device Dims"); if (handle->venc_set_config(configData, OMX_IndexConfigCommonRotate) != true) { DEBUG_PRINT_ERROR("ERROR: Set OMX_IndexConfigCommonRotate failed"); return OMX_ErrorUnsupportedSetting; } else { OMX_U32 nFrameWidth; OMX_U32 nFrameHeight; DEBUG_PRINT_HIGH("set_config: updating port Dims"); nFrameWidth = m_sOutPortDef.format.video.nFrameWidth; nFrameHeight = m_sOutPortDef.format.video.nFrameHeight; m_sOutPortDef.format.video.nFrameWidth = nFrameHeight; m_sOutPortDef.format.video.nFrameHeight = nFrameWidth; m_sConfigFrameRotation.nRotation = pParam->nRotation; } } else { m_sConfigFrameRotation.nRotation = pParam->nRotation; } break; } case OMX_QcomIndexConfigVideoFramePackingArrangement: { DEBUG_PRINT_HIGH("set_config(): OMX_QcomIndexConfigVideoFramePackingArrangement"); if (m_sOutPortFormat.eCompressionFormat == OMX_VIDEO_CodingAVC) { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_FRAME_PACK_ARRANGEMENT); OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; extra_data_handle.set_frame_pack_data(configFmt); } else { DEBUG_PRINT_ERROR("ERROR: FramePackingData not supported for non AVC compression"); } break; } case QOMX_IndexConfigVideoLTRPeriod: { VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE); QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE* pParam = (QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE*)configData; if (!handle->venc_set_config(configData, (OMX_INDEXTYPE)QOMX_IndexConfigVideoLTRPeriod)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR period failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigLTRPeriod, pParam, sizeof(m_sConfigLTRPeriod)); break; } case OMX_IndexConfigVideoVp8ReferenceFrame: { VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_VP8REFERENCEFRAMETYPE); OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam = (OMX_VIDEO_VP8REFERENCEFRAMETYPE*) configData; if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE) OMX_IndexConfigVideoVp8ReferenceFrame)) { DEBUG_PRINT_ERROR("ERROR: Setting VP8 reference frame"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigVp8ReferenceFrame, pParam, sizeof(m_sConfigVp8ReferenceFrame)); break; } case QOMX_IndexConfigVideoLTRUse: { VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_CONFIG_LTRUSE_TYPE); QOMX_VIDEO_CONFIG_LTRUSE_TYPE* pParam = (QOMX_VIDEO_CONFIG_LTRUSE_TYPE*)configData; if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)QOMX_IndexConfigVideoLTRUse)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR use failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigLTRUse, pParam, sizeof(m_sConfigLTRUse)); break; } case QOMX_IndexConfigVideoLTRMark: { VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_CONFIG_LTRMARK_TYPE); QOMX_VIDEO_CONFIG_LTRMARK_TYPE* pParam = (QOMX_VIDEO_CONFIG_LTRMARK_TYPE*)configData; if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)QOMX_IndexConfigVideoLTRMark)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR mark failed"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexConfigVideoAVCIntraPeriod: { VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_AVCINTRAPERIOD); OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam = (OMX_VIDEO_CONFIG_AVCINTRAPERIOD*) configData; DEBUG_PRINT_LOW("set_config: OMX_IndexConfigVideoAVCIntraPeriod"); if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)OMX_IndexConfigVideoAVCIntraPeriod)) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigVideoAVCIntraPeriod failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigAVCIDRPeriod, pParam, sizeof(m_sConfigAVCIDRPeriod)); break; } case OMX_IndexConfigCommonDeinterlace: { VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_DEINTERLACE); OMX_VIDEO_CONFIG_DEINTERLACE *pParam = (OMX_VIDEO_CONFIG_DEINTERLACE*) configData; DEBUG_PRINT_LOW("set_config: OMX_IndexConfigCommonDeinterlace"); if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)OMX_IndexConfigCommonDeinterlace)) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_IndexConfigCommonDeinterlace failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sConfigDeinterlace, pParam, sizeof(m_sConfigDeinterlace)); break; } case OMX_QcomIndexConfigVideoVencPerfMode: { VALIDATE_OMX_PARAM_DATA(configData, QOMX_EXTNINDEX_VIDEO_PERFMODE); QOMX_EXTNINDEX_VIDEO_PERFMODE* pParam = (QOMX_EXTNINDEX_VIDEO_PERFMODE*)configData; if (!handle->venc_set_config(pParam, (OMX_INDEXTYPE)OMX_QcomIndexConfigVideoVencPerfMode)) { DEBUG_PRINT_ERROR("ERROR: Setting OMX_QcomIndexConfigVideoVencPerfMode failed"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexConfigPriority: { VALIDATE_OMX_PARAM_DATA(configData, OMX_PARAM_U32TYPE); if (!handle->venc_set_config(configData, (OMX_INDEXTYPE)OMX_IndexConfigPriority)) { DEBUG_PRINT_ERROR("Failed to set OMX_IndexConfigPriority"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexConfigOperatingRate: { VALIDATE_OMX_PARAM_DATA(configData, OMX_PARAM_U32TYPE); if (!handle->venc_set_config(configData, (OMX_INDEXTYPE)OMX_IndexConfigOperatingRate)) { DEBUG_PRINT_ERROR("Failed to set OMX_IndexConfigOperatingRate"); return handle->hw_overload ? OMX_ErrorInsufficientResources : OMX_ErrorUnsupportedSetting; } break; } default: DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex); break; } return OMX_ErrorNone; }
173,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out) { #if 0 jp2_pclr_t *pclr = &box->data.pclr; #endif /* Eliminate warning about unused variable. */ box = 0; out = 0; return -1; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out) { #if 0 jp2_pclr_t *pclr = &box->data.pclr; #endif /* Eliminate warning about unused variable. */ box = 0; out = 0; return -1; }
168,324
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile( const FilePath::StringType& filepath, const std::string& output) { VLOG(0) << "Writing renderer heap profile dump to: " << filepath; file_util::WriteFile(FilePath(filepath), output.c_str(), output.size()); } Commit Message: Disable tcmalloc profile files. BUG=154983 [email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile(
170,664
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *get_object( FILE *fp, int obj_id, const xref_t *xref, size_t *size, int *is_stream) { static const int blk_sz = 256; int i, total_sz, read_sz, n_blks, search, stream; size_t obj_sz; char *c, *data; long start; const xref_entry_t *entry; if (size) *size = 0; if (is_stream) *is_stream = 0; start = ftell(fp); /* Find object */ entry = NULL; for (i=0; i<xref->n_entries; i++) if (xref->entries[i].obj_id == obj_id) { entry = &xref->entries[i]; break; } if (!entry) return NULL; /* Jump to object start */ fseek(fp, entry->offset, SEEK_SET); /* Initial allocate */ obj_sz = 0; /* Bytes in object */ total_sz = 0; /* Bytes read in */ n_blks = 1; data = malloc(blk_sz * n_blks); memset(data, 0, blk_sz * n_blks); /* Suck in data */ stream = 0; while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp)) { total_sz += read_sz; *(data + total_sz) = '\0'; if (total_sz + blk_sz >= (blk_sz * n_blks)) data = realloc(data, blk_sz * (++n_blks)); search = total_sz - read_sz; if (search < 0) search = 0; if ((c = strstr(data + search, "endobj"))) { *(c + strlen("endobj") + 1) = '\0'; obj_sz = (void *)strstr(data + search, "endobj") - (void *)data; obj_sz += strlen("endobj") + 1; break; } else if (strstr(data, "stream")) stream = 1; } clearerr(fp); fseek(fp, start, SEEK_SET); if (size) *size = obj_sz; if (is_stream) *is_stream = stream; return data; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787
static char *get_object( FILE *fp, int obj_id, const xref_t *xref, size_t *size, int *is_stream) { static const int blk_sz = 256; int i, total_sz, read_sz, n_blks, search, stream; size_t obj_sz; char *c, *data; long start; const xref_entry_t *entry; if (size) *size = 0; if (is_stream) *is_stream = 0; start = ftell(fp); /* Find object */ entry = NULL; for (i=0; i<xref->n_entries; i++) if (xref->entries[i].obj_id == obj_id) { entry = &xref->entries[i]; break; } if (!entry) return NULL; /* Jump to object start */ fseek(fp, entry->offset, SEEK_SET); /* Initial allocate */ obj_sz = 0; /* Bytes in object */ total_sz = 0; /* Bytes read in */ n_blks = 1; data = safe_calloc(blk_sz * n_blks); /* Suck in data */ stream = 0; while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp)) { total_sz += read_sz; *(data + total_sz) = '\0'; if (total_sz + blk_sz >= (blk_sz * n_blks)) data = realloc(data, blk_sz * (++n_blks)); search = total_sz - read_sz; if (search < 0) search = 0; if ((c = strstr(data + search, "endobj"))) { *(c + strlen("endobj") + 1) = '\0'; obj_sz = (void *)strstr(data + search, "endobj") - (void *)data; obj_sz += strlen("endobj") + 1; break; } else if (strstr(data, "stream")) stream = 1; } clearerr(fp); fseek(fp, start, SEEK_SET); if (size) *size = obj_sz; if (is_stream) *is_stream = stream; return data; }
169,568
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix) { struct pci_dev *pdev = vdev->pdev; unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; int ret; if (!is_irq_none(vdev)) return -EINVAL; vdev->ctx = kzalloc(nvec * sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; /* return the number of supported vectors if we can't get all: */ ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag); if (ret < nvec) { if (ret > 0) pci_free_irq_vectors(pdev); kfree(vdev->ctx); return ret; } vdev->num_ctx = nvec; vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; if (!msix) { /* * Compute the virtual hardware field for max msi vectors - * it is the log base 2 of the number of vectors. */ vdev->msi_qmax = fls(nvec * 2 - 1) - 1; } return 0; } Commit Message: vfio/pci: Fix integer overflows, bitmask check The VFIO_DEVICE_SET_IRQS ioctl did not sufficiently sanitize user-supplied integers, potentially allowing memory corruption. This patch adds appropriate integer overflow checks, checks the range bounds for VFIO_IRQ_SET_DATA_NONE, and also verifies that only single element in the VFIO_IRQ_SET_DATA_TYPE_MASK bitmask is set. VFIO_IRQ_SET_ACTION_TYPE_MASK is already correctly checked later in vfio_pci_set_irqs_ioctl(). Furthermore, a kzalloc is changed to a kcalloc because the use of a kzalloc with an integer multiplication allowed an integer overflow condition to be reached without this patch. kcalloc checks for overflow and should prevent a similar occurrence. Signed-off-by: Vlad Tsyrklevich <[email protected]> Signed-off-by: Alex Williamson <[email protected]> CWE ID: CWE-190
static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix) { struct pci_dev *pdev = vdev->pdev; unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; int ret; if (!is_irq_none(vdev)) return -EINVAL; vdev->ctx = kcalloc(nvec, sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; /* return the number of supported vectors if we can't get all: */ ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag); if (ret < nvec) { if (ret > 0) pci_free_irq_vectors(pdev); kfree(vdev->ctx); return ret; } vdev->num_ctx = nvec; vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; if (!msix) { /* * Compute the virtual hardware field for max msi vectors - * it is the log base 2 of the number of vectors. */ vdev->msi_qmax = fls(nvec * 2 - 1) - 1; } return 0; }
166,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __f2fs_set_acl(struct inode *inode, int type, struct posix_acl *acl, struct page *ipage) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; set_acl_inode(inode, inode->i_mode); if (error == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = f2fs_acl_to_disk(acl, &size); if (IS_ERR(value)) { clear_inode_flag(inode, FI_ACL_MODE); return (int)PTR_ERR(value); } } error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); clear_inode_flag(inode, FI_ACL_MODE); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
static int __f2fs_set_acl(struct inode *inode, int type, struct posix_acl *acl, struct page *ipage) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; set_acl_inode(inode, inode->i_mode); } break; case ACL_TYPE_DEFAULT: name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = f2fs_acl_to_disk(acl, &size); if (IS_ERR(value)) { clear_inode_flag(inode, FI_ACL_MODE); return (int)PTR_ERR(value); } } error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); clear_inode_flag(inode, FI_ACL_MODE); return error; }
166,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ivr_read_header(AVFormatContext *s) { unsigned tag, type, len, tlen, value; int i, j, n, count, nb_streams = 0, ret; uint8_t key[256], val[256]; AVIOContext *pb = s->pb; AVStream *st; int64_t pos, offset, temp; pos = avio_tell(pb); tag = avio_rl32(pb); if (tag == MKTAG('.','R','1','M')) { if (avio_rb16(pb) != 1) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); avio_skip(pb, 5); temp = avio_rb64(pb); while (!avio_feof(pb) && temp) { offset = temp; temp = avio_rb64(pb); } avio_skip(pb, offset - avio_tell(pb)); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); if (avio_r8(pb) != 2) return AVERROR_INVALIDDATA; avio_skip(pb, 16); pos = avio_tell(pb); tag = avio_rl32(pb); } if (tag != MKTAG('.','R','E','C')) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 0) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4) { av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) { nb_streams = value = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } for (n = 0; n < nb_streams; n++) { st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) { ret = ffio_ensure_seekback(pb, 4); if (ret < 0) return ret; if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, pb, st, NULL); } else { avio_seek(pb, -4, SEEK_CUR); ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); } if (ret < 0) return ret; } else if (type == 4) { int j; av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) { st->duration = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } } if (avio_r8(pb) != 6) return AVERROR_INVALIDDATA; avio_skip(pb, 12); avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb)); if (avio_r8(pb) != 8) return AVERROR_INVALIDDATA; avio_skip(pb, 8); return 0; } Commit Message: avformat/rmdec: Fix DoS due to lack of eof check Fixes: loop.ivr Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static int ivr_read_header(AVFormatContext *s) { unsigned tag, type, len, tlen, value; int i, j, n, count, nb_streams = 0, ret; uint8_t key[256], val[256]; AVIOContext *pb = s->pb; AVStream *st; int64_t pos, offset, temp; pos = avio_tell(pb); tag = avio_rl32(pb); if (tag == MKTAG('.','R','1','M')) { if (avio_rb16(pb) != 1) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); avio_skip(pb, 5); temp = avio_rb64(pb); while (!avio_feof(pb) && temp) { offset = temp; temp = avio_rb64(pb); } avio_skip(pb, offset - avio_tell(pb)); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); if (avio_r8(pb) != 2) return AVERROR_INVALIDDATA; avio_skip(pb, 16); pos = avio_tell(pb); tag = avio_rl32(pb); } if (tag != MKTAG('.','R','E','C')) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 0) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4) { av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); } av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) { nb_streams = value = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } for (n = 0; n < nb_streams; n++) { st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) { ret = ffio_ensure_seekback(pb, 4); if (ret < 0) return ret; if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, pb, st, NULL); } else { avio_seek(pb, -4, SEEK_CUR); ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); } if (ret < 0) return ret; } else if (type == 4) { int j; av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) { st->duration = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } } if (avio_r8(pb) != 6) return AVERROR_INVALIDDATA; avio_skip(pb, 12); avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb)); if (avio_r8(pb) != 8) return AVERROR_INVALIDDATA; avio_skip(pb, 8); return 0; }
167,778
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ssl3_take_mac(SSL *s) { const char *sender; int slen; if (s->state & SSL_ST_CONNECT) { sender=s->method->ssl3_enc->server_finished_label; sender=s->method->ssl3_enc->client_finished_label; slen=s->method->ssl3_enc->client_finished_label_len; } s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s, sender,slen,s->s3->tmp.peer_finish_md); } Commit Message: CWE ID: CWE-20
static void ssl3_take_mac(SSL *s) { const char *sender; int slen; /* If no new cipher setup return immediately: other functions will * set the appropriate error. */ if (s->s3->tmp.new_cipher == NULL) return; if (s->state & SSL_ST_CONNECT) { sender=s->method->ssl3_enc->server_finished_label; sender=s->method->ssl3_enc->client_finished_label; slen=s->method->ssl3_enc->client_finished_label_len; } s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s, sender,slen,s->s3->tmp.peer_finish_md); }
165,360
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sctp_init_sock(struct sock *sk) { struct net *net = sock_net(sk); struct sctp_sock *sp; pr_debug("%s: sk:%p\n", __func__, sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = net->sctp.max_burst; sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init; sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = net->sctp.rto_initial; sp->rtoinfo.srto_max = net->sctp.rto_max; sp->rtoinfo.srto_min = net->sctp.rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = net->sctp.hb_interval; sp->pathmaxrxt = net->sctp.max_retrans_path; sp->pathmtu = 0; /* allow default discovery */ sp->sackdelay = net->sctp.sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; sp->recvrcvinfo = 0; sp->recvnxtinfo = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ sp->ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!sp->ep) return -ENOMEM; sp->hmac = NULL; sk->sk_destruct = sctp_destruct_sock; SCTP_DBG_OBJCNT_INC(sock); local_bh_disable(); percpu_counter_inc(&sctp_sockets_allocated); sock_prot_inuse_add(net, sk->sk_prot, 1); if (net->sctp.default_auto_asconf) { list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; } else sp->do_auto_asconf = 0; local_bh_enable(); return 0; } Commit Message: sctp: fix ASCONF list handling ->auto_asconf_splist is per namespace and mangled by functions like sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization. Also, the call to inet_sk_copy_descendant() was backuping ->auto_asconf_list through the copy but was not honoring ->do_auto_asconf, which could lead to list corruption if it was different between both sockets. This commit thus fixes the list handling by using ->addr_wq_lock spinlock to protect the list. A special handling is done upon socket creation and destruction for that. Error handlig on sctp_init_sock() will never return an error after having initialized asconf, so sctp_destroy_sock() can be called without addrq_wq_lock. The lock now will be take on sctp_close_sock(), before locking the socket, so we don't do it in inverse order compared to sctp_addr_wq_timeout_handler(). Instead of taking the lock on sctp_sock_migrate() for copying and restoring the list values, it's preferred to avoid rewritting it by implementing sctp_copy_descendant(). Issue was found with a test application that kept flipping sysctl default_auto_asconf on and off, but one could trigger it by issuing simultaneous setsockopt() calls on multiple sockets or by creating/destroying sockets fast enough. This is only triggerable locally. Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).") Reported-by: Ji Jianwen <[email protected]> Suggested-by: Neil Horman <[email protected]> Suggested-by: Hannes Frederic Sowa <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static int sctp_init_sock(struct sock *sk) { struct net *net = sock_net(sk); struct sctp_sock *sp; pr_debug("%s: sk:%p\n", __func__, sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = net->sctp.max_burst; sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init; sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = net->sctp.rto_initial; sp->rtoinfo.srto_max = net->sctp.rto_max; sp->rtoinfo.srto_min = net->sctp.rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = net->sctp.hb_interval; sp->pathmaxrxt = net->sctp.max_retrans_path; sp->pathmtu = 0; /* allow default discovery */ sp->sackdelay = net->sctp.sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; sp->recvrcvinfo = 0; sp->recvnxtinfo = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ sp->ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!sp->ep) return -ENOMEM; sp->hmac = NULL; sk->sk_destruct = sctp_destruct_sock; SCTP_DBG_OBJCNT_INC(sock); local_bh_disable(); percpu_counter_inc(&sctp_sockets_allocated); sock_prot_inuse_add(net, sk->sk_prot, 1); /* Nothing can fail after this block, otherwise * sctp_destroy_sock() will be called without addr_wq_lock held */ if (net->sctp.default_auto_asconf) { spin_lock(&sock_net(sk)->sctp.addr_wq_lock); list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; spin_unlock(&sock_net(sk)->sctp.addr_wq_lock); } else { sp->do_auto_asconf = 0; } local_bh_enable(); return 0; }
166,629
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: interlace_row(png_bytep buffer, png_const_bytep imageRow, unsigned int pixel_size, png_uint_32 w, int pass) { png_uint_32 xin, xout, xstep; /* Note that this can, trivially, be optimized to a memcpy on pass 7, the * code is presented this way to make it easier to understand. In practice * consult the code in the libpng source to see other ways of doing this. */ xin = PNG_PASS_START_COL(pass); xstep = 1U<<PNG_PASS_COL_SHIFT(pass); for (xout=0; xin<w; xin+=xstep) { pixel_copy(buffer, xout, imageRow, xin, pixel_size); ++xout; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
interlace_row(png_bytep buffer, png_const_bytep imageRow,
173,659
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct *desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; desc = get_desc(sel); if (!desc) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc->type & BIT(3))) return -EINVAL; switch ((desc->l << 1) | desc->d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } } Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: [email protected] Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
int insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; if (!get_desc(&desc, sel)) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc.type & BIT(3))) return -EINVAL; switch ((desc.l << 1) | desc.d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } }
169,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int ip_ufo_append_data(struct sock *sk, struct sk_buff_head *queue, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int maxfraglen, unsigned int flags) { struct sk_buff *skb; int err; /* There is support for UDP fragmentation offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb, fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; /* specify the length of each IP datagram fragment */ skb_shinfo(skb)->gso_size = maxfraglen - fragheaderlen; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; __skb_queue_tail(queue, skb); } return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } Commit Message: ip_output: do skb ufo init for peeked non ufo skb as well Now, if user application does: sendto len<mtu flag MSG_MORE sendto len>mtu flag 0 The skb is not treated as fragmented one because it is not initialized that way. So move the initialization to fix this. introduced by: commit e89e9cf539a28df7d0eb1d0a545368e9920b34ac "[IPv4/IPv6]: UFO Scatter-gather approach" Signed-off-by: Jiri Pirko <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
static inline int ip_ufo_append_data(struct sock *sk, struct sk_buff_head *queue, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int maxfraglen, unsigned int flags) { struct sk_buff *skb; int err; /* There is support for UDP fragmentation offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb, fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->csum = 0; __skb_queue_tail(queue, skb); } else if (skb_is_gso(skb)) { goto append; } skb->ip_summed = CHECKSUM_PARTIAL; /* specify the length of each IP datagram fragment */ skb_shinfo(skb)->gso_size = maxfraglen - fragheaderlen; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; append: return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); }
165,986
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ShellBrowserMain(const content::MainFunctionParams& parameters) { bool layout_test_mode = CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree); base::ScopedTempDir browser_context_path_for_layout_tests; if (layout_test_mode) { CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir()); CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kContentShellDataPath, browser_context_path_for_layout_tests.path().MaybeAsASCII()); } scoped_ptr<content::BrowserMainRunner> main_runner_( content::BrowserMainRunner::Create()); int exit_code = main_runner_->Initialize(parameters); if (exit_code >= 0) return exit_code; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kCheckLayoutTestSysDeps)) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); main_runner_->Shutdown(); return 0; } if (layout_test_mode) { content::WebKitTestController test_controller; std::string test_string; CommandLine::StringVector args = CommandLine::ForCurrentProcess()->GetArgs(); size_t command_line_position = 0; bool ran_at_least_once = false; #if defined(OS_ANDROID) std::cout << "#READY\n"; std::cout.flush(); #endif while (GetNextTest(args, &command_line_position, &test_string)) { if (test_string.empty()) continue; if (test_string == "QUIT") break; bool enable_pixel_dumps; std::string pixel_hash; FilePath cwd; GURL test_url = GetURLForLayoutTest( test_string, &cwd, &enable_pixel_dumps, &pixel_hash); if (!content::WebKitTestController::Get()->PrepareForLayoutTest( test_url, cwd, enable_pixel_dumps, pixel_hash)) { break; } ran_at_least_once = true; main_runner_->Run(); if (!content::WebKitTestController::Get()->ResetAfterLayoutTest()) break; } if (!ran_at_least_once) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); } exit_code = 0; } else { exit_code = main_runner_->Run(); } main_runner_->Shutdown(); return exit_code; } Commit Message: [content shell] reset the CWD after each layout test BUG=111316 [email protected] Review URL: https://codereview.chromium.org/11633017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173906 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
int ShellBrowserMain(const content::MainFunctionParams& parameters) { bool layout_test_mode = CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree); base::ScopedTempDir browser_context_path_for_layout_tests; if (layout_test_mode) { CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir()); CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kContentShellDataPath, browser_context_path_for_layout_tests.path().MaybeAsASCII()); } scoped_ptr<content::BrowserMainRunner> main_runner_( content::BrowserMainRunner::Create()); int exit_code = main_runner_->Initialize(parameters); if (exit_code >= 0) return exit_code; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kCheckLayoutTestSysDeps)) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); main_runner_->Shutdown(); return 0; } if (layout_test_mode) { content::WebKitTestController test_controller; std::string test_string; CommandLine::StringVector args = CommandLine::ForCurrentProcess()->GetArgs(); size_t command_line_position = 0; bool ran_at_least_once = false; #if defined(OS_ANDROID) std::cout << "#READY\n"; std::cout.flush(); #endif FilePath original_cwd; { // We're outside of the message loop here, and this is a test. base::ThreadRestrictions::ScopedAllowIO allow_io; file_util::GetCurrentDirectory(&original_cwd); } while (GetNextTest(args, &command_line_position, &test_string)) { if (test_string.empty()) continue; if (test_string == "QUIT") break; bool enable_pixel_dumps; std::string pixel_hash; FilePath cwd; GURL test_url = GetURLForLayoutTest( test_string, &cwd, &enable_pixel_dumps, &pixel_hash); if (!content::WebKitTestController::Get()->PrepareForLayoutTest( test_url, cwd, enable_pixel_dumps, pixel_hash)) { break; } ran_at_least_once = true; main_runner_->Run(); { // We're outside of the message loop here, and this is a test. base::ThreadRestrictions::ScopedAllowIO allow_io; file_util::SetCurrentDirectory(original_cwd); } if (!content::WebKitTestController::Get()->ResetAfterLayoutTest()) break; } if (!ran_at_least_once) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); } exit_code = 0; } else { exit_code = main_runner_->Run(); } main_runner_->Shutdown(); return exit_code; }
171,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_emit_signal2 (MyObject *obj, GError **error) { GHashTable *table; table = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (table, "baz", "cow"); g_hash_table_insert (table, "bar", "foo"); g_signal_emit (obj, signals[SIG2], 0, table); g_hash_table_destroy (table); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_emit_signal2 (MyObject *obj, GError **error)
165,095
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; } Commit Message: avformat/rtpdec_h264: Fix heap-buffer-overflow Fixes: rtp_sdp/poc.sdp Found-by: Bingchang <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (*value == 0 || value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; }
167,744
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigatorImpl::DidFailProvisionalLoadWithError( RenderFrameHostImpl* render_frame_host, const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << render_frame_host->GetRoutingID(); GURL validated_url(params.url); RenderProcessHost* render_process_host = render_frame_host->GetProcess(); render_process_host->FilterURL(false, &validated_url); if (net::ERR_ABORTED == params.error_code) { FrameTreeNode* root = render_frame_host->frame_tree_node()->frame_tree()->root(); if (root->render_manager()->interstitial_page() != NULL) { LOG(WARNING) << "Discarding message during interstitial."; return; } } int expected_pending_entry_id = render_frame_host->navigation_handle() ? render_frame_host->navigation_handle()->pending_nav_entry_id() : 0; DiscardPendingEntryIfNeeded(expected_pending_entry_id); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
void NavigatorImpl::DidFailProvisionalLoadWithError( RenderFrameHostImpl* render_frame_host, const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << render_frame_host->GetRoutingID(); GURL validated_url(params.url); RenderProcessHost* render_process_host = render_frame_host->GetProcess(); render_process_host->FilterURL(false, &validated_url); if (net::ERR_ABORTED == params.error_code) { if (delegate_ && delegate_->ShowingInterstitialPage()) { LOG(WARNING) << "Discarding message during interstitial."; return; } } int expected_pending_entry_id = render_frame_host->navigation_handle() ? render_frame_host->navigation_handle()->pending_nav_entry_id() : 0; DiscardPendingEntryIfNeeded(expected_pending_entry_id); }
172,319
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi, HB_GPOS_SubTable* st, HB_Buffer buffer, HB_UShort flags, HB_UShort context_length, int nesting_level ) { HB_UShort i, j, mark1_index, mark2_index, property, class; HB_Fixed x_mark1_value, y_mark1_value, x_mark2_value, y_mark2_value; HB_Error error; HB_GPOSHeader* gpos = gpi->gpos; HB_MarkMarkPos* mmp = &st->markmark; HB_MarkArray* ma1; HB_Mark2Array* ma2; HB_Mark2Record* m2r; HB_Anchor* mark1_anchor; HB_Anchor* mark2_anchor; HB_Position o; HB_UNUSED(nesting_level); if ( context_length != 0xFFFF && context_length < 1 ) return HB_Err_Not_Covered; if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS ) return HB_Err_Not_Covered; if ( CHECK_Property( gpos->gdef, IN_CURITEM(), flags, &property ) ) return error; error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(), &mark1_index ); if ( error ) return error; /* now we search backwards for a suitable mark glyph until a non-mark glyph */ if ( buffer->in_pos == 0 ) return HB_Err_Not_Covered; i = 1; j = buffer->in_pos - 1; while ( i <= buffer->in_pos ) { error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ), &property ); if ( error ) return error; if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) ) return HB_Err_Not_Covered; if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) { if ( property == (flags & 0xFF00) ) break; } else break; i++; j--; } error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ), &mark2_index ); if ( error ) if ( mark1_index >= ma1->MarkCount ) return ERR(HB_Err_Invalid_SubTable); class = ma1->MarkRecord[mark1_index].Class; mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor; if ( class >= mmp->ClassCount ) return ERR(HB_Err_Invalid_SubTable); ma2 = &mmp->Mark2Array; if ( mark2_index >= ma2->Mark2Count ) return ERR(HB_Err_Invalid_SubTable); m2r = &ma2->Mark2Record[mark2_index]; mark2_anchor = &m2r->Mark2Anchor[class]; error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(), &x_mark1_value, &y_mark1_value ); if ( error ) return error; error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ), &x_mark2_value, &y_mark2_value ); if ( error ) return error; /* anchor points are not cumulative */ o = POSITION( buffer->in_pos ); o->x_pos = x_mark2_value - x_mark1_value; o->y_pos = y_mark2_value - y_mark1_value; o->x_advance = 0; o->y_advance = 0; o->back = 1; (buffer->in_pos)++; return HB_Err_Ok; } Commit Message: CWE ID: CWE-119
static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi, HB_GPOS_SubTable* st, HB_Buffer buffer, HB_UShort flags, HB_UShort context_length, int nesting_level ) { HB_UShort i, j, mark1_index, mark2_index, property, class; HB_Fixed x_mark1_value, y_mark1_value, x_mark2_value, y_mark2_value; HB_Error error; HB_GPOSHeader* gpos = gpi->gpos; HB_MarkMarkPos* mmp = &st->markmark; HB_MarkArray* ma1; HB_Mark2Array* ma2; HB_Mark2Record* m2r; HB_Anchor* mark1_anchor; HB_Anchor* mark2_anchor; HB_Position o; HB_UNUSED(nesting_level); if ( context_length != 0xFFFF && context_length < 1 ) return HB_Err_Not_Covered; if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS ) return HB_Err_Not_Covered; if ( CHECK_Property( gpos->gdef, IN_CURITEM(), flags, &property ) ) return error; error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(), &mark1_index ); if ( error ) return error; /* now we search backwards for a suitable mark glyph until a non-mark glyph */ if ( buffer->in_pos == 0 ) return HB_Err_Not_Covered; i = 1; j = buffer->in_pos - 1; while ( i <= buffer->in_pos ) { error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ), &property ); if ( error ) return error; if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) ) return HB_Err_Not_Covered; if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) { if ( property == (flags & 0xFF00) ) break; } else break; i++; j--; } if ( i > buffer->in_pos ) return HB_Err_Not_Covered; error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ), &mark2_index ); if ( error ) if ( mark1_index >= ma1->MarkCount ) return ERR(HB_Err_Invalid_SubTable); class = ma1->MarkRecord[mark1_index].Class; mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor; if ( class >= mmp->ClassCount ) return ERR(HB_Err_Invalid_SubTable); ma2 = &mmp->Mark2Array; if ( mark2_index >= ma2->Mark2Count ) return ERR(HB_Err_Invalid_SubTable); m2r = &ma2->Mark2Record[mark2_index]; mark2_anchor = &m2r->Mark2Anchor[class]; error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(), &x_mark1_value, &y_mark1_value ); if ( error ) return error; error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ), &x_mark2_value, &y_mark2_value ); if ( error ) return error; /* anchor points are not cumulative */ o = POSITION( buffer->in_pos ); o->x_pos = x_mark2_value - x_mark1_value; o->y_pos = y_mark2_value - y_mark1_value; o->x_advance = 0; o->y_advance = 0; o->back = 1; (buffer->in_pos)++; return HB_Err_Ok; }
165,246
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_strip_alpha_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; that->have_tRNS = 0; that->alphaf = 1; this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_strip_alpha_mod(PNG_CONST image_transform *this, image_transform_png_set_strip_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; that->have_tRNS = 0; that->alphaf = 1; this->next->mod(this->next, that, pp, display); }
173,652
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HTMLCanvasElement::Dispose() { if (PlaceholderFrame()) ReleasePlaceholderFrame(); if (context_) { context_->DetachHost(); context_ = nullptr; } if (canvas2d_bridge_) { canvas2d_bridge_->SetCanvasResourceHost(nullptr); canvas2d_bridge_ = nullptr; } if (gpu_memory_usage_) { DCHECK_GT(global_accelerated_context_count_, 0u); global_accelerated_context_count_--; } global_gpu_memory_usage_ -= gpu_memory_usage_; } Commit Message: Clean up CanvasResourceDispatcher on finalizer We may have pending mojo messages after GC, so we want to drop the dispatcher as soon as possible. Bug: 929757,913964 Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0 Reviewed-on: https://chromium-review.googlesource.com/c/1489175 Reviewed-by: Ken Rockot <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Auto-Submit: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#635833} CWE ID: CWE-416
void HTMLCanvasElement::Dispose() { if (PlaceholderFrame()) ReleasePlaceholderFrame(); // We need to drop frame dispatcher, to prevent mojo calls from completing. frame_dispatcher_ = nullptr; if (context_) { context_->DetachHost(); context_ = nullptr; } if (canvas2d_bridge_) { canvas2d_bridge_->SetCanvasResourceHost(nullptr); canvas2d_bridge_ = nullptr; } if (gpu_memory_usage_) { DCHECK_GT(global_accelerated_context_count_, 0u); global_accelerated_context_count_--; } global_gpu_memory_usage_ -= gpu_memory_usage_; }
173,028
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WarmupURLFetcher::FetchWarmupURL( size_t previous_attempt_counts, const DataReductionProxyServer& proxy_server) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); previous_attempt_counts_ = previous_attempt_counts; DCHECK_LE(0u, previous_attempt_counts_); DCHECK_GE(2u, previous_attempt_counts_); fetch_delay_timer_.Stop(); if (previous_attempt_counts_ == 0) { FetchWarmupURLNow(proxy_server); return; } fetch_delay_timer_.Start( FROM_HERE, GetFetchWaitTime(), base::BindOnce(&WarmupURLFetcher::FetchWarmupURLNow, base::Unretained(this), proxy_server)); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
void WarmupURLFetcher::FetchWarmupURL( size_t previous_attempt_counts, const DataReductionProxyServer& proxy_server) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!params::IsIncludedInHoldbackFieldTrial()); previous_attempt_counts_ = previous_attempt_counts; DCHECK_LE(0u, previous_attempt_counts_); DCHECK_GE(2u, previous_attempt_counts_); fetch_delay_timer_.Stop(); if (previous_attempt_counts_ == 0) { FetchWarmupURLNow(proxy_server); return; } fetch_delay_timer_.Start( FROM_HERE, GetFetchWaitTime(), base::BindOnce(&WarmupURLFetcher::FetchWarmupURLNow, base::Unretained(this), proxy_server)); }
172,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: foreach_nfs_shareopt(const char *shareopts, nfs_shareopt_callback_t callback, void *cookie) { char *shareopts_dup, *opt, *cur, *value; int was_nul, rc; if (shareopts == NULL) return (SA_OK); shareopts_dup = strdup(shareopts); if (shareopts_dup == NULL) return (SA_NO_MEMORY); opt = shareopts_dup; was_nul = 0; while (1) { cur = opt; while (*cur != ',' && *cur != '\0') cur++; if (*cur == '\0') was_nul = 1; *cur = '\0'; if (cur > opt) { value = strchr(opt, '='); if (value != NULL) { *value = '\0'; value++; } rc = callback(opt, value, cookie); if (rc != SA_OK) { free(shareopts_dup); return (rc); } } opt = cur + 1; if (was_nul) break; } free(shareopts_dup); return (0); } Commit Message: Move nfs.c:foreach_nfs_shareopt() to libshare.c:foreach_shareopt() so that it can be (re)used in other parts of libshare. CWE ID: CWE-200
foreach_nfs_shareopt(const char *shareopts,
170,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr) { vcpu->arch.apic->vapic_addr = vapic_addr; if (vapic_addr) __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention); else __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention); } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20
void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr) int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr) { if (vapic_addr) { if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apic->vapic_cache, vapic_addr, sizeof(u32))) return -EINVAL; __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention); } else { __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention); } vcpu->arch.apic->vapic_addr = vapic_addr; return 0; }
165,944
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_ecb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_ecb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); }
167,108
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } Commit Message: l2tp: fix info leak in l2tp_ip6_recvmsg() The L2TP code for IPv6 fails to initialize the l2tp_conn_id member of struct sockaddr_l2tpip6 and therefore leaks four bytes kernel stack in l2tp_ip6_recvmsg() in case msg_name is set. Initialize l2tp_conn_id with 0 to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_conn_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; }
166,037
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { ret = -ENOKEY; goto error2; } /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error2; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = -EOPNOTSUPP; if (key->type->read) { /* Read the data with the semaphore held (since we might sleep) * to protect against the key being updated or revoked. */ down_read(&key->sem); ret = key_validate(key); if (ret == 0) ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } error2: key_put(key); error: return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); ret = key_read_state(key); if (ret < 0) goto error2; /* Negatively instantiated */ /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error2; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = -EOPNOTSUPP; if (key->type->read) { /* Read the data with the semaphore held (since we might sleep) * to protect against the key being updated or revoked. */ down_read(&key->sem); ret = key_validate(key); if (ret == 0) ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } error2: key_put(key); error: return ret; }
167,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AddMainWebResources(content::WebUIDataSource* html_source) { html_source->AddResourcePath("media_router.js", IDR_MEDIA_ROUTER_JS); html_source->AddResourcePath("media_router_common.css", IDR_MEDIA_ROUTER_COMMON_CSS); html_source->AddResourcePath("media_router.css", IDR_MEDIA_ROUTER_CSS); html_source->AddResourcePath("media_router_data.js", IDR_MEDIA_ROUTER_DATA_JS); html_source->AddResourcePath("media_router_ui_interface.js", IDR_MEDIA_ROUTER_UI_INTERFACE_JS); html_source->AddResourcePath("polymer_config.js", IDR_MEDIA_ROUTER_POLYMER_CONFIG_JS); } Commit Message: One polymer_config.js to rule them all. [email protected],[email protected],[email protected] BUG=425626 Review URL: https://codereview.chromium.org/1224783005 Cr-Commit-Position: refs/heads/master@{#337882} CWE ID: CWE-399
void AddMainWebResources(content::WebUIDataSource* html_source) { html_source->AddResourcePath("media_router.js", IDR_MEDIA_ROUTER_JS); html_source->AddResourcePath("media_router_common.css", IDR_MEDIA_ROUTER_COMMON_CSS); html_source->AddResourcePath("media_router.css", IDR_MEDIA_ROUTER_CSS); html_source->AddResourcePath("media_router_data.js", IDR_MEDIA_ROUTER_DATA_JS); html_source->AddResourcePath("media_router_ui_interface.js", IDR_MEDIA_ROUTER_UI_INTERFACE_JS); }
171,708
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length) { register const struct rip6 *rp = (const struct rip6 *)dat; register const struct netinfo6 *ni; register u_int amt; register u_int i; int j; int trunc; if (ndo->ndo_snapend < dat) return; amt = ndo->ndo_snapend - dat; i = min(length, amt); if (i < (sizeof(struct rip6) - sizeof(struct netinfo6))) return; i -= (sizeof(struct rip6) - sizeof(struct netinfo6)); switch (rp->rip6_cmd) { case RIP6_REQUEST: j = length / sizeof(*ni); if (j == 1 && rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6 && IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) { ND_PRINT((ndo, " ripng-req dump")); break; } if (j * sizeof(*ni) != length - 4) ND_PRINT((ndo, " ripng-req %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-req %d:", j)); trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i); for (ni = rp->rip6_nets; i >= sizeof(*ni); i -= sizeof(*ni), ++ni) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, 0); } break; case RIP6_RESPONSE: j = length / sizeof(*ni); if (j * sizeof(*ni) != length - 4) ND_PRINT((ndo, " ripng-resp %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-resp %d:", j)); trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i); for (ni = rp->rip6_nets; i >= sizeof(*ni); i -= sizeof(*ni), ++ni) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, ni->rip6_metric); } if (trunc) ND_PRINT((ndo, "[|ripng]")); break; default: ND_PRINT((ndo, " ripng-%d ?? %u", rp->rip6_cmd, length)); break; } if (rp->rip6_vers != RIP6_VERSION) ND_PRINT((ndo, " [vers %d]", rp->rip6_vers)); } Commit Message: CVE-2017-12992/RIPng: Clean up bounds checking. Do bounds checking as we access items. Scan the list of netinfo6 entries based on the supplied packet length, without taking the captured length into account; let the aforementioned bounds checking handle that. This fixes a buffer over-read discovered by Kamil Frankowicz. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length) { register const struct rip6 *rp = (const struct rip6 *)dat; register const struct netinfo6 *ni; unsigned int length_left; u_int j; ND_TCHECK(rp->rip6_cmd); switch (rp->rip6_cmd) { case RIP6_REQUEST: length_left = length; if (length_left < (sizeof(struct rip6) - sizeof(struct netinfo6))) goto trunc; length_left -= (sizeof(struct rip6) - sizeof(struct netinfo6)); j = length_left / sizeof(*ni); if (j == 1) { ND_TCHECK(rp->rip6_nets); if (rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6 && IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) { ND_PRINT((ndo, " ripng-req dump")); break; } } if (j * sizeof(*ni) != length_left) ND_PRINT((ndo, " ripng-req %u[%u]:", j, length)); else ND_PRINT((ndo, " ripng-req %u:", j)); for (ni = rp->rip6_nets; length_left >= sizeof(*ni); length_left -= sizeof(*ni), ++ni) { ND_TCHECK(*ni); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, 0); } if (length_left != 0) goto trunc; break; case RIP6_RESPONSE: length_left = length; if (length_left < (sizeof(struct rip6) - sizeof(struct netinfo6))) goto trunc; length_left -= (sizeof(struct rip6) - sizeof(struct netinfo6)); j = length_left / sizeof(*ni); if (j * sizeof(*ni) != length_left) ND_PRINT((ndo, " ripng-resp %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-resp %d:", j)); for (ni = rp->rip6_nets; length_left >= sizeof(*ni); length_left -= sizeof(*ni), ++ni) { ND_TCHECK(*ni); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, ni->rip6_metric); } if (length_left != 0) goto trunc; break; default: ND_PRINT((ndo, " ripng-%d ?? %u", rp->rip6_cmd, length)); break; } ND_TCHECK(rp->rip6_vers); if (rp->rip6_vers != RIP6_VERSION) ND_PRINT((ndo, " [vers %d]", rp->rip6_vers)); return; trunc: ND_PRINT((ndo, "[|ripng]")); return; }
167,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ieee802_15_4_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int hdrlen; uint16_t fc; uint8_t seq; uint16_t panid = 0; if (caplen < 3) { ND_PRINT((ndo, "[|802.15.4]")); return caplen; } hdrlen = 3; fc = EXTRACT_LE_16BITS(p); seq = EXTRACT_LE_8BITS(p + 2); p += 3; caplen -= 3; ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)])); if (ndo->ndo_vflag) ND_PRINT((ndo,"seq %02x ", seq)); /* * Destination address and PAN ID, if present. */ switch (FC_DEST_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (fc & FC_PAN_ID_COMPRESSION) { /* * PAN ID compression; this requires that both * the source and destination addresses be present, * but the destination address is missing. */ ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved destination addressing mode")); return hdrlen; case FC_ADDRESSING_MODE_SHORT: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2))); p += 8; caplen -= 8; hdrlen += 8; break; } if (ndo->ndo_vflag) ND_PRINT((ndo,"< ")); /* * Source address and PAN ID, if present. */ switch (FC_SRC_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved source addressing mode")); return 0; case FC_ADDRESSING_MODE_SHORT: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); return hdrlen; } Commit Message: CVE-2017-13000/IEEE 802.15.4: Fix bug introduced by previous fix. We've already advanced the pointer past the PAN ID, if present; it now points to the address, so don't add 2 to it. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ieee802_15_4_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int hdrlen; uint16_t fc; uint8_t seq; uint16_t panid = 0; if (caplen < 3) { ND_PRINT((ndo, "[|802.15.4]")); return caplen; } hdrlen = 3; fc = EXTRACT_LE_16BITS(p); seq = EXTRACT_LE_8BITS(p + 2); p += 3; caplen -= 3; ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)])); if (ndo->ndo_vflag) ND_PRINT((ndo,"seq %02x ", seq)); /* * Destination address and PAN ID, if present. */ switch (FC_DEST_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (fc & FC_PAN_ID_COMPRESSION) { /* * PAN ID compression; this requires that both * the source and destination addresses be present, * but the destination address is missing. */ ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved destination addressing mode")); return hdrlen; case FC_ADDRESSING_MODE_SHORT: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (ndo->ndo_vflag) ND_PRINT((ndo,"< ")); /* * Source address and PAN ID, if present. */ switch (FC_SRC_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved source addressing mode")); return 0; case FC_ADDRESSING_MODE_SHORT: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); return hdrlen; }
170,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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_ = 16; fwd_txfm_ref = fdct16x16_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); bit_depth_ = GET_PARAM(3); pitch_ = 16; fwd_txfm_ref = fdct16x16_ref; inv_txfm_ref = idct16x16_ref; mask_ = (1 << bit_depth_) - 1; #if CONFIG_VP9_HIGHBITDEPTH switch (bit_depth_) { case VPX_BITS_10: inv_txfm_ref = idct16x16_10_ref; break; case VPX_BITS_12: inv_txfm_ref = idct16x16_12_ref; break; default: inv_txfm_ref = idct16x16_ref; break; } #else inv_txfm_ref = idct16x16_ref; #endif }
174,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { FILE *infile, *outfile[NUM_ENCODERS]; vpx_codec_ctx_t codec[NUM_ENCODERS]; vpx_codec_enc_cfg_t cfg[NUM_ENCODERS]; vpx_codec_pts_t frame_cnt = 0; vpx_image_t raw[NUM_ENCODERS]; vpx_codec_err_t res[NUM_ENCODERS]; int i; long width; long height; int frame_avail; int got_data; int flags = 0; /*Currently, only realtime mode is supported in multi-resolution encoding.*/ int arg_deadline = VPX_DL_REALTIME; /* Set show_psnr to 1/0 to show/not show PSNR. Choose show_psnr=0 if you don't need to know PSNR, which will skip PSNR calculation and save encoding time. */ int show_psnr = 0; uint64_t psnr_sse_total[NUM_ENCODERS] = {0}; uint64_t psnr_samples_total[NUM_ENCODERS] = {0}; double psnr_totals[NUM_ENCODERS][4] = {{0,0}}; int psnr_count[NUM_ENCODERS] = {0}; /* Set the required target bitrates for each resolution level. * If target bitrate for highest-resolution level is set to 0, * (i.e. target_bitrate[0]=0), we skip encoding at that level. */ unsigned int target_bitrate[NUM_ENCODERS]={1000, 500, 100}; /* Enter the frame rate of the input video */ int framerate = 30; /* Set down-sampling factor for each resolution level. dsf[0] controls down sampling from level 0 to level 1; dsf[1] controls down sampling from level 1 to level 2; dsf[2] is not used. */ vpx_rational_t dsf[NUM_ENCODERS] = {{2, 1}, {2, 1}, {1, 1}}; if(argc!= (5+NUM_ENCODERS)) die("Usage: %s <width> <height> <infile> <outfile(s)> <output psnr?>\n", argv[0]); printf("Using %s\n",vpx_codec_iface_name(interface)); width = strtol(argv[1], NULL, 0); height = strtol(argv[2], NULL, 0); if(width < 16 || width%2 || height <16 || height%2) die("Invalid resolution: %ldx%ld", width, height); /* Open input video file for encoding */ if(!(infile = fopen(argv[3], "rb"))) die("Failed to open %s for reading", argv[3]); /* Open output file for each encoder to output bitstreams */ for (i=0; i< NUM_ENCODERS; i++) { if(!target_bitrate[i]) { outfile[i] = NULL; continue; } if(!(outfile[i] = fopen(argv[i+4], "wb"))) die("Failed to open %s for writing", argv[i+4]); } show_psnr = strtol(argv[NUM_ENCODERS + 4], NULL, 0); /* Populate default encoder configuration */ for (i=0; i< NUM_ENCODERS; i++) { res[i] = vpx_codec_enc_config_default(interface, &cfg[i], 0); if(res[i]) { printf("Failed to get config: %s\n", vpx_codec_err_to_string(res[i])); return EXIT_FAILURE; } } /* * Update the default configuration according to needs of the application. */ /* Highest-resolution encoder settings */ cfg[0].g_w = width; cfg[0].g_h = height; cfg[0].g_threads = 1; /* number of threads used */ cfg[0].rc_dropframe_thresh = 30; cfg[0].rc_end_usage = VPX_CBR; cfg[0].rc_resize_allowed = 0; cfg[0].rc_min_quantizer = 4; cfg[0].rc_max_quantizer = 56; cfg[0].rc_undershoot_pct = 98; cfg[0].rc_overshoot_pct = 100; cfg[0].rc_buf_initial_sz = 500; cfg[0].rc_buf_optimal_sz = 600; cfg[0].rc_buf_sz = 1000; cfg[0].g_error_resilient = 1; /* Enable error resilient mode */ cfg[0].g_lag_in_frames = 0; /* Disable automatic keyframe placement */ /* Note: These 3 settings are copied to all levels. But, except the lowest * resolution level, all other levels are set to VPX_KF_DISABLED internally. */ cfg[0].kf_min_dist = 3000; cfg[0].kf_max_dist = 3000; cfg[0].rc_target_bitrate = target_bitrate[0]; /* Set target bitrate */ cfg[0].g_timebase.num = 1; /* Set fps */ cfg[0].g_timebase.den = framerate; /* Other-resolution encoder settings */ for (i=1; i< NUM_ENCODERS; i++) { memcpy(&cfg[i], &cfg[0], sizeof(vpx_codec_enc_cfg_t)); cfg[i].g_threads = 1; /* number of threads used */ cfg[i].rc_target_bitrate = target_bitrate[i]; /* Note: Width & height of other-resolution encoders are calculated * from the highest-resolution encoder's size and the corresponding * down_sampling_factor. */ { unsigned int iw = cfg[i-1].g_w*dsf[i-1].den + dsf[i-1].num - 1; unsigned int ih = cfg[i-1].g_h*dsf[i-1].den + dsf[i-1].num - 1; cfg[i].g_w = iw/dsf[i-1].num; cfg[i].g_h = ih/dsf[i-1].num; } /* Make width & height to be multiplier of 2. */ if((cfg[i].g_w)%2)cfg[i].g_w++; if((cfg[i].g_h)%2)cfg[i].g_h++; } /* Allocate image for each encoder */ for (i=0; i< NUM_ENCODERS; i++) if(!vpx_img_alloc(&raw[i], VPX_IMG_FMT_I420, cfg[i].g_w, cfg[i].g_h, 32)) die("Failed to allocate image", cfg[i].g_w, cfg[i].g_h); if (raw[0].stride[VPX_PLANE_Y] == raw[0].d_w) read_frame_p = read_frame; else read_frame_p = read_frame_by_row; for (i=0; i< NUM_ENCODERS; i++) if(outfile[i]) write_ivf_file_header(outfile[i], &cfg[i], 0); /* Initialize multi-encoder */ if(vpx_codec_enc_init_multi(&codec[0], interface, &cfg[0], NUM_ENCODERS, (show_psnr ? VPX_CODEC_USE_PSNR : 0), &dsf[0])) die_codec(&codec[0], "Failed to initialize encoder"); /* The extra encoding configuration parameters can be set as follows. */ /* Set encoding speed */ for ( i=0; i<NUM_ENCODERS; i++) { int speed = -6; if(vpx_codec_control(&codec[i], VP8E_SET_CPUUSED, speed)) die_codec(&codec[i], "Failed to set cpu_used"); } /* Set static threshold. */ for ( i=0; i<NUM_ENCODERS; i++) { unsigned int static_thresh = 1; if(vpx_codec_control(&codec[i], VP8E_SET_STATIC_THRESHOLD, static_thresh)) die_codec(&codec[i], "Failed to set static threshold"); } /* Set NOISE_SENSITIVITY to do TEMPORAL_DENOISING */ /* Enable denoising for the highest-resolution encoder. */ if(vpx_codec_control(&codec[0], VP8E_SET_NOISE_SENSITIVITY, 1)) die_codec(&codec[0], "Failed to set noise_sensitivity"); for ( i=1; i< NUM_ENCODERS; i++) { if(vpx_codec_control(&codec[i], VP8E_SET_NOISE_SENSITIVITY, 0)) die_codec(&codec[i], "Failed to set noise_sensitivity"); } frame_avail = 1; got_data = 0; while(frame_avail || got_data) { vpx_codec_iter_t iter[NUM_ENCODERS]={NULL}; const vpx_codec_cx_pkt_t *pkt[NUM_ENCODERS]; flags = 0; frame_avail = read_frame_p(infile, &raw[0]); if(frame_avail) { for ( i=1; i<NUM_ENCODERS; i++) { /*Scale the image down a number of times by downsampling factor*/ /* FilterMode 1 or 2 give better psnr than FilterMode 0. */ I420Scale(raw[i-1].planes[VPX_PLANE_Y], raw[i-1].stride[VPX_PLANE_Y], raw[i-1].planes[VPX_PLANE_U], raw[i-1].stride[VPX_PLANE_U], raw[i-1].planes[VPX_PLANE_V], raw[i-1].stride[VPX_PLANE_V], raw[i-1].d_w, raw[i-1].d_h, raw[i].planes[VPX_PLANE_Y], raw[i].stride[VPX_PLANE_Y], raw[i].planes[VPX_PLANE_U], raw[i].stride[VPX_PLANE_U], raw[i].planes[VPX_PLANE_V], raw[i].stride[VPX_PLANE_V], raw[i].d_w, raw[i].d_h, 1); } } /* Encode each frame at multi-levels */ if(vpx_codec_encode(&codec[0], frame_avail? &raw[0] : NULL, frame_cnt, 1, flags, arg_deadline)) die_codec(&codec[0], "Failed to encode frame"); for (i=NUM_ENCODERS-1; i>=0 ; i--) { got_data = 0; while( (pkt[i] = vpx_codec_get_cx_data(&codec[i], &iter[i])) ) { got_data = 1; switch(pkt[i]->kind) { case VPX_CODEC_CX_FRAME_PKT: write_ivf_frame_header(outfile[i], pkt[i]); (void) fwrite(pkt[i]->data.frame.buf, 1, pkt[i]->data.frame.sz, outfile[i]); break; case VPX_CODEC_PSNR_PKT: if (show_psnr) { int j; psnr_sse_total[i] += pkt[i]->data.psnr.sse[0]; psnr_samples_total[i] += pkt[i]->data.psnr.samples[0]; for (j = 0; j < 4; j++) { } psnr_count[i]++; } break; default: break; } printf(pkt[i]->kind == VPX_CODEC_CX_FRAME_PKT && (pkt[i]->data.frame.flags & VPX_FRAME_IS_KEY)? "K":"."); fflush(stdout); } } frame_cnt++; } printf("\n"); fclose(infile); printf("Processed %ld frames.\n",(long int)frame_cnt-1); for (i=0; i< NUM_ENCODERS; i++) { /* Calculate PSNR and print it out */ if ( (show_psnr) && (psnr_count[i]>0) ) { int j; double ovpsnr = sse_to_psnr(psnr_samples_total[i], 255.0, psnr_sse_total[i]); fprintf(stderr, "\n ENC%d PSNR (Overall/Avg/Y/U/V)", i); fprintf(stderr, " %.3lf", ovpsnr); for (j = 0; j < 4; j++) { fprintf(stderr, " %.3lf", psnr_totals[i][j]/psnr_count[i]); } } if(vpx_codec_destroy(&codec[i])) die_codec(&codec[i], "Failed to destroy codec"); vpx_img_free(&raw[i]); if(!outfile[i]) continue; /* Try to rewrite the file header with the actual frame count */ if(!fseek(outfile[i], 0, SEEK_SET)) write_ivf_file_header(outfile[i], &cfg[i], frame_cnt-1); fclose(outfile[i]); } printf("\n"); return EXIT_SUCCESS; } 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
int main(int argc, char **argv) { FILE *infile, *outfile[NUM_ENCODERS]; FILE *downsampled_input[NUM_ENCODERS - 1]; char filename[50]; vpx_codec_ctx_t codec[NUM_ENCODERS]; vpx_codec_enc_cfg_t cfg[NUM_ENCODERS]; int frame_cnt = 0; vpx_image_t raw[NUM_ENCODERS]; vpx_codec_err_t res[NUM_ENCODERS]; int i; long width; long height; int length_frame; int frame_avail; int got_data; int flags = 0; int layer_id = 0; int layer_flags[VPX_TS_MAX_PERIODICITY * NUM_ENCODERS] = {0}; int flag_periodicity; /*Currently, only realtime mode is supported in multi-resolution encoding.*/ int arg_deadline = VPX_DL_REALTIME; /* Set show_psnr to 1/0 to show/not show PSNR. Choose show_psnr=0 if you don't need to know PSNR, which will skip PSNR calculation and save encoding time. */ int show_psnr = 0; int key_frame_insert = 0; uint64_t psnr_sse_total[NUM_ENCODERS] = {0}; uint64_t psnr_samples_total[NUM_ENCODERS] = {0}; double psnr_totals[NUM_ENCODERS][4] = {{0,0}}; int psnr_count[NUM_ENCODERS] = {0}; double cx_time = 0; struct timeval tv1, tv2, difftv; /* Set the required target bitrates for each resolution level. * If target bitrate for highest-resolution level is set to 0, * (i.e. target_bitrate[0]=0), we skip encoding at that level. */ unsigned int target_bitrate[NUM_ENCODERS]={1000, 500, 100}; /* Enter the frame rate of the input video */ int framerate = 30; /* Set down-sampling factor for each resolution level. dsf[0] controls down sampling from level 0 to level 1; dsf[1] controls down sampling from level 1 to level 2; dsf[2] is not used. */ vpx_rational_t dsf[NUM_ENCODERS] = {{2, 1}, {2, 1}, {1, 1}}; /* Set the number of temporal layers for each encoder/resolution level, * starting from highest resoln down to lowest resoln. */ unsigned int num_temporal_layers[NUM_ENCODERS] = {3, 3, 3}; if(argc!= (7 + 3 * NUM_ENCODERS)) die("Usage: %s <width> <height> <frame_rate> <infile> <outfile(s)> " "<rate_encoder(s)> <temporal_layer(s)> <key_frame_insert> <output psnr?> \n", argv[0]); printf("Using %s\n",vpx_codec_iface_name(interface)); width = strtol(argv[1], NULL, 0); height = strtol(argv[2], NULL, 0); framerate = strtol(argv[3], NULL, 0); if(width < 16 || width%2 || height <16 || height%2) die("Invalid resolution: %ldx%ld", width, height); /* Open input video file for encoding */ if(!(infile = fopen(argv[4], "rb"))) die("Failed to open %s for reading", argv[4]); /* Open output file for each encoder to output bitstreams */ for (i=0; i< NUM_ENCODERS; i++) { if(!target_bitrate[i]) { outfile[i] = NULL; continue; } if(!(outfile[i] = fopen(argv[i+5], "wb"))) die("Failed to open %s for writing", argv[i+4]); } // Bitrates per spatial layer: overwrite default rates above. for (i=0; i< NUM_ENCODERS; i++) { target_bitrate[i] = strtol(argv[NUM_ENCODERS + 5 + i], NULL, 0); } // Temporal layers per spatial layers: overwrite default settings above. for (i=0; i< NUM_ENCODERS; i++) { num_temporal_layers[i] = strtol(argv[2 * NUM_ENCODERS + 5 + i], NULL, 0); if (num_temporal_layers[i] < 1 || num_temporal_layers[i] > 3) die("Invalid temporal layers: %d, Must be 1, 2, or 3. \n", num_temporal_layers); } /* Open file to write out each spatially downsampled input stream. */ for (i=0; i< NUM_ENCODERS - 1; i++) { // Highest resoln is encoder 0. if (sprintf(filename,"ds%d.yuv",NUM_ENCODERS - i) < 0) { return EXIT_FAILURE; } downsampled_input[i] = fopen(filename,"wb"); } key_frame_insert = strtol(argv[3 * NUM_ENCODERS + 5], NULL, 0); show_psnr = strtol(argv[3 * NUM_ENCODERS + 6], NULL, 0); /* Populate default encoder configuration */ for (i=0; i< NUM_ENCODERS; i++) { res[i] = vpx_codec_enc_config_default(interface, &cfg[i], 0); if(res[i]) { printf("Failed to get config: %s\n", vpx_codec_err_to_string(res[i])); return EXIT_FAILURE; } } /* * Update the default configuration according to needs of the application. */ /* Highest-resolution encoder settings */ cfg[0].g_w = width; cfg[0].g_h = height; cfg[0].rc_dropframe_thresh = 0; cfg[0].rc_end_usage = VPX_CBR; cfg[0].rc_resize_allowed = 0; cfg[0].rc_min_quantizer = 2; cfg[0].rc_max_quantizer = 56; cfg[0].rc_undershoot_pct = 100; cfg[0].rc_overshoot_pct = 15; cfg[0].rc_buf_initial_sz = 500; cfg[0].rc_buf_optimal_sz = 600; cfg[0].rc_buf_sz = 1000; cfg[0].g_error_resilient = 1; /* Enable error resilient mode */ cfg[0].g_lag_in_frames = 0; /* Disable automatic keyframe placement */ /* Note: These 3 settings are copied to all levels. But, except the lowest * resolution level, all other levels are set to VPX_KF_DISABLED internally. */ cfg[0].kf_min_dist = 3000; cfg[0].kf_max_dist = 3000; cfg[0].rc_target_bitrate = target_bitrate[0]; /* Set target bitrate */ cfg[0].g_timebase.num = 1; /* Set fps */ cfg[0].g_timebase.den = framerate; /* Other-resolution encoder settings */ for (i=1; i< NUM_ENCODERS; i++) { memcpy(&cfg[i], &cfg[0], sizeof(vpx_codec_enc_cfg_t)); cfg[i].rc_target_bitrate = target_bitrate[i]; /* Note: Width & height of other-resolution encoders are calculated * from the highest-resolution encoder's size and the corresponding * down_sampling_factor. */ { unsigned int iw = cfg[i-1].g_w*dsf[i-1].den + dsf[i-1].num - 1; unsigned int ih = cfg[i-1].g_h*dsf[i-1].den + dsf[i-1].num - 1; cfg[i].g_w = iw/dsf[i-1].num; cfg[i].g_h = ih/dsf[i-1].num; } /* Make width & height to be multiplier of 2. */ if((cfg[i].g_w)%2)cfg[i].g_w++; if((cfg[i].g_h)%2)cfg[i].g_h++; } // Set the number of threads per encode/spatial layer. // (1, 1, 1) means no encoder threading. cfg[0].g_threads = 2; cfg[1].g_threads = 1; cfg[2].g_threads = 1; /* Allocate image for each encoder */ for (i=0; i< NUM_ENCODERS; i++) if(!vpx_img_alloc(&raw[i], VPX_IMG_FMT_I420, cfg[i].g_w, cfg[i].g_h, 32)) die("Failed to allocate image", cfg[i].g_w, cfg[i].g_h); if (raw[0].stride[VPX_PLANE_Y] == raw[0].d_w) read_frame_p = read_frame; else read_frame_p = read_frame_by_row; for (i=0; i< NUM_ENCODERS; i++) if(outfile[i]) write_ivf_file_header(outfile[i], &cfg[i], 0); /* Temporal layers settings */ for ( i=0; i<NUM_ENCODERS; i++) { set_temporal_layer_pattern(num_temporal_layers[i], &cfg[i], cfg[i].rc_target_bitrate, &layer_flags[i * VPX_TS_MAX_PERIODICITY]); } /* Initialize multi-encoder */ if(vpx_codec_enc_init_multi(&codec[0], interface, &cfg[0], NUM_ENCODERS, (show_psnr ? VPX_CODEC_USE_PSNR : 0), &dsf[0])) die_codec(&codec[0], "Failed to initialize encoder"); /* The extra encoding configuration parameters can be set as follows. */ /* Set encoding speed */ for ( i=0; i<NUM_ENCODERS; i++) { int speed = -6; /* Lower speed for the lowest resolution. */ if (i == NUM_ENCODERS - 1) speed = -4; if(vpx_codec_control(&codec[i], VP8E_SET_CPUUSED, speed)) die_codec(&codec[i], "Failed to set cpu_used"); } /* Set static threshold = 1 for all encoders */ for ( i=0; i<NUM_ENCODERS; i++) { if(vpx_codec_control(&codec[i], VP8E_SET_STATIC_THRESHOLD, 1)) die_codec(&codec[i], "Failed to set static threshold"); } /* Set NOISE_SENSITIVITY to do TEMPORAL_DENOISING */ /* Enable denoising for the highest-resolution encoder. */ if(vpx_codec_control(&codec[0], VP8E_SET_NOISE_SENSITIVITY, 1)) die_codec(&codec[0], "Failed to set noise_sensitivity"); for ( i=1; i< NUM_ENCODERS; i++) { if(vpx_codec_control(&codec[i], VP8E_SET_NOISE_SENSITIVITY, 0)) die_codec(&codec[i], "Failed to set noise_sensitivity"); } /* Set the number of token partitions */ for ( i=0; i<NUM_ENCODERS; i++) { if(vpx_codec_control(&codec[i], VP8E_SET_TOKEN_PARTITIONS, 1)) die_codec(&codec[i], "Failed to set static threshold"); } /* Set the max intra target bitrate */ for ( i=0; i<NUM_ENCODERS; i++) { unsigned int max_intra_size_pct = (int)(((double)cfg[0].rc_buf_optimal_sz * 0.5) * framerate / 10); if(vpx_codec_control(&codec[i], VP8E_SET_MAX_INTRA_BITRATE_PCT, max_intra_size_pct)) die_codec(&codec[i], "Failed to set static threshold"); //printf("%d %d \n",i,max_intra_size_pct); } frame_avail = 1; got_data = 0; while(frame_avail || got_data) { vpx_codec_iter_t iter[NUM_ENCODERS]={NULL}; const vpx_codec_cx_pkt_t *pkt[NUM_ENCODERS]; flags = 0; frame_avail = read_frame_p(infile, &raw[0]); if(frame_avail) { for ( i=1; i<NUM_ENCODERS; i++) { /*Scale the image down a number of times by downsampling factor*/ /* FilterMode 1 or 2 give better psnr than FilterMode 0. */ I420Scale(raw[i-1].planes[VPX_PLANE_Y], raw[i-1].stride[VPX_PLANE_Y], raw[i-1].planes[VPX_PLANE_U], raw[i-1].stride[VPX_PLANE_U], raw[i-1].planes[VPX_PLANE_V], raw[i-1].stride[VPX_PLANE_V], raw[i-1].d_w, raw[i-1].d_h, raw[i].planes[VPX_PLANE_Y], raw[i].stride[VPX_PLANE_Y], raw[i].planes[VPX_PLANE_U], raw[i].stride[VPX_PLANE_U], raw[i].planes[VPX_PLANE_V], raw[i].stride[VPX_PLANE_V], raw[i].d_w, raw[i].d_h, 1); /* Write out down-sampled input. */ length_frame = cfg[i].g_w * cfg[i].g_h *3/2; if (fwrite(raw[i].planes[0], 1, length_frame, downsampled_input[NUM_ENCODERS - i - 1]) != length_frame) { return EXIT_FAILURE; } } } /* Set the flags (reference and update) for all the encoders.*/ for ( i=0; i<NUM_ENCODERS; i++) { layer_id = cfg[i].ts_layer_id[frame_cnt % cfg[i].ts_periodicity]; flags = 0; flag_periodicity = periodicity_to_num_layers [num_temporal_layers[i] - 1]; flags = layer_flags[i * VPX_TS_MAX_PERIODICITY + frame_cnt % flag_periodicity]; // Key frame flag for first frame. if (frame_cnt == 0) { flags |= VPX_EFLAG_FORCE_KF; } if (frame_cnt > 0 && frame_cnt == key_frame_insert) { flags = VPX_EFLAG_FORCE_KF; } vpx_codec_control(&codec[i], VP8E_SET_FRAME_FLAGS, flags); vpx_codec_control(&codec[i], VP8E_SET_TEMPORAL_LAYER_ID, layer_id); } gettimeofday(&tv1, NULL); /* Encode each frame at multi-levels */ /* Note the flags must be set to 0 in the encode call if they are set for each frame with the vpx_codec_control(), as done above. */ if(vpx_codec_encode(&codec[0], frame_avail? &raw[0] : NULL, frame_cnt, 1, 0, arg_deadline)) { die_codec(&codec[0], "Failed to encode frame"); } gettimeofday(&tv2, NULL); timersub(&tv2, &tv1, &difftv); cx_time += (double)(difftv.tv_sec * 1000000 + difftv.tv_usec); for (i=NUM_ENCODERS-1; i>=0 ; i--) { got_data = 0; while( (pkt[i] = vpx_codec_get_cx_data(&codec[i], &iter[i])) ) { got_data = 1; switch(pkt[i]->kind) { case VPX_CODEC_CX_FRAME_PKT: write_ivf_frame_header(outfile[i], pkt[i]); (void) fwrite(pkt[i]->data.frame.buf, 1, pkt[i]->data.frame.sz, outfile[i]); break; case VPX_CODEC_PSNR_PKT: if (show_psnr) { int j; psnr_sse_total[i] += pkt[i]->data.psnr.sse[0]; psnr_samples_total[i] += pkt[i]->data.psnr.samples[0]; for (j = 0; j < 4; j++) { } psnr_count[i]++; } break; default: break; } printf(pkt[i]->kind == VPX_CODEC_CX_FRAME_PKT && (pkt[i]->data.frame.flags & VPX_FRAME_IS_KEY)? "K":""); fflush(stdout); } } frame_cnt++; } printf("\n"); printf("FPS for encoding %d %f %f \n", frame_cnt, (float)cx_time / 1000000, 1000000 * (double)frame_cnt / (double)cx_time); fclose(infile); printf("Processed %ld frames.\n",(long int)frame_cnt-1); for (i=0; i< NUM_ENCODERS; i++) { /* Calculate PSNR and print it out */ if ( (show_psnr) && (psnr_count[i]>0) ) { int j; double ovpsnr = sse_to_psnr(psnr_samples_total[i], 255.0, psnr_sse_total[i]); fprintf(stderr, "\n ENC%d PSNR (Overall/Avg/Y/U/V)", i); fprintf(stderr, " %.3lf", ovpsnr); for (j = 0; j < 4; j++) { fprintf(stderr, " %.3lf", psnr_totals[i][j]/psnr_count[i]); } } if(vpx_codec_destroy(&codec[i])) die_codec(&codec[i], "Failed to destroy codec"); vpx_img_free(&raw[i]); if(!outfile[i]) continue; /* Try to rewrite the file header with the actual frame count */ if(!fseek(outfile[i], 0, SEEK_SET)) write_ivf_file_header(outfile[i], &cfg[i], frame_cnt-1); fclose(outfile[i]); } printf("\n"); return EXIT_SUCCESS; }
174,497
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DataReductionProxySettings::MaybeActivateDataReductionProxy( bool at_startup) { DCHECK(thread_checker_.CalledOnValidThread()); PrefService* prefs = GetOriginalProfilePrefs(); if (!prefs) return; if (spdy_proxy_auth_enabled_.GetValue() && at_startup) { int64_t last_enabled_time = prefs->GetInt64(prefs::kDataReductionProxyLastEnabledTime); if (last_enabled_time != 0) { RecordDaysSinceEnabledMetric( (clock_->Now() - base::Time::FromInternalValue(last_enabled_time)) .InDays()); } int64_t last_savings_cleared_time = prefs->GetInt64( prefs::kDataReductionProxySavingsClearedNegativeSystemClock); if (last_savings_cleared_time != 0) { int32_t days_since_savings_cleared = (clock_->Now() - base::Time::FromInternalValue(last_savings_cleared_time)) .InDays(); if (days_since_savings_cleared == 0) days_since_savings_cleared = 1; UMA_HISTOGRAM_CUSTOM_COUNTS( "DataReductionProxy.DaysSinceSavingsCleared.NegativeSystemClock", days_since_savings_cleared, 1, 365, 50); } } if (spdy_proxy_auth_enabled_.GetValue() && !prefs->GetBoolean(prefs::kDataReductionProxyWasEnabledBefore)) { prefs->SetBoolean(prefs::kDataReductionProxyWasEnabledBefore, true); ResetDataReductionStatistics(); } if (!at_startup) { if (IsDataReductionProxyEnabled()) { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON); prefs->SetInt64(prefs::kDataReductionProxyLastEnabledTime, clock_->Now().ToInternalValue()); RecordDaysSinceEnabledMetric(0); } else { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF); } } if (at_startup && !data_reduction_proxy_service_->Initialized()) deferred_initialization_ = true; else UpdateIOData(at_startup); } 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 <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
void DataReductionProxySettings::MaybeActivateDataReductionProxy( bool at_startup) { DCHECK(thread_checker_.CalledOnValidThread()); PrefService* prefs = GetOriginalProfilePrefs(); if (!prefs) return; bool enabled = IsDataSaverEnabledByUser(prefs); if (enabled && at_startup) { int64_t last_enabled_time = prefs->GetInt64(prefs::kDataReductionProxyLastEnabledTime); if (last_enabled_time != 0) { RecordDaysSinceEnabledMetric( (clock_->Now() - base::Time::FromInternalValue(last_enabled_time)) .InDays()); } int64_t last_savings_cleared_time = prefs->GetInt64( prefs::kDataReductionProxySavingsClearedNegativeSystemClock); if (last_savings_cleared_time != 0) { int32_t days_since_savings_cleared = (clock_->Now() - base::Time::FromInternalValue(last_savings_cleared_time)) .InDays(); if (days_since_savings_cleared == 0) days_since_savings_cleared = 1; UMA_HISTOGRAM_CUSTOM_COUNTS( "DataReductionProxy.DaysSinceSavingsCleared.NegativeSystemClock", days_since_savings_cleared, 1, 365, 50); } } if (enabled && !prefs->GetBoolean(prefs::kDataReductionProxyWasEnabledBefore)) { prefs->SetBoolean(prefs::kDataReductionProxyWasEnabledBefore, true); ResetDataReductionStatistics(); } if (!at_startup) { if (IsDataReductionProxyEnabled()) { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON); prefs->SetInt64(prefs::kDataReductionProxyLastEnabledTime, clock_->Now().ToInternalValue()); RecordDaysSinceEnabledMetric(0); } else { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF); } } if (at_startup && !data_reduction_proxy_service_->Initialized()) deferred_initialization_ = true; else UpdateIOData(at_startup); }
172,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: FramebufferInfoTest() : manager_(1, 1), feature_info_(new FeatureInfo()), renderbuffer_manager_(NULL, kMaxRenderbufferSize, kMaxSamples, kDepth24Supported) { texture_manager_.reset(new TextureManager(NULL, feature_info_.get(), kMaxTextureSize, kMaxCubemapSize, kUseDefaultTextures)); } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
FramebufferInfoTest() : manager_(kMaxDrawBuffers, kMaxColorAttachments), feature_info_(new FeatureInfo()), renderbuffer_manager_(NULL, kMaxRenderbufferSize, kMaxSamples, kDepth24Supported) { texture_manager_.reset(new TextureManager(NULL, feature_info_.get(), kMaxTextureSize, kMaxCubemapSize, kUseDefaultTextures)); }
171,656
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram( HistogramType histogram_type, const std::string& name, int minimum, int maximum, const BucketRanges* bucket_ranges, int32_t flags, Reference* ref_ptr) { if (memory_allocator_->IsCorrupt()) { RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_CORRUPT); return nullptr; } PersistentHistogramData* histogram_data = memory_allocator_->New<PersistentHistogramData>( offsetof(PersistentHistogramData, name) + name.length() + 1); if (histogram_data) { memcpy(histogram_data->name, name.c_str(), name.size() + 1); histogram_data->histogram_type = histogram_type; histogram_data->flags = flags | HistogramBase::kIsPersistent; } if (histogram_type != SPARSE_HISTOGRAM) { size_t bucket_count = bucket_ranges->bucket_count(); size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count); if (counts_bytes == 0) { NOTREACHED(); return nullptr; } DCHECK_EQ(this, GlobalHistogramAllocator::Get()); PersistentMemoryAllocator::Reference ranges_ref = bucket_ranges->persistent_reference(); if (!ranges_ref) { size_t ranges_count = bucket_count + 1; size_t ranges_bytes = ranges_count * sizeof(HistogramBase::Sample); ranges_ref = memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray); if (ranges_ref) { HistogramBase::Sample* ranges_data = memory_allocator_->GetAsArray<HistogramBase::Sample>( ranges_ref, kTypeIdRangesArray, ranges_count); if (ranges_data) { for (size_t i = 0; i < bucket_ranges->size(); ++i) ranges_data[i] = bucket_ranges->range(i); bucket_ranges->set_persistent_reference(ranges_ref); } else { NOTREACHED(); ranges_ref = PersistentMemoryAllocator::kReferenceNull; } } } else { DCHECK_EQ(kTypeIdRangesArray, memory_allocator_->GetType(ranges_ref)); } if (ranges_ref && histogram_data) { histogram_data->minimum = minimum; histogram_data->maximum = maximum; histogram_data->bucket_count = static_cast<uint32_t>(bucket_count); histogram_data->ranges_ref = ranges_ref; histogram_data->ranges_checksum = bucket_ranges->checksum(); } else { histogram_data = nullptr; // Clear this for proper handling below. } } if (histogram_data) { std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data); DCHECK(histogram); DCHECK_NE(0U, histogram_data->samples_metadata.id); DCHECK_NE(0U, histogram_data->logged_metadata.id); PersistentMemoryAllocator::Reference histogram_ref = memory_allocator_->GetAsReference(histogram_data); if (ref_ptr != nullptr) *ref_ptr = histogram_ref; subtle::NoBarrier_Store(&last_created_, histogram_ref); return histogram; } CreateHistogramResultType result; if (memory_allocator_->IsCorrupt()) { RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_NEWLY_CORRUPT); result = CREATE_HISTOGRAM_ALLOCATOR_CORRUPT; } else if (memory_allocator_->IsFull()) { result = CREATE_HISTOGRAM_ALLOCATOR_FULL; } else { result = CREATE_HISTOGRAM_ALLOCATOR_ERROR; } RecordCreateHistogramResult(result); if (result != CREATE_HISTOGRAM_ALLOCATOR_FULL) NOTREACHED() << memory_allocator_->Name() << ", error=" << result; return nullptr; } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram( HistogramType histogram_type, const std::string& name, int minimum, int maximum, const BucketRanges* bucket_ranges, int32_t flags, Reference* ref_ptr) { if (memory_allocator_->IsCorrupt()) return nullptr; PersistentHistogramData* histogram_data = memory_allocator_->New<PersistentHistogramData>( offsetof(PersistentHistogramData, name) + name.length() + 1); if (histogram_data) { memcpy(histogram_data->name, name.c_str(), name.size() + 1); histogram_data->histogram_type = histogram_type; histogram_data->flags = flags | HistogramBase::kIsPersistent; } if (histogram_type != SPARSE_HISTOGRAM) { size_t bucket_count = bucket_ranges->bucket_count(); size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count); if (counts_bytes == 0) { NOTREACHED(); return nullptr; } DCHECK_EQ(this, GlobalHistogramAllocator::Get()); PersistentMemoryAllocator::Reference ranges_ref = bucket_ranges->persistent_reference(); if (!ranges_ref) { size_t ranges_count = bucket_count + 1; size_t ranges_bytes = ranges_count * sizeof(HistogramBase::Sample); ranges_ref = memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray); if (ranges_ref) { HistogramBase::Sample* ranges_data = memory_allocator_->GetAsArray<HistogramBase::Sample>( ranges_ref, kTypeIdRangesArray, ranges_count); if (ranges_data) { for (size_t i = 0; i < bucket_ranges->size(); ++i) ranges_data[i] = bucket_ranges->range(i); bucket_ranges->set_persistent_reference(ranges_ref); } else { NOTREACHED(); ranges_ref = PersistentMemoryAllocator::kReferenceNull; } } } else { DCHECK_EQ(kTypeIdRangesArray, memory_allocator_->GetType(ranges_ref)); } if (ranges_ref && histogram_data) { histogram_data->minimum = minimum; histogram_data->maximum = maximum; histogram_data->bucket_count = static_cast<uint32_t>(bucket_count); histogram_data->ranges_ref = ranges_ref; histogram_data->ranges_checksum = bucket_ranges->checksum(); } else { histogram_data = nullptr; // Clear this for proper handling below. } } if (histogram_data) { std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data); DCHECK(histogram); DCHECK_NE(0U, histogram_data->samples_metadata.id); DCHECK_NE(0U, histogram_data->logged_metadata.id); PersistentMemoryAllocator::Reference histogram_ref = memory_allocator_->GetAsReference(histogram_data); if (ref_ptr != nullptr) *ref_ptr = histogram_ref; subtle::NoBarrier_Store(&last_created_, histogram_ref); return histogram; } if (memory_allocator_->IsCorrupt()) NOTREACHED() << memory_allocator_->Name() << " is corrupt!"; return nullptr; }
172,131
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } Commit Message: Fix bug #72114 - int/size_t confusion in fread CWE ID: CWE-190
PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } if (len > INT_MAX) { /* string length is int in 5.x so we can not read more than int */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; }
167,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool InitSkBitmapFromData(SkBitmap* bitmap, const char* pixels, size_t pixels_size) const { if (!bitmap->tryAllocPixels( SkImageInfo::Make(width, height, color_type, alpha_type))) return false; if (pixels_size != bitmap->computeByteSize()) return false; memcpy(bitmap->getPixels(), pixels, pixels_size); return true; } Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices. Using memcpy() to serialize a POD struct is highly discouraged. Just use the standard IPC param traits macros for doing it. Bug: 779428 Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334 Reviewed-on: https://chromium-review.googlesource.com/899649 Reviewed-by: Tom Sepez <[email protected]> Commit-Queue: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#534562} CWE ID: CWE-125
bool InitSkBitmapFromData(SkBitmap* bitmap, bool ParamTraits<SkImageInfo>::Read(const base::Pickle* m, base::PickleIterator* iter, SkImageInfo* r) { SkColorType color_type; SkAlphaType alpha_type; uint32_t width; uint32_t height; if (!ReadParam(m, iter, &color_type) || !ReadParam(m, iter, &alpha_type) || !ReadParam(m, iter, &width) || !ReadParam(m, iter, &height)) { return false; }
172,892
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UrlData::MergeFrom(const scoped_refptr<UrlData>& other) { if (ValidateDataOrigin(other->data_origin_)) { DCHECK(thread_checker_.CalledOnValidThread()); valid_until_ = std::max(valid_until_, other->valid_until_); set_length(other->length_); cacheable_ |= other->cacheable_; range_supported_ |= other->range_supported_; if (last_modified_.is_null()) { last_modified_ = other->last_modified_; } bytes_read_from_cache_ += other->bytes_read_from_cache_; set_has_opaque_data(other->has_opaque_data_); multibuffer()->MergeFrom(other->multibuffer()); } } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
void UrlData::MergeFrom(const scoped_refptr<UrlData>& other) { if (ValidateDataOrigin(other->data_origin_)) { DCHECK(thread_checker_.CalledOnValidThread()); valid_until_ = std::max(valid_until_, other->valid_until_); set_length(other->length_); cacheable_ |= other->cacheable_; range_supported_ |= other->range_supported_; if (last_modified_.is_null()) { last_modified_ = other->last_modified_; } bytes_read_from_cache_ += other->bytes_read_from_cache_; // is_cors_corss_origin_ will not relax from true to false. set_is_cors_cross_origin(other->is_cors_cross_origin_); multibuffer()->MergeFrom(other->multibuffer()); } }
172,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: do_ed_script (char const *inname, char const *outname, bool *outname_needs_removal, FILE *ofp) { static char const editor_program[] = EDITOR_PROGRAM; file_offset beginning_of_this_line; size_t chars_read; FILE *tmpfp = 0; char const *tmpname; int tmpfd; pid_t pid; if (! dry_run && ! skip_rest_of_patch) { /* Write ed script to a temporary file. This causes ed to abort on invalid commands such as when line numbers or ranges exceed the number of available lines. When ed reads from a pipe, it rejects invalid commands and treats the next line as a new command, which can lead to arbitrary command execution. */ tmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0); if (tmpfd == -1) pfatal ("Can't create temporary file %s", quotearg (tmpname)); tmpfp = fdopen (tmpfd, "w+b"); if (! tmpfp) pfatal ("Can't open stream for file %s", quotearg (tmpname)); } for (;;) { char ed_command_letter; beginning_of_this_line = file_tell (pfp); chars_read = get_line (); if (! chars_read) { next_intuit_at(beginning_of_this_line,p_input_line); break; } ed_command_letter = get_ed_command_letter (buf); if (ed_command_letter) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (ed_command_letter != 'd' && ed_command_letter != 's') { p_pass_comments_through = true; while ((chars_read = get_line ()) != 0) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (chars_read == 2 && strEQ (buf, ".\n")) break; } p_pass_comments_through = false; } } else { next_intuit_at(beginning_of_this_line,p_input_line); break; } } if (!tmpfp) return; if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, tmpfp) == 0 || fflush (tmpfp) != 0) write_fatal (); if (lseek (tmpfd, 0, SEEK_SET) == -1) pfatal ("Can't rewind to the beginning of file %s", quotearg (tmpname)); if (! dry_run && ! skip_rest_of_patch) { int exclusive = *outname_needs_removal ? 0 : O_EXCL; *outname_needs_removal = true; if (inerrno != ENOENT) { *outname_needs_removal = true; copy_file (inname, outname, 0, exclusive, instat.st_mode, true); } sprintf (buf, "%s %s%s", editor_program, verbosity == VERBOSE ? "" : "- ", outname); fflush (stdout); pid = fork(); fflush (stdout); else if (pid == 0) { dup2 (tmpfd, 0); execl ("/bin/sh", "sh", "-c", buf, (char *) 0); _exit (2); } else } else { int wstatus; if (waitpid (pid, &wstatus, 0) == -1 || ! WIFEXITED (wstatus) || WEXITSTATUS (wstatus) != 0) fatal ("%s FAILED", editor_program); } } Commit Message: CWE ID: CWE-78
do_ed_script (char const *inname, char const *outname, bool *outname_needs_removal, FILE *ofp) { static char const editor_program[] = EDITOR_PROGRAM; file_offset beginning_of_this_line; size_t chars_read; FILE *tmpfp = 0; char const *tmpname; int tmpfd; pid_t pid; if (! dry_run && ! skip_rest_of_patch) { /* Write ed script to a temporary file. This causes ed to abort on invalid commands such as when line numbers or ranges exceed the number of available lines. When ed reads from a pipe, it rejects invalid commands and treats the next line as a new command, which can lead to arbitrary command execution. */ tmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0); if (tmpfd == -1) pfatal ("Can't create temporary file %s", quotearg (tmpname)); tmpfp = fdopen (tmpfd, "w+b"); if (! tmpfp) pfatal ("Can't open stream for file %s", quotearg (tmpname)); } for (;;) { char ed_command_letter; beginning_of_this_line = file_tell (pfp); chars_read = get_line (); if (! chars_read) { next_intuit_at(beginning_of_this_line,p_input_line); break; } ed_command_letter = get_ed_command_letter (buf); if (ed_command_letter) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (ed_command_letter != 'd' && ed_command_letter != 's') { p_pass_comments_through = true; while ((chars_read = get_line ()) != 0) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (chars_read == 2 && strEQ (buf, ".\n")) break; } p_pass_comments_through = false; } } else { next_intuit_at(beginning_of_this_line,p_input_line); break; } } if (!tmpfp) return; if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, tmpfp) == 0 || fflush (tmpfp) != 0) write_fatal (); if (lseek (tmpfd, 0, SEEK_SET) == -1) pfatal ("Can't rewind to the beginning of file %s", quotearg (tmpname)); if (! dry_run && ! skip_rest_of_patch) { int exclusive = *outname_needs_removal ? 0 : O_EXCL; *outname_needs_removal = true; if (inerrno != ENOENT) { *outname_needs_removal = true; copy_file (inname, outname, 0, exclusive, instat.st_mode, true); } fflush (stdout); pid = fork(); fflush (stdout); else if (pid == 0) { dup2 (tmpfd, 0); assert (outname[0] != '!' && outname[0] != '-'); execlp (editor_program, editor_program, "-", outname, (char *) NULL); _exit (2); } else } else { int wstatus; if (waitpid (pid, &wstatus, 0) == -1 || ! WIFEXITED (wstatus) || WEXITSTATUS (wstatus) != 0) fatal ("%s FAILED", editor_program); } }
164,684
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PP_Bool LaunchSelLdr(PP_Instance instance, const char* alleged_url, int socket_count, void* imc_handles) { std::vector<nacl::FileDescriptor> sockets; IPC::Sender* sender = content::RenderThread::Get(); if (sender == NULL) sender = g_background_thread_sender.Pointer()->get(); IPC::ChannelHandle channel_handle; if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl( GURL(alleged_url), socket_count, &sockets, &channel_handle))) { return PP_FALSE; } bool invalid_handle = channel_handle.name.empty(); #if defined(OS_POSIX) if (!invalid_handle) invalid_handle = (channel_handle.socket.fd == -1); #endif if (!invalid_handle) g_channel_handle_map.Get()[instance] = channel_handle; CHECK(static_cast<int>(sockets.size()) == socket_count); for (int i = 0; i < socket_count; i++) { static_cast<nacl::Handle*>(imc_handles)[i] = nacl::ToNativeHandle(sockets[i]); } return PP_TRUE; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
PP_Bool LaunchSelLdr(PP_Instance instance, const char* alleged_url, int socket_count, void* imc_handles) { std::vector<nacl::FileDescriptor> sockets; IPC::Sender* sender = content::RenderThread::Get(); if (sender == NULL) sender = g_background_thread_sender.Pointer()->get(); if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl( GURL(alleged_url), socket_count, &sockets))) return PP_FALSE; CHECK(static_cast<int>(sockets.size()) == socket_count); for (int i = 0; i < socket_count; i++) { static_cast<nacl::Handle*>(imc_handles)[i] = nacl::ToNativeHandle(sockets[i]); } return PP_TRUE; }
170,736
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int handle_pte_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *pte, pmd_t *pmd, unsigned int flags) { pte_t entry; spinlock_t *ptl; /* * some architectures can have larger ptes than wordsize, * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and CONFIG_32BIT=y, * so READ_ONCE or ACCESS_ONCE cannot guarantee atomic accesses. * The code below just needs a consistent view for the ifs and * we later double check anyway with the ptl lock held. So here * a barrier will do. */ entry = *pte; barrier(); if (!pte_present(entry)) { if (pte_none(entry)) { if (vma->vm_ops) { if (likely(vma->vm_ops->fault)) return do_fault(mm, vma, address, pte, pmd, flags, entry); } return do_anonymous_page(mm, vma, address, pte, pmd, flags); } return do_swap_page(mm, vma, address, pte, pmd, flags, entry); } if (pte_protnone(entry)) return do_numa_page(mm, vma, address, entry, pte, pmd); ptl = pte_lockptr(mm, pmd); spin_lock(ptl); if (unlikely(!pte_same(*pte, entry))) goto unlock; if (flags & FAULT_FLAG_WRITE) { if (!pte_write(entry)) return do_wp_page(mm, vma, address, pte, pmd, ptl, entry); entry = pte_mkdirty(entry); } entry = pte_mkyoung(entry); if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) { update_mmu_cache(vma, address, pte); } else { /* * This is needed only for protection faults but the arch code * is not yet telling us if this is a protection fault or not. * This still avoids useless tlb flushes for .text page faults * with threads. */ if (flags & FAULT_FLAG_WRITE) flush_tlb_fix_spurious_fault(vma, address); } unlock: pte_unmap_unlock(pte, ptl); return 0; } Commit Message: mm: avoid setting up anonymous pages into file mapping Reading page fault handler code I've noticed that under right circumstances kernel would map anonymous pages into file mappings: if the VMA doesn't have vm_ops->fault() and the VMA wasn't fully populated on ->mmap(), kernel would handle page fault to not populated pte with do_anonymous_page(). Let's change page fault handler to use do_anonymous_page() only on anonymous VMA (->vm_ops == NULL) and make sure that the VMA is not shared. For file mappings without vm_ops->fault() or shred VMA without vm_ops, page fault on pte_none() entry would lead to SIGBUS. Signed-off-by: Kirill A. Shutemov <[email protected]> Acked-by: Oleg Nesterov <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
static int handle_pte_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *pte, pmd_t *pmd, unsigned int flags) { pte_t entry; spinlock_t *ptl; /* * some architectures can have larger ptes than wordsize, * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and CONFIG_32BIT=y, * so READ_ONCE or ACCESS_ONCE cannot guarantee atomic accesses. * The code below just needs a consistent view for the ifs and * we later double check anyway with the ptl lock held. So here * a barrier will do. */ entry = *pte; barrier(); if (!pte_present(entry)) { if (pte_none(entry)) { if (vma->vm_ops) return do_fault(mm, vma, address, pte, pmd, flags, entry); return do_anonymous_page(mm, vma, address, pte, pmd, flags); } return do_swap_page(mm, vma, address, pte, pmd, flags, entry); } if (pte_protnone(entry)) return do_numa_page(mm, vma, address, entry, pte, pmd); ptl = pte_lockptr(mm, pmd); spin_lock(ptl); if (unlikely(!pte_same(*pte, entry))) goto unlock; if (flags & FAULT_FLAG_WRITE) { if (!pte_write(entry)) return do_wp_page(mm, vma, address, pte, pmd, ptl, entry); entry = pte_mkdirty(entry); } entry = pte_mkyoung(entry); if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) { update_mmu_cache(vma, address, pte); } else { /* * This is needed only for protection faults but the arch code * is not yet telling us if this is a protection fault or not. * This still avoids useless tlb flushes for .text page faults * with threads. */ if (flags & FAULT_FLAG_WRITE) flush_tlb_fix_spurious_fault(vma, address); } unlock: pte_unmap_unlock(pte, ptl); return 0; }
167,569
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionTtsController::IsSpeaking() const { return current_utterance_ != NULL; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool ExtensionTtsController::IsSpeaking() const {
170,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int lua_websocket_read(lua_State *L) { apr_socket_t *sock; apr_status_t rv; int n = 0; apr_size_t len = 1; apr_size_t plen = 0; unsigned short payload_short = 0; apr_uint64_t payload_long = 0; unsigned char *mask_bytes; char byte; int plaintext; request_rec *r = ap_lua_check_request_rec(L, 1); plaintext = ap_lua_ssl_is_https(r->connection) ? 0 : 1; mask_bytes = apr_pcalloc(r->pool, 4); sock = ap_get_conn_socket(r->connection); /* Get opcode and FIN bit */ if (plaintext) { rv = apr_socket_recv(sock, &byte, &len); } else { rv = lua_websocket_readbytes(r->connection, &byte, 1); } if (rv == APR_SUCCESS) { unsigned char ubyte, fin, opcode, mask, payload; ubyte = (unsigned char)byte; /* fin bit is the first bit */ fin = ubyte >> (CHAR_BIT - 1); /* opcode is the last four bits (there's 3 reserved bits we don't care about) */ opcode = ubyte & 0xf; /* Get the payload length and mask bit */ if (plaintext) { rv = apr_socket_recv(sock, &byte, &len); } else { rv = lua_websocket_readbytes(r->connection, &byte, 1); } if (rv == APR_SUCCESS) { ubyte = (unsigned char)byte; /* Mask is the first bit */ mask = ubyte >> (CHAR_BIT - 1); /* Payload is the last 7 bits */ payload = ubyte & 0x7f; plen = payload; /* Extended payload? */ if (payload == 126) { len = 2; if (plaintext) { /* XXX: apr_socket_recv does not receive len bits, only up to len bits! */ rv = apr_socket_recv(sock, (char*) &payload_short, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) &payload_short, 2); } payload_short = ntohs(payload_short); if (rv == APR_SUCCESS) { plen = payload_short; } else { return 0; } } /* Super duper extended payload? */ if (payload == 127) { len = 8; if (plaintext) { rv = apr_socket_recv(sock, (char*) &payload_long, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) &payload_long, 8); } if (rv == APR_SUCCESS) { plen = ap_ntoh64(&payload_long); } else { return 0; } } ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Websocket: Reading %" APR_SIZE_T_FMT " (%s) bytes, masking is %s. %s", plen, (payload >= 126) ? "extra payload" : "no extra payload", mask ? "on" : "off", fin ? "This is a final frame" : "more to follow"); if (mask) { len = 4; if (plaintext) { rv = apr_socket_recv(sock, (char*) mask_bytes, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) mask_bytes, 4); } if (rv != APR_SUCCESS) { return 0; } } if (plen < (HUGE_STRING_LEN*1024) && plen > 0) { apr_size_t remaining = plen; apr_size_t received; apr_off_t at = 0; char *buffer = apr_palloc(r->pool, plen+1); buffer[plen] = 0; if (plaintext) { while (remaining > 0) { received = remaining; rv = apr_socket_recv(sock, buffer+at, &received); if (received > 0 ) { remaining -= received; at += received; } } ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Websocket: Frame contained %" APR_OFF_T_FMT " bytes, pushed to Lua stack", at); } else { rv = lua_websocket_readbytes(r->connection, buffer, remaining); ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Websocket: SSL Frame contained %" APR_SIZE_T_FMT " bytes, "\ "pushed to Lua stack", remaining); } if (mask) { for (n = 0; n < plen; n++) { buffer[n] ^= mask_bytes[n%4]; } } lua_pushlstring(L, buffer, (size_t) plen); /* push to stack */ lua_pushboolean(L, fin); /* push FIN bit to stack as boolean */ return 2; } /* Decide if we need to react to the opcode or not */ if (opcode == 0x09) { /* ping */ char frame[2]; plen = 2; frame[0] = 0x8A; frame[1] = 0; apr_socket_send(sock, frame, &plen); /* Pong! */ lua_websocket_read(L); /* read the next frame instead */ } } } return 0; } Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org) mod_lua: A maliciously crafted websockets PING after a script calls r:wsupgrade() can cause a child process crash. [Edward Lu <Chaosed0 gmail.com>] Discovered by Guido Vranken <guidovranken gmail.com> Submitted by: Edward Lu Committed by: covener git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-20
static int lua_websocket_read(lua_State *L) { apr_socket_t *sock; apr_status_t rv; int do_read = 1; int n = 0; apr_size_t len = 1; apr_size_t plen = 0; unsigned short payload_short = 0; apr_uint64_t payload_long = 0; unsigned char *mask_bytes; char byte; int plaintext; request_rec *r = ap_lua_check_request_rec(L, 1); plaintext = ap_lua_ssl_is_https(r->connection) ? 0 : 1; mask_bytes = apr_pcalloc(r->pool, 4); sock = ap_get_conn_socket(r->connection); while (do_read) { do_read = 0; /* Get opcode and FIN bit */ if (plaintext) { rv = apr_socket_recv(sock, &byte, &len); } else { rv = lua_websocket_readbytes(r->connection, &byte, 1); } if (rv == APR_SUCCESS) { unsigned char ubyte, fin, opcode, mask, payload; ubyte = (unsigned char)byte; /* fin bit is the first bit */ fin = ubyte >> (CHAR_BIT - 1); /* opcode is the last four bits (there's 3 reserved bits we don't care about) */ opcode = ubyte & 0xf; /* Get the payload length and mask bit */ if (plaintext) { rv = apr_socket_recv(sock, &byte, &len); } else { rv = lua_websocket_readbytes(r->connection, &byte, 1); } if (rv == APR_SUCCESS) { ubyte = (unsigned char)byte; /* Mask is the first bit */ mask = ubyte >> (CHAR_BIT - 1); /* Payload is the last 7 bits */ payload = ubyte & 0x7f; plen = payload; /* Extended payload? */ if (payload == 126) { len = 2; if (plaintext) { /* XXX: apr_socket_recv does not receive len bits, only up to len bits! */ rv = apr_socket_recv(sock, (char*) &payload_short, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) &payload_short, 2); } payload_short = ntohs(payload_short); if (rv == APR_SUCCESS) { plen = payload_short; } else { return 0; } } /* Super duper extended payload? */ if (payload == 127) { len = 8; if (plaintext) { rv = apr_socket_recv(sock, (char*) &payload_long, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) &payload_long, 8); } if (rv == APR_SUCCESS) { plen = ap_ntoh64(&payload_long); } else { return 0; } } ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Websocket: Reading %" APR_SIZE_T_FMT " (%s) bytes, masking is %s. %s", plen, (payload >= 126) ? "extra payload" : "no extra payload", mask ? "on" : "off", fin ? "This is a final frame" : "more to follow"); if (mask) { len = 4; if (plaintext) { rv = apr_socket_recv(sock, (char*) mask_bytes, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) mask_bytes, 4); } if (rv != APR_SUCCESS) { return 0; } } if (plen < (HUGE_STRING_LEN*1024) && plen > 0) { apr_size_t remaining = plen; apr_size_t received; apr_off_t at = 0; char *buffer = apr_palloc(r->pool, plen+1); buffer[plen] = 0; if (plaintext) { while (remaining > 0) { received = remaining; rv = apr_socket_recv(sock, buffer+at, &received); if (received > 0 ) { remaining -= received; at += received; } } ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Websocket: Frame contained %" APR_OFF_T_FMT " bytes, pushed to Lua stack", at); } else { rv = lua_websocket_readbytes(r->connection, buffer, remaining); ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Websocket: SSL Frame contained %" APR_SIZE_T_FMT " bytes, "\ "pushed to Lua stack", remaining); } if (mask) { for (n = 0; n < plen; n++) { buffer[n] ^= mask_bytes[n%4]; } } lua_pushlstring(L, buffer, (size_t) plen); /* push to stack */ lua_pushboolean(L, fin); /* push FIN bit to stack as boolean */ return 2; } /* Decide if we need to react to the opcode or not */ if (opcode == 0x09) { /* ping */ char frame[2]; plen = 2; frame[0] = 0x8A; frame[1] = 0; apr_socket_send(sock, frame, &plen); /* Pong! */ do_read = 1; } } } } return 0; }
166,744
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_vdec::update_portdef(OMX_PARAM_PORTDEFINITIONTYPE *portDefn) { OMX_ERRORTYPE eRet = OMX_ErrorNone; struct v4l2_format fmt; if (!portDefn) { return OMX_ErrorBadParameter; } DEBUG_PRINT_LOW("omx_vdec::update_portdef"); portDefn->nVersion.nVersion = OMX_SPEC_VERSION; portDefn->nSize = sizeof(portDefn); portDefn->eDomain = OMX_PortDomainVideo; if (drv_ctx.frame_rate.fps_denominator > 0) portDefn->format.video.xFramerate = (drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator) << 16; //Q16 format else { DEBUG_PRINT_ERROR("Error: Divide by zero"); return OMX_ErrorBadParameter; } memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (0 == portDefn->nPortIndex) { portDefn->eDir = OMX_DirInput; portDefn->nBufferCountActual = drv_ctx.ip_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.ip_buf.mincount; portDefn->nBufferSize = drv_ctx.ip_buf.buffer_size; portDefn->format.video.eColorFormat = OMX_COLOR_FormatUnused; portDefn->format.video.eCompressionFormat = eCompressionFormat; portDefn->bEnabled = m_inp_bEnabled; portDefn->bPopulated = m_inp_bPopulated; fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.pixelformat = output_capability; } else if (1 == portDefn->nPortIndex) { unsigned int buf_size = 0; if (!client_buffers.update_buffer_req()) { DEBUG_PRINT_ERROR("client_buffers.update_buffer_req Failed"); return OMX_ErrorHardware; } if (!client_buffers.get_buffer_req(buf_size)) { DEBUG_PRINT_ERROR("update buffer requirements"); return OMX_ErrorHardware; } portDefn->nBufferSize = buf_size; portDefn->eDir = OMX_DirOutput; portDefn->nBufferCountActual = drv_ctx.op_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.op_buf.mincount; portDefn->format.video.eCompressionFormat = OMX_VIDEO_CodingUnused; portDefn->bEnabled = m_out_bEnabled; portDefn->bPopulated = m_out_bPopulated; if (!client_buffers.get_color_format(portDefn->format.video.eColorFormat)) { DEBUG_PRINT_ERROR("Error in getting color format"); return OMX_ErrorHardware; } fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; } else { portDefn->eDir = OMX_DirMax; DEBUG_PRINT_LOW(" get_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } if (is_down_scalar_enabled) { int ret = 0; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("update_portdef : Error in getting port resolution"); return OMX_ErrorHardware; } else { portDefn->format.video.nFrameWidth = fmt.fmt.pix_mp.width; portDefn->format.video.nFrameHeight = fmt.fmt.pix_mp.height; portDefn->format.video.nStride = fmt.fmt.pix_mp.plane_fmt[0].bytesperline; portDefn->format.video.nSliceHeight = fmt.fmt.pix_mp.plane_fmt[0].reserved[0]; } } else { portDefn->format.video.nFrameHeight = drv_ctx.video_resolution.frame_height; portDefn->format.video.nFrameWidth = drv_ctx.video_resolution.frame_width; portDefn->format.video.nStride = drv_ctx.video_resolution.stride; portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.scan_lines; } if ((portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar) || (portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar)) { portDefn->format.video.nStride = ALIGN(drv_ctx.video_resolution.frame_width, 16); portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.frame_height; } DEBUG_PRINT_HIGH("update_portdef(%u): Width = %u Height = %u Stride = %d " "SliceHeight = %u eColorFormat = %d nBufSize %u nBufCnt %u", (unsigned int)portDefn->nPortIndex, (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nStride, (unsigned int)portDefn->format.video.nSliceHeight, (unsigned int)portDefn->format.video.eColorFormat, (unsigned int)portDefn->nBufferSize, (unsigned int)portDefn->nBufferCountActual); return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
OMX_ERRORTYPE omx_vdec::update_portdef(OMX_PARAM_PORTDEFINITIONTYPE *portDefn) { OMX_ERRORTYPE eRet = OMX_ErrorNone; struct v4l2_format fmt; if (!portDefn) { return OMX_ErrorBadParameter; } DEBUG_PRINT_LOW("omx_vdec::update_portdef"); portDefn->nVersion.nVersion = OMX_SPEC_VERSION; portDefn->nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE); portDefn->eDomain = OMX_PortDomainVideo; if (drv_ctx.frame_rate.fps_denominator > 0) portDefn->format.video.xFramerate = (drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator) << 16; //Q16 format else { DEBUG_PRINT_ERROR("Error: Divide by zero"); return OMX_ErrorBadParameter; } memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (0 == portDefn->nPortIndex) { portDefn->eDir = OMX_DirInput; portDefn->nBufferCountActual = drv_ctx.ip_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.ip_buf.mincount; portDefn->nBufferSize = drv_ctx.ip_buf.buffer_size; portDefn->format.video.eColorFormat = OMX_COLOR_FormatUnused; portDefn->format.video.eCompressionFormat = eCompressionFormat; portDefn->bEnabled = m_inp_bEnabled; portDefn->bPopulated = m_inp_bPopulated; fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.pixelformat = output_capability; } else if (1 == portDefn->nPortIndex) { unsigned int buf_size = 0; if (!client_buffers.update_buffer_req()) { DEBUG_PRINT_ERROR("client_buffers.update_buffer_req Failed"); return OMX_ErrorHardware; } if (!client_buffers.get_buffer_req(buf_size)) { DEBUG_PRINT_ERROR("update buffer requirements"); return OMX_ErrorHardware; } portDefn->nBufferSize = buf_size; portDefn->eDir = OMX_DirOutput; portDefn->nBufferCountActual = drv_ctx.op_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.op_buf.mincount; portDefn->format.video.eCompressionFormat = OMX_VIDEO_CodingUnused; portDefn->bEnabled = m_out_bEnabled; portDefn->bPopulated = m_out_bPopulated; if (!client_buffers.get_color_format(portDefn->format.video.eColorFormat)) { DEBUG_PRINT_ERROR("Error in getting color format"); return OMX_ErrorHardware; } fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; } else { portDefn->eDir = OMX_DirMax; DEBUG_PRINT_LOW(" get_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } if (is_down_scalar_enabled) { int ret = 0; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("update_portdef : Error in getting port resolution"); return OMX_ErrorHardware; } else { portDefn->format.video.nFrameWidth = fmt.fmt.pix_mp.width; portDefn->format.video.nFrameHeight = fmt.fmt.pix_mp.height; portDefn->format.video.nStride = fmt.fmt.pix_mp.plane_fmt[0].bytesperline; portDefn->format.video.nSliceHeight = fmt.fmt.pix_mp.plane_fmt[0].reserved[0]; } } else { portDefn->format.video.nFrameHeight = drv_ctx.video_resolution.frame_height; portDefn->format.video.nFrameWidth = drv_ctx.video_resolution.frame_width; portDefn->format.video.nStride = drv_ctx.video_resolution.stride; portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.scan_lines; } if ((portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar) || (portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar)) { portDefn->format.video.nStride = ALIGN(drv_ctx.video_resolution.frame_width, 16); portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.frame_height; } DEBUG_PRINT_HIGH("update_portdef(%u): Width = %u Height = %u Stride = %d " "SliceHeight = %u eColorFormat = %d nBufSize %u nBufCnt %u", (unsigned int)portDefn->nPortIndex, (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nStride, (unsigned int)portDefn->format.video.nSliceHeight, (unsigned int)portDefn->format.video.eColorFormat, (unsigned int)portDefn->nBufferSize, (unsigned int)portDefn->nBufferCountActual); return eRet; }
173,792
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags) { CMS_SignerInfo *si; STACK_OF(CMS_SignerInfo) *sinfos; STACK_OF(X509) *cms_certs = NULL; STACK_OF(X509_CRL) *crls = NULL; X509 *signer; int i, scount = 0, ret = 0; BIO *cmsbio = NULL, *tmpin = NULL; if (!dcont && !check_content(cms)) return 0; /* Attempt to find all signer certificates */ sinfos = CMS_get0_SignerInfos(cms); if (sk_CMS_SignerInfo_num(sinfos) <= 0) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_NO_SIGNERS); goto err; } for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); CMS_SignerInfo_get0_algs(si, NULL, &signer, NULL, NULL); if (signer) scount++; } if (scount != sk_CMS_SignerInfo_num(sinfos)) scount += CMS_set1_signers_certs(cms, certs, flags); if (scount != sk_CMS_SignerInfo_num(sinfos)) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND); goto err; } /* Attempt to verify all signers certs */ if (!(flags & CMS_NO_SIGNER_CERT_VERIFY)) { cms_certs = CMS_get1_certs(cms); if (!(flags & CMS_NOCRL)) crls = CMS_get1_crls(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (!cms_signerinfo_verify_cert(si, store, cms_certs, crls, flags)) goto err; } } /* Attempt to verify all SignerInfo signed attribute signatures */ if (!(flags & CMS_NO_ATTR_VERIFY)) { for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (CMS_signed_get_attr_count(si) < 0) continue; if (CMS_SignerInfo_verify(si) <= 0) goto err; } } /* Performance optimization: if the content is a memory BIO then * store its contents in a temporary read only memory BIO. This * avoids potentially large numbers of slow copies of data which will * occur when reading from a read write memory BIO when signatures * are calculated. */ if (dcont && (BIO_method_type(dcont) == BIO_TYPE_MEM)) { char *ptr; long len; len = BIO_get_mem_data(dcont, &ptr); tmpin = BIO_new_mem_buf(ptr, len); if (tmpin == NULL) { CMSerr(CMS_F_CMS_VERIFY,ERR_R_MALLOC_FAILURE); return 0; } } else tmpin = dcont; cmsbio=CMS_dataInit(cms, tmpin); if (!cmsbio) goto err; if (!cms_copy_content(out, cmsbio, flags)) goto err; if (!(flags & CMS_NO_CONTENT_VERIFY)) { for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (CMS_SignerInfo_verify_content(si, cmsbio) <= 0) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_CONTENT_VERIFY_ERROR); goto err; } } } ret = 1; err: if (dcont && (tmpin == dcont)) do_free_upto(cmsbio, dcont); else BIO_free_all(cmsbio); if (cms_certs) sk_X509_pop_free(cms_certs, X509_free); if (crls) sk_X509_CRL_pop_free(crls, X509_CRL_free); return ret; } Commit Message: Canonicalise input in CMS_verify. If content is detached and not binary mode translate the input to CRLF format. Before this change the input was verified verbatim which lead to a discrepancy between sign and verify. CWE ID: CWE-399
int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags) { CMS_SignerInfo *si; STACK_OF(CMS_SignerInfo) *sinfos; STACK_OF(X509) *cms_certs = NULL; STACK_OF(X509_CRL) *crls = NULL; X509 *signer; int i, scount = 0, ret = 0; BIO *cmsbio = NULL, *tmpin = NULL, *tmpout = NULL; if (!dcont && !check_content(cms)) return 0; /* Attempt to find all signer certificates */ sinfos = CMS_get0_SignerInfos(cms); if (sk_CMS_SignerInfo_num(sinfos) <= 0) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_NO_SIGNERS); goto err; } for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); CMS_SignerInfo_get0_algs(si, NULL, &signer, NULL, NULL); if (signer) scount++; } if (scount != sk_CMS_SignerInfo_num(sinfos)) scount += CMS_set1_signers_certs(cms, certs, flags); if (scount != sk_CMS_SignerInfo_num(sinfos)) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND); goto err; } /* Attempt to verify all signers certs */ if (!(flags & CMS_NO_SIGNER_CERT_VERIFY)) { cms_certs = CMS_get1_certs(cms); if (!(flags & CMS_NOCRL)) crls = CMS_get1_crls(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (!cms_signerinfo_verify_cert(si, store, cms_certs, crls, flags)) goto err; } } /* Attempt to verify all SignerInfo signed attribute signatures */ if (!(flags & CMS_NO_ATTR_VERIFY)) { for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (CMS_signed_get_attr_count(si) < 0) continue; if (CMS_SignerInfo_verify(si) <= 0) goto err; } } /* Performance optimization: if the content is a memory BIO then * store its contents in a temporary read only memory BIO. This * avoids potentially large numbers of slow copies of data which will * occur when reading from a read write memory BIO when signatures * are calculated. */ if (dcont && (BIO_method_type(dcont) == BIO_TYPE_MEM)) { char *ptr; long len; len = BIO_get_mem_data(dcont, &ptr); tmpin = BIO_new_mem_buf(ptr, len); if (tmpin == NULL) { CMSerr(CMS_F_CMS_VERIFY,ERR_R_MALLOC_FAILURE); return 0; } } else tmpin = dcont; /* If not binary mode and detached generate digests by *writing* * through the BIO. That makes it possible to canonicalise the * input. */ if (!(flags & SMIME_BINARY) && dcont) { /* Create output BIO so we can either handle text or to * ensure included content doesn't override detached content. */ tmpout = cms_get_text_bio(out, flags); if(!tmpout) { CMSerr(CMS_F_CMS_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } cmsbio = CMS_dataInit(cms, tmpout); if (!cmsbio) goto err; /* Don't use SMIME_TEXT for verify: it adds headers and * we want to remove them. */ SMIME_crlf_copy(dcont, cmsbio, flags & ~SMIME_TEXT); if(flags & CMS_TEXT) { if (!SMIME_text(tmpout, out)) { CMSerr(CMS_F_CMS_VERIFY,CMS_R_SMIME_TEXT_ERROR); goto err; } } } else { cmsbio=CMS_dataInit(cms, tmpin); if (!cmsbio) goto err; if (!cms_copy_content(out, cmsbio, flags)) goto err; } if (!(flags & CMS_NO_CONTENT_VERIFY)) { for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (CMS_SignerInfo_verify_content(si, cmsbio) <= 0) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_CONTENT_VERIFY_ERROR); goto err; } } } ret = 1; err: if (!(flags & SMIME_BINARY) && dcont) { do_free_upto(cmsbio, tmpout); if (tmpin != dcont) BIO_free(tmpin); } else { if (dcont && (tmpin == dcont)) do_free_upto(cmsbio, dcont); else BIO_free_all(cmsbio); } if (tmpout && out != tmpout) BIO_free_all(tmpout); if (cms_certs) sk_X509_pop_free(cms_certs, X509_free); if (crls) sk_X509_CRL_pop_free(crls, X509_CRL_free); return ret; }
166,688
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height) { const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; int i, v, offset, count, segments; segments = bytestream2_get_le16(gb); while (segments--) { if (bytestream2_get_bytes_left(gb) < 2) return AVERROR_INVALIDDATA; if (mask == 0x10000) { bitbuf = bytestream2_get_le16u(gb); mask = 1; } if (bitbuf & mask) { v = bytestream2_get_le16(gb); offset = (v & 0x1FFF) << 2; count = ((v >> 13) + 2) << 1; if (frame - frame_start < offset || frame_end - frame < count*2 + width) return AVERROR_INVALIDDATA; for (i = 0; i < count; i++) { frame[0] = frame[1] = frame[width] = frame[width + 1] = frame[-offset]; frame += 2; } } else if (bitbuf & (mask << 1)) { v = bytestream2_get_le16(gb)*2; if (frame - frame_end < v) return AVERROR_INVALIDDATA; frame += v; } else { if (frame_end - frame < width + 3) return AVERROR_INVALIDDATA; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; } mask <<= 2; } return 0; } Commit Message: avcodec/dfa: Fix off by 1 error Fixes out of array access Fixes: 1345/clusterfuzz-testcase-minimized-6062963045695488 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height) { const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; int i, v, offset, count, segments; segments = bytestream2_get_le16(gb); while (segments--) { if (bytestream2_get_bytes_left(gb) < 2) return AVERROR_INVALIDDATA; if (mask == 0x10000) { bitbuf = bytestream2_get_le16u(gb); mask = 1; } if (bitbuf & mask) { v = bytestream2_get_le16(gb); offset = (v & 0x1FFF) << 2; count = ((v >> 13) + 2) << 1; if (frame - frame_start < offset || frame_end - frame < count*2 + width) return AVERROR_INVALIDDATA; for (i = 0; i < count; i++) { frame[0] = frame[1] = frame[width] = frame[width + 1] = frame[-offset]; frame += 2; } } else if (bitbuf & (mask << 1)) { v = bytestream2_get_le16(gb)*2; if (frame - frame_end < v) return AVERROR_INVALIDDATA; frame += v; } else { if (frame_end - frame < width + 4) return AVERROR_INVALIDDATA; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; } mask <<= 2; } return 0; }
168,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const char *parse_scheme(struct parse_state *state) { size_t mb; const char *tmp = state->ptr; do { switch (*state->ptr) { case ':': /* scheme delimiter */ state->url.scheme = &state->buffer[0]; state->buffer[state->offset++] = 0; return ++state->ptr; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': case '.': if (state->ptr == tmp) { return tmp; } /* no break */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': /* scheme part */ state->buffer[state->offset++] = *state->ptr; break; default: if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) { /* soft fail; parse path next */ return tmp; } state->ptr += mb - 1; } } while (++state->ptr != state->end); return state->ptr = tmp; } Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions) The parser's offset was not reset when we softfail in scheme parsing and continue to parse a path. Thanks to hlt99 at blinkenshell dot org for the report. CWE ID: CWE-119
static const char *parse_scheme(struct parse_state *state) { size_t mb; const char *tmp = state->ptr; do { switch (*state->ptr) { case ':': /* scheme delimiter */ state->url.scheme = &state->buffer[0]; state->buffer[state->offset++] = 0; return ++state->ptr; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': case '.': if (state->ptr == tmp) { goto softfail; } /* no break */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': /* scheme part */ state->buffer[state->offset++] = *state->ptr; break; default: if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) { goto softfail; } state->ptr += mb - 1; } } while (++state->ptr != state->end); softfail: state->offset = 0; return state->ptr = tmp; }
168,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: find_referral_tgs(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_principal *krbtgt_princ) { krb5_error_code retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; char **realms = NULL, *hostname = NULL; krb5_data srealm = request->server->realm; if (!is_referral_req(kdc_active_realm, request)) goto cleanup; hostname = data2string(krb5_princ_component(kdc_context, request->server, 1)); if (hostname == NULL) { retval = ENOMEM; goto cleanup; } /* If the hostname doesn't contain a '.', it's not a FQDN. */ if (strchr(hostname, '.') == NULL) goto cleanup; retval = krb5_get_host_realm(kdc_context, hostname, &realms); if (retval) { /* no match found */ kdc_err(kdc_context, retval, "unable to find realm of host"); goto cleanup; } /* Don't return a referral to the empty realm or the service realm. */ if (realms == NULL || realms[0] == '\0' || data_eq_string(srealm, realms[0])) { retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto cleanup; } retval = krb5_build_principal(kdc_context, krbtgt_princ, srealm.length, srealm.data, "krbtgt", realms[0], (char *)0); cleanup: krb5_free_host_realm(kdc_context, realms); free(hostname); return retval; } Commit Message: KDC null deref due to referrals [CVE-2013-1417] An authenticated remote client can cause a KDC to crash by making a valid TGS-REQ to a KDC serving a realm with a single-component name. The process_tgs_req() function dereferences a null pointer because an unusual failure condition causes a helper function to return success. While attempting to provide cross-realm referrals for host-based service principals, the find_referral_tgs() function could return a TGS principal for a zero-length realm name (indicating that the hostname in the service principal has no known realm associated with it). Subsequently, the find_alternate_tgs() function would attempt to construct a path to this empty-string realm, and return success along with a null pointer in its output parameter. This happens because krb5_walk_realm_tree() returns a list of length one when it attempts to construct a transit path between a single-component realm and the empty-string realm. This list causes a loop in find_alternate_tgs() to iterate over zero elements, resulting in the unexpected output of a null pointer, which process_tgs_req() proceeds to dereference because there is no error condition. Add an error condition to find_referral_tgs() when krb5_get_host_realm() returns an empty realm name. Also add an error condition to find_alternate_tgs() to handle the length-one output from krb5_walk_realm_tree(). The vulnerable configuration is not likely to arise in practice. (Realm names that have a single component are likely to be test realms.) Releases prior to krb5-1.11 are not vulnerable. Thanks to Sol Jerome for reporting this problem. CVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C (cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0) ticket: 7668 version_fixed: 1.11.4 status: resolved CWE ID: CWE-20
find_referral_tgs(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_principal *krbtgt_princ) { krb5_error_code retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; char **realms = NULL, *hostname = NULL; krb5_data srealm = request->server->realm; if (!is_referral_req(kdc_active_realm, request)) goto cleanup; hostname = data2string(krb5_princ_component(kdc_context, request->server, 1)); if (hostname == NULL) { retval = ENOMEM; goto cleanup; } /* If the hostname doesn't contain a '.', it's not a FQDN. */ if (strchr(hostname, '.') == NULL) goto cleanup; retval = krb5_get_host_realm(kdc_context, hostname, &realms); if (retval) { /* no match found */ kdc_err(kdc_context, retval, "unable to find realm of host"); goto cleanup; } /* Don't return a referral to the empty realm or the service realm. */ if (realms == NULL || realms[0] == NULL || *realms[0] == '\0' || data_eq_string(srealm, realms[0])) { retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto cleanup; } retval = krb5_build_principal(kdc_context, krbtgt_princ, srealm.length, srealm.data, "krbtgt", realms[0], (char *)0); cleanup: krb5_free_host_realm(kdc_context, realms); free(hostname); return retval; }
166,131
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE5(perf_event_open, struct perf_event_attr __user *, attr_uptr, pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) { struct perf_event *group_leader = NULL, *output_event = NULL; struct perf_event *event, *sibling; struct perf_event_attr attr; struct perf_event_context *ctx; struct file *event_file = NULL; struct fd group = {NULL, 0}; struct task_struct *task = NULL; struct pmu *pmu; int event_fd; int move_group = 0; int err; int f_flags = O_RDWR; /* for future expandability... */ if (flags & ~PERF_FLAG_ALL) return -EINVAL; err = perf_copy_attr(attr_uptr, &attr); if (err) return err; if (!attr.exclude_kernel) { if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr.freq) { if (attr.sample_freq > sysctl_perf_event_sample_rate) return -EINVAL; } else { if (attr.sample_period & (1ULL << 63)) return -EINVAL; } /* * In cgroup mode, the pid argument is used to pass the fd * opened to the cgroup directory in cgroupfs. The cpu argument * designates the cpu on which to monitor threads from that * cgroup. */ if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) return -EINVAL; if (flags & PERF_FLAG_FD_CLOEXEC) f_flags |= O_CLOEXEC; event_fd = get_unused_fd_flags(f_flags); if (event_fd < 0) return event_fd; if (group_fd != -1) { err = perf_fget_light(group_fd, &group); if (err) goto err_fd; group_leader = group.file->private_data; if (flags & PERF_FLAG_FD_OUTPUT) output_event = group_leader; if (flags & PERF_FLAG_FD_NO_GROUP) group_leader = NULL; } if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { task = find_lively_task_by_vpid(pid); if (IS_ERR(task)) { err = PTR_ERR(task); goto err_group_fd; } } if (task && group_leader && group_leader->attr.inherit != attr.inherit) { err = -EINVAL; goto err_task; } get_online_cpus(); event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL, NULL); if (IS_ERR(event)) { err = PTR_ERR(event); goto err_cpus; } if (flags & PERF_FLAG_PID_CGROUP) { err = perf_cgroup_connect(pid, event, &attr, group_leader); if (err) { __free_event(event); goto err_cpus; } } if (is_sampling_event(event)) { if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { err = -ENOTSUPP; goto err_alloc; } } account_event(event); /* * Special case software events and allow them to be part of * any hardware group. */ pmu = event->pmu; if (group_leader && (is_software_event(event) != is_software_event(group_leader))) { if (is_software_event(event)) { /* * If event and group_leader are not both a software * event, and event is, then group leader is not. * * Allow the addition of software events to !software * groups, this is safe because software events never * fail to schedule. */ pmu = group_leader->pmu; } else if (is_software_event(group_leader) && (group_leader->group_flags & PERF_GROUP_SOFTWARE)) { /* * In case the group is a pure software group, and we * try to add a hardware event, move the whole group to * the hardware context. */ move_group = 1; } } /* * Get the target context (task or percpu): */ ctx = find_get_context(pmu, task, event->cpu); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_alloc; } if (task) { put_task_struct(task); task = NULL; } /* * Look up the group leader (we will attach this event to it): */ if (group_leader) { err = -EINVAL; /* * Do not allow a recursive hierarchy (this new sibling * becoming part of another group-sibling): */ if (group_leader->group_leader != group_leader) goto err_context; /* * Do not allow to attach to a group in a different * task or CPU context: */ if (move_group) { if (group_leader->ctx->type != ctx->type) goto err_context; } else { if (group_leader->ctx != ctx) goto err_context; } /* * Only a group leader can be exclusive or pinned */ if (attr.exclusive || attr.pinned) goto err_context; } if (output_event) { err = perf_event_set_output(event, output_event); if (err) goto err_context; } event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); if (IS_ERR(event_file)) { err = PTR_ERR(event_file); goto err_context; } if (move_group) { struct perf_event_context *gctx = group_leader->ctx; mutex_lock(&gctx->mutex); perf_remove_from_context(group_leader, false); /* * Removing from the context ends up with disabled * event. What we want here is event in the initial * startup state, ready to be add into new context. */ perf_event__state_init(group_leader); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_remove_from_context(sibling, false); perf_event__state_init(sibling); put_ctx(gctx); } mutex_unlock(&gctx->mutex); put_ctx(gctx); } WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); if (move_group) { synchronize_rcu(); perf_install_in_context(ctx, group_leader, group_leader->cpu); get_ctx(ctx); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_install_in_context(ctx, sibling, sibling->cpu); get_ctx(ctx); } } perf_install_in_context(ctx, event, event->cpu); perf_unpin_context(ctx); mutex_unlock(&ctx->mutex); put_online_cpus(); event->owner = current; mutex_lock(&current->perf_event_mutex); list_add_tail(&event->owner_entry, &current->perf_event_list); mutex_unlock(&current->perf_event_mutex); /* * Precalculate sample_data sizes */ perf_event__header_size(event); perf_event__id_header_size(event); /* * Drop the reference on the group_event after placing the * new event on the sibling_list. This ensures destruction * of the group leader will find the pointer to itself in * perf_group_detach(). */ fdput(group); fd_install(event_fd, event_file); return event_fd; err_context: perf_unpin_context(ctx); put_ctx(ctx); err_alloc: free_event(event); err_cpus: put_online_cpus(); err_task: if (task) put_task_struct(task); err_group_fd: fdput(group); err_fd: put_unused_fd(event_fd); return err; } Commit Message: perf: Tighten (and fix) the grouping condition The fix from 9fc81d87420d ("perf: Fix events installation during moving group") was incomplete in that it failed to recognise that creating a group with events for different CPUs is semantically broken -- they cannot be co-scheduled. Furthermore, it leads to real breakage where, when we create an event for CPU Y and then migrate it to form a group on CPU X, the code gets confused where the counter is programmed -- triggered in practice as well by me via the perf fuzzer. Fix this by tightening the rules for creating groups. Only allow grouping of counters that can be co-scheduled in the same context. This means for the same task and/or the same cpu. Fixes: 9fc81d87420d ("perf: Fix events installation during moving group") Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
SYSCALL_DEFINE5(perf_event_open, struct perf_event_attr __user *, attr_uptr, pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) { struct perf_event *group_leader = NULL, *output_event = NULL; struct perf_event *event, *sibling; struct perf_event_attr attr; struct perf_event_context *ctx; struct file *event_file = NULL; struct fd group = {NULL, 0}; struct task_struct *task = NULL; struct pmu *pmu; int event_fd; int move_group = 0; int err; int f_flags = O_RDWR; /* for future expandability... */ if (flags & ~PERF_FLAG_ALL) return -EINVAL; err = perf_copy_attr(attr_uptr, &attr); if (err) return err; if (!attr.exclude_kernel) { if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr.freq) { if (attr.sample_freq > sysctl_perf_event_sample_rate) return -EINVAL; } else { if (attr.sample_period & (1ULL << 63)) return -EINVAL; } /* * In cgroup mode, the pid argument is used to pass the fd * opened to the cgroup directory in cgroupfs. The cpu argument * designates the cpu on which to monitor threads from that * cgroup. */ if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) return -EINVAL; if (flags & PERF_FLAG_FD_CLOEXEC) f_flags |= O_CLOEXEC; event_fd = get_unused_fd_flags(f_flags); if (event_fd < 0) return event_fd; if (group_fd != -1) { err = perf_fget_light(group_fd, &group); if (err) goto err_fd; group_leader = group.file->private_data; if (flags & PERF_FLAG_FD_OUTPUT) output_event = group_leader; if (flags & PERF_FLAG_FD_NO_GROUP) group_leader = NULL; } if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { task = find_lively_task_by_vpid(pid); if (IS_ERR(task)) { err = PTR_ERR(task); goto err_group_fd; } } if (task && group_leader && group_leader->attr.inherit != attr.inherit) { err = -EINVAL; goto err_task; } get_online_cpus(); event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL, NULL); if (IS_ERR(event)) { err = PTR_ERR(event); goto err_cpus; } if (flags & PERF_FLAG_PID_CGROUP) { err = perf_cgroup_connect(pid, event, &attr, group_leader); if (err) { __free_event(event); goto err_cpus; } } if (is_sampling_event(event)) { if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { err = -ENOTSUPP; goto err_alloc; } } account_event(event); /* * Special case software events and allow them to be part of * any hardware group. */ pmu = event->pmu; if (group_leader && (is_software_event(event) != is_software_event(group_leader))) { if (is_software_event(event)) { /* * If event and group_leader are not both a software * event, and event is, then group leader is not. * * Allow the addition of software events to !software * groups, this is safe because software events never * fail to schedule. */ pmu = group_leader->pmu; } else if (is_software_event(group_leader) && (group_leader->group_flags & PERF_GROUP_SOFTWARE)) { /* * In case the group is a pure software group, and we * try to add a hardware event, move the whole group to * the hardware context. */ move_group = 1; } } /* * Get the target context (task or percpu): */ ctx = find_get_context(pmu, task, event->cpu); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_alloc; } if (task) { put_task_struct(task); task = NULL; } /* * Look up the group leader (we will attach this event to it): */ if (group_leader) { err = -EINVAL; /* * Do not allow a recursive hierarchy (this new sibling * becoming part of another group-sibling): */ if (group_leader->group_leader != group_leader) goto err_context; /* * Do not allow to attach to a group in a different * task or CPU context: */ if (move_group) { /* * Make sure we're both on the same task, or both * per-cpu events. */ if (group_leader->ctx->task != ctx->task) goto err_context; /* * Make sure we're both events for the same CPU; * grouping events for different CPUs is broken; since * you can never concurrently schedule them anyhow. */ if (group_leader->cpu != event->cpu) goto err_context; } else { if (group_leader->ctx != ctx) goto err_context; } /* * Only a group leader can be exclusive or pinned */ if (attr.exclusive || attr.pinned) goto err_context; } if (output_event) { err = perf_event_set_output(event, output_event); if (err) goto err_context; } event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); if (IS_ERR(event_file)) { err = PTR_ERR(event_file); goto err_context; } if (move_group) { struct perf_event_context *gctx = group_leader->ctx; mutex_lock(&gctx->mutex); perf_remove_from_context(group_leader, false); /* * Removing from the context ends up with disabled * event. What we want here is event in the initial * startup state, ready to be add into new context. */ perf_event__state_init(group_leader); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_remove_from_context(sibling, false); perf_event__state_init(sibling); put_ctx(gctx); } mutex_unlock(&gctx->mutex); put_ctx(gctx); } WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); if (move_group) { synchronize_rcu(); perf_install_in_context(ctx, group_leader, group_leader->cpu); get_ctx(ctx); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_install_in_context(ctx, sibling, sibling->cpu); get_ctx(ctx); } } perf_install_in_context(ctx, event, event->cpu); perf_unpin_context(ctx); mutex_unlock(&ctx->mutex); put_online_cpus(); event->owner = current; mutex_lock(&current->perf_event_mutex); list_add_tail(&event->owner_entry, &current->perf_event_list); mutex_unlock(&current->perf_event_mutex); /* * Precalculate sample_data sizes */ perf_event__header_size(event); perf_event__id_header_size(event); /* * Drop the reference on the group_event after placing the * new event on the sibling_list. This ensures destruction * of the group leader will find the pointer to itself in * perf_group_detach(). */ fdput(group); fd_install(event_fd, event_file); return event_fd; err_context: perf_unpin_context(ctx); put_ctx(ctx); err_alloc: free_event(event); err_cpus: put_online_cpus(); err_task: if (task) put_task_struct(task); err_group_fd: fdput(group); err_fd: put_unused_fd(event_fd); return err; }
168,851
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp, struct mount *source_mnt, struct hlist_head *tree_list) { struct mount *m, *n; int ret = 0; /* * we don't want to bother passing tons of arguments to * propagate_one(); everything is serialized by namespace_sem, * so globals will do just fine. */ user_ns = current->nsproxy->mnt_ns->user_ns; last_dest = dest_mnt; last_source = source_mnt; mp = dest_mp; list = tree_list; dest_master = dest_mnt->mnt_master; /* all peers of dest_mnt, except dest_mnt itself */ for (n = next_peer(dest_mnt); n != dest_mnt; n = next_peer(n)) { ret = propagate_one(n); if (ret) goto out; } /* all slave groups */ for (m = next_group(dest_mnt, dest_mnt); m; m = next_group(m, dest_mnt)) { /* everything in that slave group */ n = m; do { ret = propagate_one(n); if (ret) goto out; n = next_peer(n); } while (n != m); } out: read_seqlock_excl(&mount_lock); hlist_for_each_entry(n, tree_list, mnt_hash) { m = n->mnt_parent; if (m->mnt_master != dest_mnt->mnt_master) CLEAR_MNT_MARK(m->mnt_master); } read_sequnlock_excl(&mount_lock); return ret; } Commit Message: propogate_mnt: Handle the first propogated copy being a slave When the first propgated copy was a slave the following oops would result: > BUG: unable to handle kernel NULL pointer dereference at 0000000000000010 > IP: [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0 > PGD bacd4067 PUD bac66067 PMD 0 > Oops: 0000 [#1] SMP > Modules linked in: > CPU: 1 PID: 824 Comm: mount Not tainted 4.6.0-rc5userns+ #1523 > Hardware name: Bochs Bochs, BIOS Bochs 01/01/2007 > task: ffff8800bb0a8000 ti: ffff8800bac3c000 task.ti: ffff8800bac3c000 > RIP: 0010:[<ffffffff811fba4e>] [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0 > RSP: 0018:ffff8800bac3fd38 EFLAGS: 00010283 > RAX: 0000000000000000 RBX: ffff8800bb77ec00 RCX: 0000000000000010 > RDX: 0000000000000000 RSI: ffff8800bb58c000 RDI: ffff8800bb58c480 > RBP: ffff8800bac3fd48 R08: 0000000000000001 R09: 0000000000000000 > R10: 0000000000001ca1 R11: 0000000000001c9d R12: 0000000000000000 > R13: ffff8800ba713800 R14: ffff8800bac3fda0 R15: ffff8800bb77ec00 > FS: 00007f3c0cd9b7e0(0000) GS:ffff8800bfb00000(0000) knlGS:0000000000000000 > CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 > CR2: 0000000000000010 CR3: 00000000bb79d000 CR4: 00000000000006e0 > Stack: > ffff8800bb77ec00 0000000000000000 ffff8800bac3fd88 ffffffff811fbf85 > ffff8800bac3fd98 ffff8800bb77f080 ffff8800ba713800 ffff8800bb262b40 > 0000000000000000 0000000000000000 ffff8800bac3fdd8 ffffffff811f1da0 > Call Trace: > [<ffffffff811fbf85>] propagate_mnt+0x105/0x140 > [<ffffffff811f1da0>] attach_recursive_mnt+0x120/0x1e0 > [<ffffffff811f1ec3>] graft_tree+0x63/0x70 > [<ffffffff811f1f6b>] do_add_mount+0x9b/0x100 > [<ffffffff811f2c1a>] do_mount+0x2aa/0xdf0 > [<ffffffff8117efbe>] ? strndup_user+0x4e/0x70 > [<ffffffff811f3a45>] SyS_mount+0x75/0xc0 > [<ffffffff8100242b>] do_syscall_64+0x4b/0xa0 > [<ffffffff81988f3c>] entry_SYSCALL64_slow_path+0x25/0x25 > Code: 00 00 75 ec 48 89 0d 02 22 22 01 8b 89 10 01 00 00 48 89 05 fd 21 22 01 39 8e 10 01 00 00 0f 84 e0 00 00 00 48 8b 80 d8 00 00 00 <48> 8b 50 10 48 89 05 df 21 22 01 48 89 15 d0 21 22 01 8b 53 30 > RIP [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0 > RSP <ffff8800bac3fd38> > CR2: 0000000000000010 > ---[ end trace 2725ecd95164f217 ]--- This oops happens with the namespace_sem held and can be triggered by non-root users. An all around not pleasant experience. To avoid this scenario when finding the appropriate source mount to copy stop the walk up the mnt_master chain when the first source mount is encountered. Further rewrite the walk up the last_source mnt_master chain so that it is clear what is going on. The reason why the first source mount is special is that it it's mnt_parent is not a mount in the dest_mnt propagation tree, and as such termination conditions based up on the dest_mnt mount propgation tree do not make sense. To avoid other kinds of confusion last_dest is not changed when computing last_source. last_dest is only used once in propagate_one and that is above the point of the code being modified, so changing the global variable is meaningless and confusing. Cc: [email protected] fixes: f2ebb3a921c1ca1e2ddd9242e95a1989a50c4c68 ("smarter propagate_mnt()") Reported-by: Tycho Andersen <[email protected]> Reviewed-by: Seth Forshee <[email protected]> Tested-by: Seth Forshee <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID:
int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp, struct mount *source_mnt, struct hlist_head *tree_list) { struct mount *m, *n; int ret = 0; /* * we don't want to bother passing tons of arguments to * propagate_one(); everything is serialized by namespace_sem, * so globals will do just fine. */ user_ns = current->nsproxy->mnt_ns->user_ns; last_dest = dest_mnt; first_source = source_mnt; last_source = source_mnt; mp = dest_mp; list = tree_list; dest_master = dest_mnt->mnt_master; /* all peers of dest_mnt, except dest_mnt itself */ for (n = next_peer(dest_mnt); n != dest_mnt; n = next_peer(n)) { ret = propagate_one(n); if (ret) goto out; } /* all slave groups */ for (m = next_group(dest_mnt, dest_mnt); m; m = next_group(m, dest_mnt)) { /* everything in that slave group */ n = m; do { ret = propagate_one(n); if (ret) goto out; n = next_peer(n); } while (n != m); } out: read_seqlock_excl(&mount_lock); hlist_for_each_entry(n, tree_list, mnt_hash) { m = n->mnt_parent; if (m->mnt_master != dest_mnt->mnt_master) CLEAR_MNT_MARK(m->mnt_master); } read_sequnlock_excl(&mount_lock); return ret; }
167,233
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); }
167,030
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; if (insn_bitness == 32) { /* Relevant for 32-bit RSH: Information can propagate towards * LSB, so it isn't sufficient to only truncate the output to * 32 bits. */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (!src_known && opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { __mark_reg_unknown(dst_reg); return 0; } switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_ARSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* Upon reaching here, src_known is true and * umax_val is equal to umin_val. */ dst_reg->smin_value >>= umin_val; dst_reg->smax_value >>= umin_val; dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); /* blow away the dst_reg umin_value/umax_value and rely on * dst_reg var_off to refine the result. */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") took care of rejecting alu op on pointer when e.g. pointer came from two different map values with different map properties such as value size, Jann reported that a case was not covered yet when a given alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from different branches where we would incorrectly try to sanitize based on the pointer's limit. Catch this corner case and reject the program instead. Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> CWE ID: CWE-189
static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; u32 dst = insn->dst_reg; int ret; if (insn_bitness == 32) { /* Relevant for 32-bit RSH: Information can propagate towards * LSB, so it isn't sufficient to only truncate the output to * 32 bits. */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (!src_known && opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { __mark_reg_unknown(dst_reg); return 0; } switch (opcode) { case BPF_ADD: ret = sanitize_val_alu(env, insn); if (ret < 0) { verbose(env, "R%d tried to add from different pointers or scalars\n", dst); return ret; } if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: ret = sanitize_val_alu(env, insn); if (ret < 0) { verbose(env, "R%d tried to sub from different pointers or scalars\n", dst); return ret; } if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_ARSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* Upon reaching here, src_known is true and * umax_val is equal to umin_val. */ dst_reg->smin_value >>= umin_val; dst_reg->smax_value >>= umin_val; dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); /* blow away the dst_reg umin_value/umax_value and rely on * dst_reg var_off to refine the result. */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; }
169,730
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void mptsas_fetch_request(MPTSASState *s) { PCIDevice *pci = (PCIDevice *) s; char req[MPTSAS_MAX_REQUEST_SIZE]; MPIRequestHeader *hdr = (MPIRequestHeader *)req; hwaddr addr; int size; if (s->state != MPI_IOC_STATE_OPERATIONAL) { mptsas_set_fault(s, MPI_IOCSTATUS_INVALID_STATE); return; } /* Read the message header from the guest first. */ addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post); pci_dma_read(pci, addr, req, sizeof(hdr)); } Commit Message: CWE ID: CWE-20
static void mptsas_fetch_request(MPTSASState *s) { PCIDevice *pci = (PCIDevice *) s; char req[MPTSAS_MAX_REQUEST_SIZE]; MPIRequestHeader *hdr = (MPIRequestHeader *)req; hwaddr addr; int size; /* Read the message header from the guest first. */ addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post); pci_dma_read(pci, addr, req, sizeof(hdr)); }
165,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep)) { return (-1); } n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); } Commit Message: CVE-2017-13014/White Board: Do more bounds checks. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). While we're at it, print a truncation error if the packets are truncated, rather than just, in effect, ignoring the result of the routines that print particular packet types. CWE ID: CWE-125
wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep) || !ND_TTEST(*prep)) return (-1); n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); }
167,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_init_cpu(int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); mutex_lock(&swhash->hlist_mutex); swhash->online = true; if (swhash->hlist_refcount > 0) { struct swevent_hlist *hlist; hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); WARN_ON(!hlist); rcu_assign_pointer(swhash->swevent_hlist, hlist); } mutex_unlock(&swhash->hlist_mutex); } Commit Message: perf: Fix race in swevent hash There's a race on CPU unplug where we free the swevent hash array while it can still have events on. This will result in a use-after-free which is BAD. Simply do not free the hash array on unplug. This leaves the thing around and no use-after-free takes place. When the last swevent dies, we do a for_each_possible_cpu() iteration anyway to clean these up, at which time we'll free it, so no leakage will occur. Reported-by: Sasha Levin <[email protected]> Tested-by: Sasha Levin <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-416
static void perf_event_init_cpu(int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); mutex_lock(&swhash->hlist_mutex); if (swhash->hlist_refcount > 0) { struct swevent_hlist *hlist; hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); WARN_ON(!hlist); rcu_assign_pointer(swhash->swevent_hlist, hlist); } mutex_unlock(&swhash->hlist_mutex); }
167,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) { DTLS1_RECORD_DATA *rdata; pitem *item; /* Limit the size of the queue to prevent DOS attacks */ if (pqueue_size(queue->q) >= 100) return 0; rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA)); item = pitem_new(priority, rdata); if (rdata == NULL || item == NULL) { if (rdata != NULL) OPENSSL_free(rdata); if (item != NULL) pitem_free(item); SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); return(0); } rdata->packet = s->packet; rdata->packet_length = s->packet_length; memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER)); memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD)); item->data = rdata; #ifndef OPENSSL_NO_SCTP /* Store bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) { BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif s->packet = NULL; s->packet_length = 0; memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER)); memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD)); if (!ssl3_setup_buffers(s)) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); OPENSSL_free(rdata); pitem_free(item); return(0); } /* insert should not fail, since duplicates are dropped */ if (pqueue_insert(queue->q, item) == NULL) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); OPENSSL_free(rdata); pitem_free(item); return(0); } return(1); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <[email protected]> CWE ID: CWE-119
dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) { DTLS1_RECORD_DATA *rdata; pitem *item; /* Limit the size of the queue to prevent DOS attacks */ if (pqueue_size(queue->q) >= 100) return 0; rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA)); item = pitem_new(priority, rdata); if (rdata == NULL || item == NULL) { if (rdata != NULL) OPENSSL_free(rdata); if (item != NULL) pitem_free(item); SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); return(0); } rdata->packet = s->packet; rdata->packet_length = s->packet_length; memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER)); memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD)); item->data = rdata; #ifndef OPENSSL_NO_SCTP /* Store bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) { BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif s->packet = NULL; s->packet_length = 0; memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER)); memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD)); if (!ssl3_setup_buffers(s)) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); if (rdata->rbuf.buf != NULL) OPENSSL_free(rdata->rbuf.buf); OPENSSL_free(rdata); pitem_free(item); return(-1); } /* insert should not fail, since duplicates are dropped */ if (pqueue_insert(queue->q, item) == NULL) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); if (rdata->rbuf.buf != NULL) OPENSSL_free(rdata->rbuf.buf); OPENSSL_free(rdata); pitem_free(item); return(-1); } return(1); }
166,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dotraplinkage void do_stack_segment(struct pt_regs *regs, long error_code) { enum ctx_state prev_state; prev_state = exception_enter(); if (notify_die(DIE_TRAP, "stack segment", regs, error_code, X86_TRAP_SS, SIGBUS) != NOTIFY_STOP) { preempt_conditional_sti(regs); do_trap(X86_TRAP_SS, SIGBUS, "stack segment", regs, error_code, NULL); preempt_conditional_cli(regs); } exception_exit(prev_state); } Commit Message: x86_64, traps: Stop using IST for #SS On a 32-bit kernel, this has no effect, since there are no IST stacks. On a 64-bit kernel, #SS can only happen in user code, on a failed iret to user space, a canonical violation on access via RSP or RBP, or a genuine stack segment violation in 32-bit kernel code. The first two cases don't need IST, and the latter two cases are unlikely fatal bugs, and promoting them to double faults would be fine. This fixes a bug in which the espfix64 code mishandles a stack segment violation. This saves 4k of memory per CPU and a tiny bit of code. Signed-off-by: Andy Lutomirski <[email protected]> Reviewed-by: Thomas Gleixner <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
dotraplinkage void do_stack_segment(struct pt_regs *regs, long error_code)
166,238
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: VP8XChunk::VP8XChunk(Container* parent) : Chunk(parent, kChunk_VP8X) { this->needsRewrite = true; this->size = 10; this->data.resize(this->size); this->data.assign(this->size, 0); XMP_Uns8* bitstream = (XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data(); XMP_Uns32 width = ((bitstream[7] << 8) | bitstream[6]) & 0x3fff; XMP_Uns32 height = ((bitstream[9] << 8) | bitstream[8]) & 0x3fff; this->width(width); this->height(height); parent->vp8x = this; VP8XChunk::VP8XChunk(Container* parent, WEBP_MetaHandler* handler) : Chunk(parent, handler) { this->size = 10; this->needsRewrite = true; parent->vp8x = this; } XMP_Uns32 VP8XChunk::width() { return GetLE24(&this->data[4]) + 1; } void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); } XMP_Uns32 VP8XChunk::height() { return GetLE24(&this->data[7]) + 1; } void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); } bool VP8XChunk::xmp() { XMP_Uns32 flags = GetLE32(&this->data[0]); return (bool)((flags >> XMP_FLAG_BIT) & 1); } void VP8XChunk::xmp(bool hasXMP) { XMP_Uns32 flags = GetLE32(&this->data[0]); flags ^= (-hasXMP ^ flags) & (1 << XMP_FLAG_BIT); PutLE32(&this->data[0], flags); } Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler) { this->needsRewrite = false; XMP_IO* file = handler->parent->ioRef; file->Seek(12, kXMP_SeekFromStart); XMP_Int64 size = handler->initialFileSize; XMP_Uns32 peek = 0; while (file->Offset() < size) { peek = XIO::PeekUns32_LE(file); switch (peek) { case kChunk_XMP_: this->addChunk(new XMPChunk(this, handler)); break; case kChunk_VP8X: this->addChunk(new VP8XChunk(this, handler)); break; default: this->addChunk(new Chunk(this, handler)); break; } } if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) { XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat); } if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) { this->needsRewrite = true; this->addChunk(new VP8XChunk(this)); } if (this->chunks[WEBP_CHUNK_XMP].size() == 0) { XMPChunk* xmpChunk = new XMPChunk(this); this->addChunk(xmpChunk); handler->xmpChunk = xmpChunk; this->vp8x->xmp(true); } } Chunk* Container::getExifChunk() { if (this->chunks[WEBP::WEBP_CHUNK_EXIF].size() == 0) { return NULL; } return this->chunks[WEBP::WEBP_CHUNK_EXIF][0]; } void Container::addChunk(Chunk* chunk) { ChunkId idx; try { idx = chunkMap.at(chunk->tag); } catch (const std::out_of_range& e) { idx = WEBP_CHUNK_UNKNOWN; } this->chunks[idx].push_back(chunk); } void Container::write(WEBP_MetaHandler* handler) { XMP_IO* file = handler->parent->ioRef; file->Rewind(); XIO::WriteUns32_LE(file, this->tag); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); XIO::WriteUns32_LE(file, kChunk_WEBP); size_t i, j; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; for (j = 0; j < chunkVect.size(); j++) { chunkVect.at(j)->write(handler); } } XMP_Int64 lastOffset = file->Offset(); this->size = lastOffset - 8; file->Seek(this->pos + 4, kXMP_SeekFromStart); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); file->Seek(lastOffset, kXMP_SeekFromStart); if (lastOffset < handler->initialFileSize) { file->Truncate(lastOffset); } } Container::~Container() { Chunk* chunk; size_t i; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; while (!chunkVect.empty()) { chunk = chunkVect.back(); delete chunk; chunkVect.pop_back(); } } } } Commit Message: CWE ID: CWE-476
VP8XChunk::VP8XChunk(Container* parent) : Chunk(parent, kChunk_VP8X) { this->needsRewrite = true; this->size = 10; this->data.resize(this->size); this->data.assign(this->size, 0); XMP_Uns8* bitstream = (XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data(); // See bug https://bugs.freedesktop.org/show_bug.cgi?id=105247 // bitstream could be NULL. XMP_Uns32 width = bitstream ? ((bitstream[7] << 8) | bitstream[6]) & 0x3fff : 0; XMP_Uns32 height = bitstream ? ((bitstream[9] << 8) | bitstream[8]) & 0x3fff : 0; this->width(width); this->height(height); parent->vp8x = this; VP8XChunk::VP8XChunk(Container* parent, WEBP_MetaHandler* handler) : Chunk(parent, handler) { this->size = 10; this->needsRewrite = true; parent->vp8x = this; } XMP_Uns32 VP8XChunk::width() { return GetLE24(&this->data[4]) + 1; } void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); } XMP_Uns32 VP8XChunk::height() { return GetLE24(&this->data[7]) + 1; } void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); } bool VP8XChunk::xmp() { XMP_Uns32 flags = GetLE32(&this->data[0]); return (bool)((flags >> XMP_FLAG_BIT) & 1); } void VP8XChunk::xmp(bool hasXMP) { XMP_Uns32 flags = GetLE32(&this->data[0]); flags ^= (-hasXMP ^ flags) & (1 << XMP_FLAG_BIT); PutLE32(&this->data[0], flags); } Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler) { this->needsRewrite = false; XMP_IO* file = handler->parent->ioRef; file->Seek(12, kXMP_SeekFromStart); XMP_Int64 size = handler->initialFileSize; XMP_Uns32 peek = 0; while (file->Offset() < size) { peek = XIO::PeekUns32_LE(file); switch (peek) { case kChunk_XMP_: this->addChunk(new XMPChunk(this, handler)); break; case kChunk_VP8X: this->addChunk(new VP8XChunk(this, handler)); break; default: this->addChunk(new Chunk(this, handler)); break; } } if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) { XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat); } if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) { this->needsRewrite = true; this->addChunk(new VP8XChunk(this)); } if (this->chunks[WEBP_CHUNK_XMP].size() == 0) { XMPChunk* xmpChunk = new XMPChunk(this); this->addChunk(xmpChunk); handler->xmpChunk = xmpChunk; this->vp8x->xmp(true); } } Chunk* Container::getExifChunk() { if (this->chunks[WEBP::WEBP_CHUNK_EXIF].size() == 0) { return NULL; } return this->chunks[WEBP::WEBP_CHUNK_EXIF][0]; } void Container::addChunk(Chunk* chunk) { ChunkId idx; try { idx = chunkMap.at(chunk->tag); } catch (const std::out_of_range& e) { idx = WEBP_CHUNK_UNKNOWN; } this->chunks[idx].push_back(chunk); } void Container::write(WEBP_MetaHandler* handler) { XMP_IO* file = handler->parent->ioRef; file->Rewind(); XIO::WriteUns32_LE(file, this->tag); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); XIO::WriteUns32_LE(file, kChunk_WEBP); size_t i, j; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; for (j = 0; j < chunkVect.size(); j++) { chunkVect.at(j)->write(handler); } } XMP_Int64 lastOffset = file->Offset(); this->size = lastOffset - 8; file->Seek(this->pos + 4, kXMP_SeekFromStart); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); file->Seek(lastOffset, kXMP_SeekFromStart); if (lastOffset < handler->initialFileSize) { file->Truncate(lastOffset); } } Container::~Container() { Chunk* chunk; size_t i; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; while (!chunkVect.empty()) { chunk = chunkVect.back(); delete chunk; chunkVect.pop_back(); } } } }
164,993
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { #ifdef sgi char tmpline[80]; #endif char *p; int rc, alen, flen; int error = 0; int have_bg = FALSE; double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ XEvent e; KeySym k; displayname = (char *)NULL; filename = (char *)NULL; /* First set the default value for our display-system exponent, i.e., * the product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. This is not an * exhaustive list of LUT values (e.g., OpenStep has a lot of weird * ones), but it should cover 99% of the current possibilities. */ #if defined(NeXT) LUT_exponent = 1.0 / 2.2; /* if (some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to get the * "gamma" value, so we do it the hard way */ infile = fopen("/etc/config/system.glGammaVal", "r"); if (infile) { double sgi_gamma; fgets(tmpline, 80, infile); fclose(infile); sgi_gamma = atof(tmpline); if (sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if (some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ if ((p = getenv("SCREEN_GAMMA")) != NULL) display_exponent = atof(p); else display_exponent = default_display_exponent; /* Now parse the command line for options and the PNG filename. */ while (*++argv && !error) { if (!strncmp(*argv, "-display", 2)) { if (!*++argv) ++error; else displayname = *argv; } else if (!strncmp(*argv, "-gamma", 2)) { if (!*++argv) ++error; else { display_exponent = atof(*argv); if (display_exponent <= 0.0) ++error; } } else if (!strncmp(*argv, "-bgcolor", 2)) { if (!*++argv) ++error; else { bgstr = *argv; if (strlen(bgstr) != 7 || bgstr[0] != '#') ++error; else have_bg = TRUE; } } else { if (**argv != '-') { filename = *argv; if (argv[1]) /* shouldn't be any more args after filename */ ++error; } else ++error; /* not expecting any other options */ } } if (!filename) ++error; /* print usage screen if any errors up to this point */ if (error) { fprintf(stderr, "\n%s %s: %s\n", PROGNAME, VERSION, appname); readpng_version_info(); fprintf(stderr, "\n" "Usage: %s [-display xdpy] [-gamma exp] [-bgcolor bg] file.png\n" " xdpy\tname of the target X display (e.g., ``hostname:0'')\n" " exp \ttransfer-function exponent (``gamma'') of the display\n" "\t\t system in floating-point format (e.g., ``%.1f''); equal\n" "\t\t to the product of the lookup-table exponent (varies)\n" "\t\t and the CRT exponent (usually 2.2); must be positive\n" " bg \tdesired background color in 7-character hex RGB format\n" "\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n" "\t\t used with transparent images\n" "\nPress Q, Esc or mouse button 1 (within image window, after image\n" "is displayed) to quit.\n" "\n", PROGNAME, default_display_exponent); exit(1); } if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename); ++error; } else { if ((rc = readpng_init(infile, &image_width, &image_height)) != 0) { switch (rc) { case 1: fprintf(stderr, PROGNAME ": [%s] is not a PNG file: incorrect signature\n", filename); break; case 2: fprintf(stderr, PROGNAME ": [%s] has bad IHDR (libpng longjmp)\n", filename); break; case 4: fprintf(stderr, PROGNAME ": insufficient memory\n"); break; default: fprintf(stderr, PROGNAME ": unknown readpng_init() error\n"); break; } ++error; } else { display = XOpenDisplay(displayname); if (!display) { readpng_cleanup(TRUE); fprintf(stderr, PROGNAME ": can't open X display [%s]\n", displayname? displayname : "default"); ++error; } } if (error) fclose(infile); } if (error) { fprintf(stderr, PROGNAME ": aborting.\n"); exit(2); } /* set the title-bar string, but make sure buffer doesn't overflow */ alen = strlen(appname); flen = strlen(filename); if (alen + flen + 3 > 1023) sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023)); else sprintf(titlebar, "%s: %s", appname, filename); /* if the user didn't specify a background color on the command line, * check for one in the PNG file--if not, the initialized values of 0 * (black) will be used */ if (have_bg) { unsigned r, g, b; /* this approach quiets compiler warnings */ sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b); bg_red = (uch)r; bg_green = (uch)g; bg_blue = (uch)b; } else if (readpng_get_bgcolor(&bg_red, &bg_green, &bg_blue) > 1) { readpng_cleanup(TRUE); fprintf(stderr, PROGNAME ": libpng error while checking for background color\n"); exit(2); } /* do the basic X initialization stuff, make the window and fill it * with the background color */ if (rpng_x_create_window()) exit(2); /* decode the image, all at once */ Trace((stderr, "calling readpng_get_image()\n")) image_data = readpng_get_image(display_exponent, &image_channels, &image_rowbytes); Trace((stderr, "done with readpng_get_image()\n")) /* done with PNG file, so clean up to minimize memory usage (but do NOT * nuke image_data!) */ readpng_cleanup(FALSE); fclose(infile); if (!image_data) { fprintf(stderr, PROGNAME ": unable to decode PNG image\n"); exit(3); } /* display image (composite with background if requested) */ Trace((stderr, "calling rpng_x_display_image()\n")) if (rpng_x_display_image()) { free(image_data); exit(4); } Trace((stderr, "done with rpng_x_display_image()\n")) /* wait for the user to tell us when to quit */ printf( "Done. Press Q, Esc or mouse button 1 (within image window) to quit.\n"); fflush(stdout); do XNextEvent(display, &e); while (!(e.type == ButtonPress && e.xbutton.button == Button1) && !(e.type == KeyPress && /* v--- or 1 for shifted keys */ ((k = XLookupKeysym(&e.xkey, 0)) == XK_q || k == XK_Escape) )); /* OK, we're done: clean up all image and X resources and go away */ rpng_x_cleanup(); return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
int main(int argc, char **argv) { #ifdef sgi char tmpline[80]; #endif char *p; int rc, alen, flen; int error = 0; int have_bg = FALSE; double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ XEvent e; KeySym k; displayname = (char *)NULL; filename = (char *)NULL; /* First set the default value for our display-system exponent, i.e., * the product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. This is not an * exhaustive list of LUT values (e.g., OpenStep has a lot of weird * ones), but it should cover 99% of the current possibilities. */ #if defined(NeXT) LUT_exponent = 1.0 / 2.2; /* if (some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to get the * "gamma" value, so we do it the hard way */ infile = fopen("/etc/config/system.glGammaVal", "r"); if (infile) { double sgi_gamma; fgets(tmpline, 80, infile); fclose(infile); sgi_gamma = atof(tmpline); if (sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if (some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ if ((p = getenv("SCREEN_GAMMA")) != NULL) display_exponent = atof(p); else display_exponent = default_display_exponent; /* Now parse the command line for options and the PNG filename. */ while (*++argv && !error) { if (!strncmp(*argv, "-display", 2)) { if (!*++argv) ++error; else displayname = *argv; } else if (!strncmp(*argv, "-gamma", 2)) { if (!*++argv) ++error; else { display_exponent = atof(*argv); if (display_exponent <= 0.0) ++error; } } else if (!strncmp(*argv, "-bgcolor", 2)) { if (!*++argv) ++error; else { bgstr = *argv; if (strlen(bgstr) != 7 || bgstr[0] != '#') ++error; else have_bg = TRUE; } } else { if (**argv != '-') { filename = *argv; if (argv[1]) /* shouldn't be any more args after filename */ ++error; } else ++error; /* not expecting any other options */ } } if (!filename) ++error; /* print usage screen if any errors up to this point */ if (error) { fprintf(stderr, "\n%s %s: %s\n", PROGNAME, VERSION, appname); readpng_version_info(); fprintf(stderr, "\n" "Usage: %s [-display xdpy] [-gamma exp] [-bgcolor bg] file.png\n" " xdpy\tname of the target X display (e.g., ``hostname:0'')\n" " exp \ttransfer-function exponent (``gamma'') of the display\n" "\t\t system in floating-point format (e.g., ``%.1f''); equal\n", PROGNAME, default_display_exponent); fprintf(stderr, "\n" "\t\t to the product of the lookup-table exponent (varies)\n" "\t\t and the CRT exponent (usually 2.2); must be positive\n" " bg \tdesired background color in 7-character hex RGB format\n" "\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n" "\t\t used with transparent images\n" "\nPress Q, Esc or mouse button 1 (within image window, after image\n" "is displayed) to quit.\n"); exit(1); } if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename); ++error; } else { if ((rc = readpng_init(infile, &image_width, &image_height)) != 0) { switch (rc) { case 1: fprintf(stderr, PROGNAME ": [%s] is not a PNG file: incorrect signature\n", filename); break; case 2: fprintf(stderr, PROGNAME ": [%s] has bad IHDR (libpng longjmp)\n", filename); break; case 4: fprintf(stderr, PROGNAME ": insufficient memory\n"); break; default: fprintf(stderr, PROGNAME ": unknown readpng_init() error\n"); break; } ++error; } else { display = XOpenDisplay(displayname); if (!display) { readpng_cleanup(TRUE); fprintf(stderr, PROGNAME ": can't open X display [%s]\n", displayname? displayname : "default"); ++error; } } if (error) fclose(infile); } if (error) { fprintf(stderr, PROGNAME ": aborting.\n"); exit(2); } /* set the title-bar string, but make sure buffer doesn't overflow */ alen = strlen(appname); flen = strlen(filename); if (alen + flen + 3 > 1023) sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023)); else sprintf(titlebar, "%s: %s", appname, filename); /* if the user didn't specify a background color on the command line, * check for one in the PNG file--if not, the initialized values of 0 * (black) will be used */ if (have_bg) { unsigned r, g, b; /* this approach quiets compiler warnings */ sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b); bg_red = (uch)r; bg_green = (uch)g; bg_blue = (uch)b; } else if (readpng_get_bgcolor(&bg_red, &bg_green, &bg_blue) > 1) { readpng_cleanup(TRUE); fprintf(stderr, PROGNAME ": libpng error while checking for background color\n"); exit(2); } /* do the basic X initialization stuff, make the window and fill it * with the background color */ if (rpng_x_create_window()) exit(2); /* decode the image, all at once */ Trace((stderr, "calling readpng_get_image()\n")) image_data = readpng_get_image(display_exponent, &image_channels, &image_rowbytes); Trace((stderr, "done with readpng_get_image()\n")) /* done with PNG file, so clean up to minimize memory usage (but do NOT * nuke image_data!) */ readpng_cleanup(FALSE); fclose(infile); if (!image_data) { fprintf(stderr, PROGNAME ": unable to decode PNG image\n"); exit(3); } /* display image (composite with background if requested) */ Trace((stderr, "calling rpng_x_display_image()\n")) if (rpng_x_display_image()) { free(image_data); exit(4); } Trace((stderr, "done with rpng_x_display_image()\n")) /* wait for the user to tell us when to quit */ printf( "Done. Press Q, Esc or mouse button 1 (within image window) to quit.\n"); fflush(stdout); do XNextEvent(display, &e); while (!(e.type == ButtonPress && e.xbutton.button == Button1) && !(e.type == KeyPress && /* v--- or 1 for shifted keys */ ((k = XLookupKeysym(&e.xkey, 0)) == XK_q || k == XK_Escape) )); /* OK, we're done: clean up all image and X resources and go away */ rpng_x_cleanup(); (void)argc; /* Unused */ return 0; }
173,573
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::~Chapters() { while (m_editions_count > 0) { Edition& e = m_editions[--m_editions_count]; e.Clear(); } } 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
Chapters::~Chapters()
174,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionsGuestViewMessageFilter::~ExtensionsGuestViewMessageFilter() { DCHECK_CURRENTLY_ON(BrowserThread::IO); (*GetProcessIdToFilterMap())[render_process_id_] = nullptr; base::PostTaskWithTraits( FROM_HERE, BrowserThread::UI, base::BindOnce(RemoveProcessIdFromGlobalMap, render_process_id_)); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362
ExtensionsGuestViewMessageFilter::~ExtensionsGuestViewMessageFilter() { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
173,051
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_venc::set_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_IN OMX_PTR paramData) { (void)hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: Set Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_ERROR("ERROR: Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } /*set_parameter can be called in loaded state or disabled port */ if (m_state == OMX_StateLoaded || m_sInPortDef.bEnabled == OMX_FALSE || m_sOutPortDef.bEnabled == OMX_FALSE) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } switch ((int)paramIndex) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *portDefn; portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d", (int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nFrameWidth); if (PORT_INDEX_IN == portDefn->nPortIndex) { if (!dev_is_video_session_supported(portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight)) { DEBUG_PRINT_ERROR("video session not supported"); omx_report_unsupported_setting(); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("i/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual); DEBUG_PRINT_LOW("i/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin); DEBUG_PRINT_LOW("i/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize); if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: (In_PORT) Min buffers (%u) > actual count (%u)", (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed"); return handle->hw_overload ? OMX_ErrorInsufficientResources : OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("i/p previous actual cnt = %u", (unsigned int)m_sInPortDef.nBufferCountActual); DEBUG_PRINT_LOW("i/p previous min cnt = %u", (unsigned int)m_sInPortDef.nBufferCountMin); memcpy(&m_sInPortDef, portDefn,sizeof(OMX_PARAM_PORTDEFINITIONTYPE)); #ifdef _ANDROID_ICS_ if (portDefn->format.video.eColorFormat == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) { m_sInPortDef.format.video.eColorFormat = (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; if (!mUseProxyColorFormat) { if (!c2d_conv.init()) { DEBUG_PRINT_ERROR("C2D init failed"); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_HIGH("C2D init is successful"); } mUseProxyColorFormat = true; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ; } else mUseProxyColorFormat = false; #endif /*Query Input Buffer Requirements*/ dev_get_buf_req (&m_sInPortDef.nBufferCountMin, &m_sInPortDef.nBufferCountActual, &m_sInPortDef.nBufferSize, m_sInPortDef.nPortIndex); /*Query ouput Buffer Requirements*/ dev_get_buf_req (&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); m_sInPortDef.nBufferCountActual = portDefn->nBufferCountActual; } else if (PORT_INDEX_OUT == portDefn->nPortIndex) { DEBUG_PRINT_LOW("o/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual); DEBUG_PRINT_LOW("o/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin); DEBUG_PRINT_LOW("o/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize); if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: (Out_PORT) Min buffers (%u) > actual count (%u)", (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param output failed"); return OMX_ErrorUnsupportedSetting; } #ifdef _MSM8974_ /*Query ouput Buffer Requirements*/ dev_get_buf_req(&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); #endif memcpy(&m_sOutPortDef,portDefn,sizeof(struct OMX_PARAM_PORTDEFINITIONTYPE)); update_profile_level(); //framerate , bitrate DEBUG_PRINT_LOW("o/p previous actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); DEBUG_PRINT_LOW("o/p previous min cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountMin); m_sOutPortDef.nBufferCountActual = portDefn->nBufferCountActual; } else { DEBUG_PRINT_ERROR("ERROR: Set_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } m_sConfigFramerate.xEncodeFramerate = portDefn->format.video.xFramerate; m_sConfigBitrate.nEncodeBitrate = portDefn->format.video.nBitrate; m_sParamBitrate.nTargetBitrate = portDefn->format.video.nBitrate; } break; case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d", portFmt->eColorFormat); if (PORT_INDEX_IN == portFmt->nPortIndex) { if (handle->venc_set_param(paramData,OMX_IndexParamVideoPortFormat) != true) { return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d", portFmt->eColorFormat); update_profile_level(); //framerate #ifdef _ANDROID_ICS_ if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) { m_sInPortFormat.eColorFormat = (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; if (!mUseProxyColorFormat) { if (!c2d_conv.init()) { DEBUG_PRINT_ERROR("C2D init failed"); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_HIGH("C2D init is successful"); } mUseProxyColorFormat = true; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ; } else #endif { m_sInPortFormat.eColorFormat = portFmt->eColorFormat; m_sInPortDef.format.video.eColorFormat = portFmt->eColorFormat; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB; mUseProxyColorFormat = false; } m_sInPortFormat.xFramerate = portFmt->xFramerate; } } break; case OMX_IndexParamVideoInit: { //TODO, do we need this index set param OMX_PORT_PARAM_TYPE* pParam = (OMX_PORT_PARAM_TYPE*)(paramData); DEBUG_PRINT_LOW("Set OMX_IndexParamVideoInit called"); break; } case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE* pParam = (OMX_VIDEO_PARAM_BITRATETYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoBitrate"); if (handle->venc_set_param(paramData,OMX_IndexParamVideoBitrate) != true) { return OMX_ErrorUnsupportedSetting; } m_sParamBitrate.nTargetBitrate = pParam->nTargetBitrate; m_sParamBitrate.eControlRate = pParam->eControlRate; update_profile_level(); //bitrate m_sConfigBitrate.nEncodeBitrate = pParam->nTargetBitrate; m_sInPortDef.format.video.nBitrate = pParam->nTargetBitrate; m_sOutPortDef.format.video.nBitrate = pParam->nTargetBitrate; DEBUG_PRINT_LOW("bitrate = %u", (unsigned int)m_sOutPortDef.format.video.nBitrate); break; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE* pParam = (OMX_VIDEO_PARAM_MPEG4TYPE*)paramData; OMX_VIDEO_PARAM_MPEG4TYPE mp4_param; memcpy(&mp4_param, pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE)); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4"); if (pParam->eProfile == OMX_VIDEO_MPEG4ProfileAdvancedSimple) { #ifdef MAX_RES_1080P if (pParam->nBFrames) { DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported"); mp4_param.nBFrames = 1; } #else if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); mp4_param.nBFrames = 0; } #endif #ifdef _MSM8974_ if (pParam->nBFrames || bframes) mp4_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes; DEBUG_PRINT_HIGH("MPEG4: %u BFrames are being set", (unsigned int)mp4_param.nBFrames); #endif } else { if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); mp4_param.nBFrames = 0; } } if (handle->venc_set_param(&mp4_param,OMX_IndexParamVideoMpeg4) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamMPEG4,pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE)); m_sIntraperiod.nPFrames = m_sParamMPEG4.nPFrames; if (pParam->nBFrames || bframes) m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames = mp4_param.nBFrames; else m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames; break; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE* pParam = (OMX_VIDEO_PARAM_H263TYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263"); if (handle->venc_set_param(paramData,OMX_IndexParamVideoH263) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamH263,pParam, sizeof(struct OMX_VIDEO_PARAM_H263TYPE)); m_sIntraperiod.nPFrames = m_sParamH263.nPFrames; m_sIntraperiod.nBFrames = m_sParamH263.nBFrames; break; } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE* pParam = (OMX_VIDEO_PARAM_AVCTYPE*)paramData; OMX_VIDEO_PARAM_AVCTYPE avc_param; memcpy(&avc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_AVCTYPE)); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc"); if ((pParam->eProfile == OMX_VIDEO_AVCProfileHigh)|| (pParam->eProfile == OMX_VIDEO_AVCProfileMain)) { #ifdef MAX_RES_1080P if (pParam->nBFrames) { DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported"); avc_param.nBFrames = 1; } if (pParam->nRefFrames != 2) { DEBUG_PRINT_ERROR("Warning: 2 RefFrames are needed, changing RefFrames from %u to 2", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 2; } #else if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); avc_param.nBFrames = 0; } if (pParam->nRefFrames != 1) { DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 1; } #endif #ifdef _MSM8974_ if (pParam->nBFrames || bframes) { avc_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes; avc_param.nRefFrames = (avc_param.nBFrames < 4)? avc_param.nBFrames + 1 : 4; } DEBUG_PRINT_HIGH("AVC: RefFrames: %u, BFrames: %u", (unsigned int)avc_param.nRefFrames, (unsigned int)avc_param.nBFrames); avc_param.bEntropyCodingCABAC = (OMX_BOOL)(avc_param.bEntropyCodingCABAC && entropy); avc_param.nCabacInitIdc = entropy ? avc_param.nCabacInitIdc : 0; #endif } else { if (pParam->nRefFrames != 1) { DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 1; } if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); avc_param.nBFrames = 0; } } if (handle->venc_set_param(&avc_param,OMX_IndexParamVideoAvc) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamAVC,pParam, sizeof(struct OMX_VIDEO_PARAM_AVCTYPE)); m_sIntraperiod.nPFrames = m_sParamAVC.nPFrames; if (pParam->nBFrames || bframes) m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames = avc_param.nBFrames; else m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames; break; } case (OMX_INDEXTYPE)OMX_IndexParamVideoVp8: { OMX_VIDEO_PARAM_VP8TYPE* pParam = (OMX_VIDEO_PARAM_VP8TYPE*)paramData; OMX_VIDEO_PARAM_VP8TYPE vp8_param; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoVp8"); if (pParam->nDCTPartitions != m_sParamVP8.nDCTPartitions || pParam->bErrorResilientMode != m_sParamVP8.bErrorResilientMode) { DEBUG_PRINT_ERROR("VP8 doesn't support nDCTPartitions or bErrorResilientMode"); } memcpy(&vp8_param, pParam, sizeof( struct OMX_VIDEO_PARAM_VP8TYPE)); if (handle->venc_set_param(&vp8_param, (OMX_INDEXTYPE)OMX_IndexParamVideoVp8) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamVP8,pParam, sizeof(struct OMX_VIDEO_PARAM_VP8TYPE)); break; } case (OMX_INDEXTYPE)OMX_IndexParamVideoHevc: { OMX_VIDEO_PARAM_HEVCTYPE* pParam = (OMX_VIDEO_PARAM_HEVCTYPE*)paramData; OMX_VIDEO_PARAM_HEVCTYPE hevc_param; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoHevc"); memcpy(&hevc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_HEVCTYPE)); if (handle->venc_set_param(&hevc_param, (OMX_INDEXTYPE)OMX_IndexParamVideoHevc) != true) { DEBUG_PRINT_ERROR("Failed : set_parameter: OMX_IndexParamVideoHevc"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamHEVC, pParam, sizeof(struct OMX_VIDEO_PARAM_HEVCTYPE)); break; } case OMX_IndexParamVideoProfileLevelCurrent: { OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoProfileLevelCurrent"); if (handle->venc_set_param(pParam,OMX_IndexParamVideoProfileLevelCurrent) != true) { DEBUG_PRINT_ERROR("set_parameter: OMX_IndexParamVideoProfileLevelCurrent failed for Profile: %u " "Level :%u", (unsigned int)pParam->eProfile, (unsigned int)pParam->eLevel); return OMX_ErrorUnsupportedSetting; } m_sParamProfileLevel.eProfile = pParam->eProfile; m_sParamProfileLevel.eLevel = pParam->eLevel; if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.mpeg4",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamMPEG4.eProfile = (OMX_VIDEO_MPEG4PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamMPEG4.eLevel = (OMX_VIDEO_MPEG4LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("MPEG4 profile = %d, level = %d", m_sParamMPEG4.eProfile, m_sParamMPEG4.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.h263",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamH263.eProfile = (OMX_VIDEO_H263PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamH263.eLevel = (OMX_VIDEO_H263LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("H263 profile = %d, level = %d", m_sParamH263.eProfile, m_sParamH263.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("AVC profile = %d, level = %d", m_sParamAVC.eProfile, m_sParamAVC.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc.secure",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("\n AVC profile = %d, level = %d", m_sParamAVC.eProfile, m_sParamAVC.eLevel); } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamVP8.eProfile = (OMX_VIDEO_VP8PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamVP8.eLevel = (OMX_VIDEO_VP8LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("VP8 profile = %d, level = %d", m_sParamVP8.eProfile, m_sParamVP8.eLevel); } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamHEVC.eProfile = (OMX_VIDEO_HEVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamHEVC.eLevel = (OMX_VIDEO_HEVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("HEVC profile = %d, level = %d", m_sParamHEVC.eProfile, m_sParamHEVC.eLevel); } break; } case OMX_IndexParamStandardComponentRole: { OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s", comp_role->cRole); if ((m_state == OMX_StateLoaded)&& !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc.secure",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s\n", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.h263",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } #ifdef _MSM8974_ else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } #endif else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %s", m_nkind); eRet = OMX_ErrorInvalidComponentName; } break; } case OMX_IndexParamPriorityMgmt: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt"); if (m_state != OMX_StateLoaded) { DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u", (unsigned int)priorityMgmtype->nGroupID); DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u", (unsigned int)priorityMgmtype->nGroupPriority); m_sPriorityMgmt.nGroupID = priorityMgmtype->nGroupID; m_sPriorityMgmt.nGroupPriority = priorityMgmtype->nGroupPriority; break; } case OMX_IndexParamCompBufferSupplier: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier"); OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d", bufferSupplierType->eBufferSupplier); if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1) m_sInBufSupplier.eBufferSupplier = bufferSupplierType->eBufferSupplier; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoQuantization: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoQuantization"); OMX_VIDEO_PARAM_QUANTIZATIONTYPE *session_qp = (OMX_VIDEO_PARAM_QUANTIZATIONTYPE*) paramData; if (session_qp->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_param(paramData, OMX_IndexParamVideoQuantization) != true) { return OMX_ErrorUnsupportedSetting; } m_sSessionQuantization.nQpI = session_qp->nQpI; m_sSessionQuantization.nQpP = session_qp->nQpP; m_sSessionQuantization.nQpB = session_qp->nQpB; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for Session QP setting"); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamVideoQPRange: { DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoQPRange"); OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *qp_range = (OMX_QCOM_VIDEO_PARAM_QPRANGETYPE*) paramData; if (qp_range->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamVideoQPRange) != true) { return OMX_ErrorUnsupportedSetting; } m_sSessionQPRange.minQP= qp_range->minQP; m_sSessionQPRange.maxQP= qp_range->maxQP; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for QP range setting"); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexPortDefn: { OMX_QCOM_PARAM_PORTDEFINITIONTYPE* pParam = (OMX_QCOM_PARAM_PORTDEFINITIONTYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexPortDefn"); if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_IN) { if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid && pParam->nMemRegion < OMX_QCOM_MemRegionMax) { m_use_input_pmem = OMX_TRUE; } else { m_use_input_pmem = OMX_FALSE; } } else if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_OUT) { if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid && pParam->nMemRegion < OMX_QCOM_MemRegionMax) { m_use_output_pmem = OMX_TRUE; } else { m_use_output_pmem = OMX_FALSE; } } else { DEBUG_PRINT_ERROR("ERROR: SetParameter called on unsupported Port Index for QcomPortDefn"); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexParamVideoErrorCorrection: { DEBUG_PRINT_LOW("OMX_IndexParamVideoErrorCorrection"); OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE* pParam = (OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE*)paramData; if (!handle->venc_set_param(paramData, OMX_IndexParamVideoErrorCorrection)) { DEBUG_PRINT_ERROR("ERROR: Request for setting Error Resilience failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sErrorCorrection,pParam, sizeof(m_sErrorCorrection)); break; } case OMX_IndexParamVideoIntraRefresh: { DEBUG_PRINT_LOW("set_param:OMX_IndexParamVideoIntraRefresh"); OMX_VIDEO_PARAM_INTRAREFRESHTYPE* pParam = (OMX_VIDEO_PARAM_INTRAREFRESHTYPE*)paramData; if (!handle->venc_set_param(paramData,OMX_IndexParamVideoIntraRefresh)) { DEBUG_PRINT_ERROR("ERROR: Request for setting intra refresh failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sIntraRefresh, pParam, sizeof(m_sIntraRefresh)); break; } #ifdef _ANDROID_ICS_ case OMX_QcomIndexParamVideoMetaBufferMode: { StoreMetaDataInBuffersParams *pParam = (StoreMetaDataInBuffersParams*)paramData; DEBUG_PRINT_HIGH("set_parameter:OMX_QcomIndexParamVideoMetaBufferMode: " "port_index = %u, meta_mode = %d", (unsigned int)pParam->nPortIndex, pParam->bStoreMetaData); if (pParam->nPortIndex == PORT_INDEX_IN) { if (pParam->bStoreMetaData != meta_mode_enable) { if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) { DEBUG_PRINT_ERROR("ERROR: set Metabuffer mode %d fail", pParam->bStoreMetaData); return OMX_ErrorUnsupportedSetting; } meta_mode_enable = pParam->bStoreMetaData; if (meta_mode_enable) { m_sInPortDef.nBufferCountActual = m_sInPortDef.nBufferCountMin; if (handle->venc_set_param(&m_sInPortDef,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed"); return OMX_ErrorUnsupportedSetting; } } else { /*TODO: reset encoder driver Meta mode*/ dev_get_buf_req (&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); } } } else if (pParam->nPortIndex == PORT_INDEX_OUT && secure_session) { if (pParam->bStoreMetaData != meta_mode_enable) { if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) { DEBUG_PRINT_ERROR("\nERROR: set Metabuffer mode %d fail", pParam->bStoreMetaData); return OMX_ErrorUnsupportedSetting; } meta_mode_enable = pParam->bStoreMetaData; } } else { DEBUG_PRINT_ERROR("set_parameter: metamode is " "valid for input port only"); eRet = OMX_ErrorUnsupportedIndex; } } break; #endif #if !defined(MAX_RES_720P) || defined(_MSM8974_) case OMX_QcomIndexParamIndexExtraDataType: { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType"); QOMX_INDEXEXTRADATATYPE *pParam = (QOMX_INDEXEXTRADATATYPE *)paramData; bool enable = false; OMX_U32 mask = 0; if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderSliceInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { mask = VEN_EXTRADATA_SLICEINFO; DEBUG_PRINT_HIGH("SliceInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: Slice information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderMBInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { mask = VEN_EXTRADATA_MBINFO; DEBUG_PRINT_HIGH("MBInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: MB information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } #ifndef _MSM8974_ else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoLTRInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { if (pParam->bEnabled == OMX_TRUE) mask = VEN_EXTRADATA_LTRINFO; DEBUG_PRINT_HIGH("LTRInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: LTR information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } #endif else { DEBUG_PRINT_ERROR("set_parameter: unsupported extrdata index (%x)", pParam->nIndex); eRet = OMX_ErrorUnsupportedIndex; break; } if (pParam->bEnabled == OMX_TRUE) m_sExtraData |= mask; else m_sExtraData &= ~mask; enable = !!(m_sExtraData & mask); if (handle->venc_set_param(&enable, (OMX_INDEXTYPE)pParam->nIndex) != true) { DEBUG_PRINT_ERROR("ERROR: Setting Extradata (%x) failed", pParam->nIndex); return OMX_ErrorUnsupportedSetting; } else { m_sOutPortDef.nPortIndex = PORT_INDEX_OUT; dev_get_buf_req(&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); DEBUG_PRINT_HIGH("updated out_buf_req: buffer cnt=%u, " "count min=%u, buffer size=%u", (unsigned int)m_sOutPortDef.nBufferCountActual, (unsigned int)m_sOutPortDef.nBufferCountMin, (unsigned int)m_sOutPortDef.nBufferSize); } break; } case QOMX_IndexParamVideoLTRMode: { QOMX_VIDEO_PARAM_LTRMODE_TYPE* pParam = (QOMX_VIDEO_PARAM_LTRMODE_TYPE*)paramData; if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRMode)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR mode failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamLTRMode, pParam, sizeof(m_sParamLTRMode)); break; } case QOMX_IndexParamVideoLTRCount: { QOMX_VIDEO_PARAM_LTRCOUNT_TYPE* pParam = (QOMX_VIDEO_PARAM_LTRCOUNT_TYPE*)paramData; if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRCount)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR count failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamLTRCount, pParam, sizeof(m_sParamLTRCount)); break; } #endif case OMX_QcomIndexParamVideoMaxAllowedBitrateCheck: { QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; if (pParam->nPortIndex == PORT_INDEX_OUT) { handle->m_max_allowed_bitrate_check = ((pParam->bEnable == OMX_TRUE) ? true : false); DEBUG_PRINT_HIGH("set_parameter: max allowed bitrate check %s", ((pParam->bEnable == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexParamVideoMaxAllowedBitrateCheck " " called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } #ifdef MAX_RES_1080P case OMX_QcomIndexEnableSliceDeliveryMode: { QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexEnableSliceDeliveryMode)) { DEBUG_PRINT_ERROR("ERROR: Request for setting slice delivery mode failed"); return OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableSliceDeliveryMode " "called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } #endif case OMX_QcomIndexEnableH263PlusPType: { QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; DEBUG_PRINT_LOW("OMX_QcomIndexEnableH263PlusPType"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexEnableH263PlusPType)) { DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed"); return OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableH263PlusPType " "called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamSequenceHeaderWithIDR: { if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamSequenceHeaderWithIDR)) { DEBUG_PRINT_ERROR("%s: %s", "OMX_QComIndexParamSequenceHeaderWithIDR:", "request for inband sps/pps failed."); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamH264AUDelimiter: { if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamH264AUDelimiter)) { DEBUG_PRINT_ERROR("%s: %s", "OMX_QComIndexParamh264AUDelimiter:", "request for AU Delimiters failed."); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexHierarchicalStructure: { QOMX_VIDEO_HIERARCHICALLAYERS* pParam = (QOMX_VIDEO_HIERARCHICALLAYERS*)paramData; DEBUG_PRINT_LOW("OMX_QcomIndexHierarchicalStructure"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexHierarchicalStructure)) { DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed"); return OMX_ErrorUnsupportedSetting; } if((pParam->eHierarchicalCodingType == QOMX_HIERARCHICALCODING_B) && pParam->nNumLayers) hier_b_enabled = true; m_sHierLayers.nNumLayers = pParam->nNumLayers; m_sHierLayers.eHierarchicalCodingType = pParam->eHierarchicalCodingType; } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexHierarchicalStructure called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamPerfLevel: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamPerfLevel)) { DEBUG_PRINT_ERROR("ERROR: Setting performance level"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamH264VUITimingInfo: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamH264VUITimingInfo)) { DEBUG_PRINT_ERROR("ERROR: Setting VUI timing info"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamPeakBitrate: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamPeakBitrate)) { DEBUG_PRINT_ERROR("ERROR: Setting peak bitrate"); return OMX_ErrorUnsupportedSetting; } break; } case QOMX_IndexParamVideoInitialQp: { if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoInitialQp)) { DEBUG_PRINT_ERROR("Request to Enable initial QP failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamInitqp, paramData, sizeof(m_sParamInitqp)); break; } case OMX_QcomIndexParamSetMVSearchrange: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamSetMVSearchrange)) { DEBUG_PRINT_ERROR("ERROR: Setting Searchrange"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamVideoHybridHierpMode: { if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamVideoHybridHierpMode)) { DEBUG_PRINT_ERROR("Request to Enable Hybrid Hier-P failed"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexParamVideoSliceFMO: default: { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %d", paramIndex); eRet = OMX_ErrorUnsupportedIndex; break; } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
OMX_ERRORTYPE omx_venc::set_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_IN OMX_PTR paramData) { (void)hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: Set Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_ERROR("ERROR: Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } /*set_parameter can be called in loaded state or disabled port */ if (m_state == OMX_StateLoaded || m_sInPortDef.bEnabled == OMX_FALSE || m_sOutPortDef.bEnabled == OMX_FALSE) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } switch ((int)paramIndex) { case OMX_IndexParamPortDefinition: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_PORTDEFINITIONTYPE); OMX_PARAM_PORTDEFINITIONTYPE *portDefn; portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d", (int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nFrameWidth); if (PORT_INDEX_IN == portDefn->nPortIndex) { if (!dev_is_video_session_supported(portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight)) { DEBUG_PRINT_ERROR("video session not supported"); omx_report_unsupported_setting(); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("i/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual); DEBUG_PRINT_LOW("i/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin); DEBUG_PRINT_LOW("i/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize); if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: (In_PORT) Min buffers (%u) > actual count (%u)", (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed"); return handle->hw_overload ? OMX_ErrorInsufficientResources : OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("i/p previous actual cnt = %u", (unsigned int)m_sInPortDef.nBufferCountActual); DEBUG_PRINT_LOW("i/p previous min cnt = %u", (unsigned int)m_sInPortDef.nBufferCountMin); memcpy(&m_sInPortDef, portDefn,sizeof(OMX_PARAM_PORTDEFINITIONTYPE)); #ifdef _ANDROID_ICS_ if (portDefn->format.video.eColorFormat == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) { m_sInPortDef.format.video.eColorFormat = (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; if (!mUseProxyColorFormat) { if (!c2d_conv.init()) { DEBUG_PRINT_ERROR("C2D init failed"); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_HIGH("C2D init is successful"); } mUseProxyColorFormat = true; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ; } else mUseProxyColorFormat = false; #endif /*Query Input Buffer Requirements*/ dev_get_buf_req (&m_sInPortDef.nBufferCountMin, &m_sInPortDef.nBufferCountActual, &m_sInPortDef.nBufferSize, m_sInPortDef.nPortIndex); /*Query ouput Buffer Requirements*/ dev_get_buf_req (&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); m_sInPortDef.nBufferCountActual = portDefn->nBufferCountActual; } else if (PORT_INDEX_OUT == portDefn->nPortIndex) { DEBUG_PRINT_LOW("o/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual); DEBUG_PRINT_LOW("o/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin); DEBUG_PRINT_LOW("o/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize); if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: (Out_PORT) Min buffers (%u) > actual count (%u)", (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param output failed"); return OMX_ErrorUnsupportedSetting; } #ifdef _MSM8974_ /*Query ouput Buffer Requirements*/ dev_get_buf_req(&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); #endif memcpy(&m_sOutPortDef,portDefn,sizeof(struct OMX_PARAM_PORTDEFINITIONTYPE)); update_profile_level(); //framerate , bitrate DEBUG_PRINT_LOW("o/p previous actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); DEBUG_PRINT_LOW("o/p previous min cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountMin); m_sOutPortDef.nBufferCountActual = portDefn->nBufferCountActual; } else { DEBUG_PRINT_ERROR("ERROR: Set_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } m_sConfigFramerate.xEncodeFramerate = portDefn->format.video.xFramerate; m_sConfigBitrate.nEncodeBitrate = portDefn->format.video.nBitrate; m_sParamBitrate.nTargetBitrate = portDefn->format.video.nBitrate; } break; case OMX_IndexParamVideoPortFormat: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE); OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d", portFmt->eColorFormat); if (PORT_INDEX_IN == portFmt->nPortIndex) { if (handle->venc_set_param(paramData,OMX_IndexParamVideoPortFormat) != true) { return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d", portFmt->eColorFormat); update_profile_level(); //framerate #ifdef _ANDROID_ICS_ if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) { m_sInPortFormat.eColorFormat = (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; if (!mUseProxyColorFormat) { if (!c2d_conv.init()) { DEBUG_PRINT_ERROR("C2D init failed"); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_HIGH("C2D init is successful"); } mUseProxyColorFormat = true; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ; } else #endif { m_sInPortFormat.eColorFormat = portFmt->eColorFormat; m_sInPortDef.format.video.eColorFormat = portFmt->eColorFormat; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB; mUseProxyColorFormat = false; } m_sInPortFormat.xFramerate = portFmt->xFramerate; } } break; case OMX_IndexParamVideoInit: { //TODO, do we need this index set param VALIDATE_OMX_PARAM_DATA(paramData, OMX_PORT_PARAM_TYPE); OMX_PORT_PARAM_TYPE* pParam = (OMX_PORT_PARAM_TYPE*)(paramData); DEBUG_PRINT_LOW("Set OMX_IndexParamVideoInit called"); break; } case OMX_IndexParamVideoBitrate: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_BITRATETYPE); OMX_VIDEO_PARAM_BITRATETYPE* pParam = (OMX_VIDEO_PARAM_BITRATETYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoBitrate"); if (handle->venc_set_param(paramData,OMX_IndexParamVideoBitrate) != true) { return OMX_ErrorUnsupportedSetting; } m_sParamBitrate.nTargetBitrate = pParam->nTargetBitrate; m_sParamBitrate.eControlRate = pParam->eControlRate; update_profile_level(); //bitrate m_sConfigBitrate.nEncodeBitrate = pParam->nTargetBitrate; m_sInPortDef.format.video.nBitrate = pParam->nTargetBitrate; m_sOutPortDef.format.video.nBitrate = pParam->nTargetBitrate; DEBUG_PRINT_LOW("bitrate = %u", (unsigned int)m_sOutPortDef.format.video.nBitrate); break; } case OMX_IndexParamVideoMpeg4: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_MPEG4TYPE); OMX_VIDEO_PARAM_MPEG4TYPE* pParam = (OMX_VIDEO_PARAM_MPEG4TYPE*)paramData; OMX_VIDEO_PARAM_MPEG4TYPE mp4_param; memcpy(&mp4_param, pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE)); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4"); if (pParam->eProfile == OMX_VIDEO_MPEG4ProfileAdvancedSimple) { #ifdef MAX_RES_1080P if (pParam->nBFrames) { DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported"); mp4_param.nBFrames = 1; } #else if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); mp4_param.nBFrames = 0; } #endif #ifdef _MSM8974_ if (pParam->nBFrames || bframes) mp4_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes; DEBUG_PRINT_HIGH("MPEG4: %u BFrames are being set", (unsigned int)mp4_param.nBFrames); #endif } else { if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); mp4_param.nBFrames = 0; } } if (handle->venc_set_param(&mp4_param,OMX_IndexParamVideoMpeg4) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamMPEG4,pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE)); m_sIntraperiod.nPFrames = m_sParamMPEG4.nPFrames; if (pParam->nBFrames || bframes) m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames = mp4_param.nBFrames; else m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames; break; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE* pParam = (OMX_VIDEO_PARAM_H263TYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263"); if (handle->venc_set_param(paramData,OMX_IndexParamVideoH263) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamH263,pParam, sizeof(struct OMX_VIDEO_PARAM_H263TYPE)); m_sIntraperiod.nPFrames = m_sParamH263.nPFrames; m_sIntraperiod.nBFrames = m_sParamH263.nBFrames; break; } case OMX_IndexParamVideoAvc: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_AVCTYPE); OMX_VIDEO_PARAM_AVCTYPE* pParam = (OMX_VIDEO_PARAM_AVCTYPE*)paramData; OMX_VIDEO_PARAM_AVCTYPE avc_param; memcpy(&avc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_AVCTYPE)); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc"); if ((pParam->eProfile == OMX_VIDEO_AVCProfileHigh)|| (pParam->eProfile == OMX_VIDEO_AVCProfileMain)) { #ifdef MAX_RES_1080P if (pParam->nBFrames) { DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported"); avc_param.nBFrames = 1; } if (pParam->nRefFrames != 2) { DEBUG_PRINT_ERROR("Warning: 2 RefFrames are needed, changing RefFrames from %u to 2", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 2; } #else if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); avc_param.nBFrames = 0; } if (pParam->nRefFrames != 1) { DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 1; } #endif #ifdef _MSM8974_ if (pParam->nBFrames || bframes) { avc_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes; avc_param.nRefFrames = (avc_param.nBFrames < 4)? avc_param.nBFrames + 1 : 4; } DEBUG_PRINT_HIGH("AVC: RefFrames: %u, BFrames: %u", (unsigned int)avc_param.nRefFrames, (unsigned int)avc_param.nBFrames); avc_param.bEntropyCodingCABAC = (OMX_BOOL)(avc_param.bEntropyCodingCABAC && entropy); avc_param.nCabacInitIdc = entropy ? avc_param.nCabacInitIdc : 0; #endif } else { if (pParam->nRefFrames != 1) { DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 1; } if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); avc_param.nBFrames = 0; } } if (handle->venc_set_param(&avc_param,OMX_IndexParamVideoAvc) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamAVC,pParam, sizeof(struct OMX_VIDEO_PARAM_AVCTYPE)); m_sIntraperiod.nPFrames = m_sParamAVC.nPFrames; if (pParam->nBFrames || bframes) m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames = avc_param.nBFrames; else m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames; break; } case (OMX_INDEXTYPE)OMX_IndexParamVideoVp8: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_VP8TYPE); OMX_VIDEO_PARAM_VP8TYPE* pParam = (OMX_VIDEO_PARAM_VP8TYPE*)paramData; OMX_VIDEO_PARAM_VP8TYPE vp8_param; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoVp8"); if (pParam->nDCTPartitions != m_sParamVP8.nDCTPartitions || pParam->bErrorResilientMode != m_sParamVP8.bErrorResilientMode) { DEBUG_PRINT_ERROR("VP8 doesn't support nDCTPartitions or bErrorResilientMode"); } memcpy(&vp8_param, pParam, sizeof( struct OMX_VIDEO_PARAM_VP8TYPE)); if (handle->venc_set_param(&vp8_param, (OMX_INDEXTYPE)OMX_IndexParamVideoVp8) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamVP8,pParam, sizeof(struct OMX_VIDEO_PARAM_VP8TYPE)); break; } case (OMX_INDEXTYPE)OMX_IndexParamVideoHevc: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_HEVCTYPE); OMX_VIDEO_PARAM_HEVCTYPE* pParam = (OMX_VIDEO_PARAM_HEVCTYPE*)paramData; OMX_VIDEO_PARAM_HEVCTYPE hevc_param; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoHevc"); memcpy(&hevc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_HEVCTYPE)); if (handle->venc_set_param(&hevc_param, (OMX_INDEXTYPE)OMX_IndexParamVideoHevc) != true) { DEBUG_PRINT_ERROR("Failed : set_parameter: OMX_IndexParamVideoHevc"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamHEVC, pParam, sizeof(struct OMX_VIDEO_PARAM_HEVCTYPE)); break; } case OMX_IndexParamVideoProfileLevelCurrent: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE); OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoProfileLevelCurrent"); if (handle->venc_set_param(pParam,OMX_IndexParamVideoProfileLevelCurrent) != true) { DEBUG_PRINT_ERROR("set_parameter: OMX_IndexParamVideoProfileLevelCurrent failed for Profile: %u " "Level :%u", (unsigned int)pParam->eProfile, (unsigned int)pParam->eLevel); return OMX_ErrorUnsupportedSetting; } m_sParamProfileLevel.eProfile = pParam->eProfile; m_sParamProfileLevel.eLevel = pParam->eLevel; if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.mpeg4",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamMPEG4.eProfile = (OMX_VIDEO_MPEG4PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamMPEG4.eLevel = (OMX_VIDEO_MPEG4LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("MPEG4 profile = %d, level = %d", m_sParamMPEG4.eProfile, m_sParamMPEG4.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.h263",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamH263.eProfile = (OMX_VIDEO_H263PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamH263.eLevel = (OMX_VIDEO_H263LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("H263 profile = %d, level = %d", m_sParamH263.eProfile, m_sParamH263.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("AVC profile = %d, level = %d", m_sParamAVC.eProfile, m_sParamAVC.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc.secure",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("\n AVC profile = %d, level = %d", m_sParamAVC.eProfile, m_sParamAVC.eLevel); } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamVP8.eProfile = (OMX_VIDEO_VP8PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamVP8.eLevel = (OMX_VIDEO_VP8LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("VP8 profile = %d, level = %d", m_sParamVP8.eProfile, m_sParamVP8.eLevel); } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamHEVC.eProfile = (OMX_VIDEO_HEVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamHEVC.eLevel = (OMX_VIDEO_HEVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("HEVC profile = %d, level = %d", m_sParamHEVC.eProfile, m_sParamHEVC.eLevel); } break; } case OMX_IndexParamStandardComponentRole: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_COMPONENTROLETYPE); OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s", comp_role->cRole); if ((m_state == OMX_StateLoaded)&& !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc.secure",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s\n", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.h263",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } #ifdef _MSM8974_ else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } #endif else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %s", m_nkind); eRet = OMX_ErrorInvalidComponentName; } break; } case OMX_IndexParamPriorityMgmt: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt"); if (m_state != OMX_StateLoaded) { DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u", (unsigned int)priorityMgmtype->nGroupID); DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u", (unsigned int)priorityMgmtype->nGroupPriority); m_sPriorityMgmt.nGroupID = priorityMgmtype->nGroupID; m_sPriorityMgmt.nGroupPriority = priorityMgmtype->nGroupPriority; break; } case OMX_IndexParamCompBufferSupplier: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier"); OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d", bufferSupplierType->eBufferSupplier); if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1) m_sInBufSupplier.eBufferSupplier = bufferSupplierType->eBufferSupplier; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoQuantization: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_QUANTIZATIONTYPE); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoQuantization"); OMX_VIDEO_PARAM_QUANTIZATIONTYPE *session_qp = (OMX_VIDEO_PARAM_QUANTIZATIONTYPE*) paramData; if (session_qp->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_param(paramData, OMX_IndexParamVideoQuantization) != true) { return OMX_ErrorUnsupportedSetting; } m_sSessionQuantization.nQpI = session_qp->nQpI; m_sSessionQuantization.nQpP = session_qp->nQpP; m_sSessionQuantization.nQpB = session_qp->nQpB; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for Session QP setting"); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamVideoQPRange: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_QPRANGETYPE); DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoQPRange"); OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *qp_range = (OMX_QCOM_VIDEO_PARAM_QPRANGETYPE*) paramData; if (qp_range->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamVideoQPRange) != true) { return OMX_ErrorUnsupportedSetting; } m_sSessionQPRange.minQP= qp_range->minQP; m_sSessionQPRange.maxQP= qp_range->maxQP; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for QP range setting"); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexPortDefn: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PARAM_PORTDEFINITIONTYPE); OMX_QCOM_PARAM_PORTDEFINITIONTYPE* pParam = (OMX_QCOM_PARAM_PORTDEFINITIONTYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexPortDefn"); if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_IN) { if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid && pParam->nMemRegion < OMX_QCOM_MemRegionMax) { m_use_input_pmem = OMX_TRUE; } else { m_use_input_pmem = OMX_FALSE; } } else if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_OUT) { if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid && pParam->nMemRegion < OMX_QCOM_MemRegionMax) { m_use_output_pmem = OMX_TRUE; } else { m_use_output_pmem = OMX_FALSE; } } else { DEBUG_PRINT_ERROR("ERROR: SetParameter called on unsupported Port Index for QcomPortDefn"); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexParamVideoErrorCorrection: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE); DEBUG_PRINT_LOW("OMX_IndexParamVideoErrorCorrection"); OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE* pParam = (OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE*)paramData; if (!handle->venc_set_param(paramData, OMX_IndexParamVideoErrorCorrection)) { DEBUG_PRINT_ERROR("ERROR: Request for setting Error Resilience failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sErrorCorrection,pParam, sizeof(m_sErrorCorrection)); break; } case OMX_IndexParamVideoIntraRefresh: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_INTRAREFRESHTYPE); DEBUG_PRINT_LOW("set_param:OMX_IndexParamVideoIntraRefresh"); OMX_VIDEO_PARAM_INTRAREFRESHTYPE* pParam = (OMX_VIDEO_PARAM_INTRAREFRESHTYPE*)paramData; if (!handle->venc_set_param(paramData,OMX_IndexParamVideoIntraRefresh)) { DEBUG_PRINT_ERROR("ERROR: Request for setting intra refresh failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sIntraRefresh, pParam, sizeof(m_sIntraRefresh)); break; } #ifdef _ANDROID_ICS_ case OMX_QcomIndexParamVideoMetaBufferMode: { VALIDATE_OMX_PARAM_DATA(paramData, StoreMetaDataInBuffersParams); StoreMetaDataInBuffersParams *pParam = (StoreMetaDataInBuffersParams*)paramData; DEBUG_PRINT_HIGH("set_parameter:OMX_QcomIndexParamVideoMetaBufferMode: " "port_index = %u, meta_mode = %d", (unsigned int)pParam->nPortIndex, pParam->bStoreMetaData); if (pParam->nPortIndex == PORT_INDEX_IN) { if (pParam->bStoreMetaData != meta_mode_enable) { if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) { DEBUG_PRINT_ERROR("ERROR: set Metabuffer mode %d fail", pParam->bStoreMetaData); return OMX_ErrorUnsupportedSetting; } meta_mode_enable = pParam->bStoreMetaData; if (meta_mode_enable) { m_sInPortDef.nBufferCountActual = m_sInPortDef.nBufferCountMin; if (handle->venc_set_param(&m_sInPortDef,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed"); return OMX_ErrorUnsupportedSetting; } } else { /*TODO: reset encoder driver Meta mode*/ dev_get_buf_req (&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); } } } else if (pParam->nPortIndex == PORT_INDEX_OUT && secure_session) { if (pParam->bStoreMetaData != meta_mode_enable) { if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) { DEBUG_PRINT_ERROR("\nERROR: set Metabuffer mode %d fail", pParam->bStoreMetaData); return OMX_ErrorUnsupportedSetting; } meta_mode_enable = pParam->bStoreMetaData; } } else { DEBUG_PRINT_ERROR("set_parameter: metamode is " "valid for input port only"); eRet = OMX_ErrorUnsupportedIndex; } } break; #endif #if !defined(MAX_RES_720P) || defined(_MSM8974_) case OMX_QcomIndexParamIndexExtraDataType: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXEXTRADATATYPE); DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType"); QOMX_INDEXEXTRADATATYPE *pParam = (QOMX_INDEXEXTRADATATYPE *)paramData; bool enable = false; OMX_U32 mask = 0; if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderSliceInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { mask = VEN_EXTRADATA_SLICEINFO; DEBUG_PRINT_HIGH("SliceInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: Slice information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderMBInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { mask = VEN_EXTRADATA_MBINFO; DEBUG_PRINT_HIGH("MBInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: MB information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } #ifndef _MSM8974_ else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoLTRInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { if (pParam->bEnabled == OMX_TRUE) mask = VEN_EXTRADATA_LTRINFO; DEBUG_PRINT_HIGH("LTRInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: LTR information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } #endif else { DEBUG_PRINT_ERROR("set_parameter: unsupported extrdata index (%x)", pParam->nIndex); eRet = OMX_ErrorUnsupportedIndex; break; } if (pParam->bEnabled == OMX_TRUE) m_sExtraData |= mask; else m_sExtraData &= ~mask; enable = !!(m_sExtraData & mask); if (handle->venc_set_param(&enable, (OMX_INDEXTYPE)pParam->nIndex) != true) { DEBUG_PRINT_ERROR("ERROR: Setting Extradata (%x) failed", pParam->nIndex); return OMX_ErrorUnsupportedSetting; } else { m_sOutPortDef.nPortIndex = PORT_INDEX_OUT; dev_get_buf_req(&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); DEBUG_PRINT_HIGH("updated out_buf_req: buffer cnt=%u, " "count min=%u, buffer size=%u", (unsigned int)m_sOutPortDef.nBufferCountActual, (unsigned int)m_sOutPortDef.nBufferCountMin, (unsigned int)m_sOutPortDef.nBufferSize); } break; } case QOMX_IndexParamVideoLTRMode: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_PARAM_LTRMODE_TYPE); QOMX_VIDEO_PARAM_LTRMODE_TYPE* pParam = (QOMX_VIDEO_PARAM_LTRMODE_TYPE*)paramData; if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRMode)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR mode failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamLTRMode, pParam, sizeof(m_sParamLTRMode)); break; } case QOMX_IndexParamVideoLTRCount: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_PARAM_LTRCOUNT_TYPE); QOMX_VIDEO_PARAM_LTRCOUNT_TYPE* pParam = (QOMX_VIDEO_PARAM_LTRCOUNT_TYPE*)paramData; if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRCount)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR count failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamLTRCount, pParam, sizeof(m_sParamLTRCount)); break; } #endif case OMX_QcomIndexParamVideoMaxAllowedBitrateCheck: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE); QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; if (pParam->nPortIndex == PORT_INDEX_OUT) { handle->m_max_allowed_bitrate_check = ((pParam->bEnable == OMX_TRUE) ? true : false); DEBUG_PRINT_HIGH("set_parameter: max allowed bitrate check %s", ((pParam->bEnable == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexParamVideoMaxAllowedBitrateCheck " " called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } #ifdef MAX_RES_1080P case OMX_QcomIndexEnableSliceDeliveryMode: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE); QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexEnableSliceDeliveryMode)) { DEBUG_PRINT_ERROR("ERROR: Request for setting slice delivery mode failed"); return OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableSliceDeliveryMode " "called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } #endif case OMX_QcomIndexEnableH263PlusPType: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE); QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; DEBUG_PRINT_LOW("OMX_QcomIndexEnableH263PlusPType"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexEnableH263PlusPType)) { DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed"); return OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableH263PlusPType " "called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamSequenceHeaderWithIDR: { VALIDATE_OMX_PARAM_DATA(paramData, PrependSPSPPSToIDRFramesParams); if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamSequenceHeaderWithIDR)) { DEBUG_PRINT_ERROR("%s: %s", "OMX_QComIndexParamSequenceHeaderWithIDR:", "request for inband sps/pps failed."); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamH264AUDelimiter: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_CONFIG_H264_AUD); if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamH264AUDelimiter)) { DEBUG_PRINT_ERROR("%s: %s", "OMX_QComIndexParamh264AUDelimiter:", "request for AU Delimiters failed."); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexHierarchicalStructure: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_HIERARCHICALLAYERS); QOMX_VIDEO_HIERARCHICALLAYERS* pParam = (QOMX_VIDEO_HIERARCHICALLAYERS*)paramData; DEBUG_PRINT_LOW("OMX_QcomIndexHierarchicalStructure"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexHierarchicalStructure)) { DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed"); return OMX_ErrorUnsupportedSetting; } if((pParam->eHierarchicalCodingType == QOMX_HIERARCHICALCODING_B) && pParam->nNumLayers) hier_b_enabled = true; m_sHierLayers.nNumLayers = pParam->nNumLayers; m_sHierLayers.eHierarchicalCodingType = pParam->eHierarchicalCodingType; } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexHierarchicalStructure called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamPerfLevel: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_PERF_LEVEL); if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamPerfLevel)) { DEBUG_PRINT_ERROR("ERROR: Setting performance level"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamH264VUITimingInfo: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO); if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamH264VUITimingInfo)) { DEBUG_PRINT_ERROR("ERROR: Setting VUI timing info"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamPeakBitrate: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE); if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamPeakBitrate)) { DEBUG_PRINT_ERROR("ERROR: Setting peak bitrate"); return OMX_ErrorUnsupportedSetting; } break; } case QOMX_IndexParamVideoInitialQp: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_VIDEO_INITIALQP); if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoInitialQp)) { DEBUG_PRINT_ERROR("Request to Enable initial QP failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamInitqp, paramData, sizeof(m_sParamInitqp)); break; } case OMX_QcomIndexParamSetMVSearchrange: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamSetMVSearchrange)) { DEBUG_PRINT_ERROR("ERROR: Setting Searchrange"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamVideoHybridHierpMode: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE); if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamVideoHybridHierpMode)) { DEBUG_PRINT_ERROR("Request to Enable Hybrid Hier-P failed"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexParamVideoSliceFMO: default: { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %d", paramIndex); eRet = OMX_ErrorUnsupportedIndex; break; } } return eRet; }
173,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1) : mIsValid(false), mData(NULL), mSize(0), mFirstFrameOffset(0), mVersion(ID3_UNKNOWN), mRawSize(0) { sp<MemorySource> source = new MemorySource(data, size); mIsValid = parseV2(source, 0); if (!mIsValid && !ignoreV1) { mIsValid = parseV1(source); } } Commit Message: better validation lengths of strings in ID3 tags Validate lengths on strings in ID3 tags, particularly around 0. Also added code to handle cases when we can't get memory for copies of strings we want to extract from these tags. Affects L/M/N/master, same patch for all of them. Bug: 30744884 Change-Id: I2675a817a39f0927ec1f7e9f9c09f2e61020311e Test: play mp3 file which caused a <0 length. (cherry picked from commit d23c01546c4f82840a01a380def76ab6cae5d43f) CWE ID: CWE-20
ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1) : mIsValid(false), mData(NULL), mSize(0), mFirstFrameOffset(0), mVersion(ID3_UNKNOWN), mRawSize(0) { sp<MemorySource> source = new (std::nothrow) MemorySource(data, size); if (source == NULL) return; mIsValid = parseV2(source, 0); if (!mIsValid && !ignoreV1) { mIsValid = parseV1(source); } }
173,392
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:quality-layers"); if (option == (const char *) NULL) option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image, (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if ((image_info->number_scenes != 0) && (image_info->scene != 0)) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene-1); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) || (jp2_image->comps[0].dx != jp2_image->comps[i].dx) || (jp2_image->comps[0].dy != jp2_image->comps[i].dy) || (jp2_image->comps[0].prec != jp2_image->comps[i].prec) || (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) || (jp2_image->comps[i].data == NULL)) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->compression=JPEG2000Compression; if (jp2_image->color_space == 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } else if (jp2_image->color_space == 3) SetImageColorspace(image,Rec601YCbCrColorspace); if (jp2_image->numcomps > 3) image->matte=MagickTrue; if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/501 CWE ID: CWE-20
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:quality-layers"); if (option == (const char *) NULL) option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image, (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if ((image_info->number_scenes != 0) && (image_info->scene != 0)) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene-1); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) || (jp2_image->comps[0].dx != jp2_image->comps[i].dx) || (jp2_image->comps[0].dy != jp2_image->comps[i].dy) || (jp2_image->comps[0].prec != jp2_image->comps[i].prec) || (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) || ((image->ping == MagickFalse) && (jp2_image->comps[i].data == NULL))) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->compression=JPEG2000Compression; if (jp2_image->color_space == 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } else if (jp2_image->color_space == 3) SetImageColorspace(image,Rec601YCbCrColorspace); if (jp2_image->numcomps > 3) image->matte=MagickTrue; if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
167,809
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg) { __be32 *p; /* * opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4, * owner 4 = 32 */ RESERVE_SPACE(8); WRITE32(OP_OPEN); WRITE32(arg->seqid->sequence->counter); encode_share_access(xdr, arg->open_flags); RESERVE_SPACE(28); WRITE64(arg->clientid); WRITE32(16); WRITEMEM("open id:", 8); WRITE64(arg->id); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg) { __be32 *p; /* * opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4, * owner 4 = 32 */ RESERVE_SPACE(8); WRITE32(OP_OPEN); WRITE32(arg->seqid->sequence->counter); encode_share_access(xdr, arg->fmode); RESERVE_SPACE(28); WRITE64(arg->clientid); WRITE32(16); WRITEMEM("open id:", 8); WRITE64(arg->id); }
165,714
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal) { HEVCLocalContext *lc = s->HEVClc; GetBitContext *gb = &lc->gb; int ctb_addr_ts, ret; *gb = nal->gb; s->nal_unit_type = nal->type; s->temporal_id = nal->temporal_id; switch (s->nal_unit_type) { case HEVC_NAL_VPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps, s->apply_defdispwin); if (ret < 0) goto fail; break; case HEVC_NAL_PPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SEI_PREFIX: case HEVC_NAL_SEI_SUFFIX: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sei(gb, s->avctx, &s->sei, &s->ps, s->nal_unit_type); if (ret < 0) goto fail; break; case HEVC_NAL_TRAIL_R: case HEVC_NAL_TRAIL_N: case HEVC_NAL_TSA_N: case HEVC_NAL_TSA_R: case HEVC_NAL_STSA_N: case HEVC_NAL_STSA_R: case HEVC_NAL_BLA_W_LP: case HEVC_NAL_BLA_W_RADL: case HEVC_NAL_BLA_N_LP: case HEVC_NAL_IDR_W_RADL: case HEVC_NAL_IDR_N_LP: case HEVC_NAL_CRA_NUT: case HEVC_NAL_RADL_N: case HEVC_NAL_RADL_R: case HEVC_NAL_RASL_N: case HEVC_NAL_RASL_R: ret = hls_slice_header(s); if (ret < 0) return ret; if ( (s->avctx->skip_frame >= AVDISCARD_BIDIR && s->sh.slice_type == HEVC_SLICE_B) || (s->avctx->skip_frame >= AVDISCARD_NONINTRA && s->sh.slice_type != HEVC_SLICE_I) || (s->avctx->skip_frame >= AVDISCARD_NONKEY && !IS_IRAP(s))) { break; } if (s->sh.first_slice_in_pic_flag) { if (s->ref) { av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n"); goto fail; } if (s->max_ra == INT_MAX) { if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) { s->max_ra = s->poc; } else { if (IS_IDR(s)) s->max_ra = INT_MIN; } } if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) && s->poc <= s->max_ra) { s->is_decoded = 0; break; } else { if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra) s->max_ra = INT_MIN; } s->overlap ++; ret = hevc_frame_start(s); if (ret < 0) return ret; } else if (!s->ref) { av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n"); goto fail; } if (s->nal_unit_type != s->first_nal_type) { av_log(s->avctx, AV_LOG_ERROR, "Non-matching NAL types of the VCL NALUs: %d %d\n", s->first_nal_type, s->nal_unit_type); return AVERROR_INVALIDDATA; } if (!s->sh.dependent_slice_segment_flag && s->sh.slice_type != HEVC_SLICE_I) { ret = ff_hevc_slice_rpl(s); if (ret < 0) { av_log(s->avctx, AV_LOG_WARNING, "Error constructing the reference lists for the current slice.\n"); goto fail; } } if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) { ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0); if (ret < 0) goto fail; } if (s->avctx->hwaccel) { ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } else { if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0) ctb_addr_ts = hls_slice_data_wpp(s, nal); else ctb_addr_ts = hls_slice_data(s); if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) { s->is_decoded = 1; } if (ctb_addr_ts < 0) { ret = ctb_addr_ts; goto fail; } } break; case HEVC_NAL_EOS_NUT: case HEVC_NAL_EOB_NUT: s->seq_decode = (s->seq_decode + 1) & 0xff; s->max_ra = INT_MAX; break; case HEVC_NAL_AUD: case HEVC_NAL_FD_NUT: break; default: av_log(s->avctx, AV_LOG_INFO, "Skipping NAL unit %d\n", s->nal_unit_type); } return 0; fail: if (s->avctx->err_recognition & AV_EF_EXPLODE) return ret; return 0; } Commit Message: avcodec/hevcdec: Avoid only partly skiping duplicate first slices Fixes: NULL pointer dereference and out of array access Fixes: 13871/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5746167087890432 Fixes: 13845/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5650370728034304 This also fixes the return code for explode mode Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Reviewed-by: James Almer <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476
static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal) { HEVCLocalContext *lc = s->HEVClc; GetBitContext *gb = &lc->gb; int ctb_addr_ts, ret; *gb = nal->gb; s->nal_unit_type = nal->type; s->temporal_id = nal->temporal_id; switch (s->nal_unit_type) { case HEVC_NAL_VPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps, s->apply_defdispwin); if (ret < 0) goto fail; break; case HEVC_NAL_PPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SEI_PREFIX: case HEVC_NAL_SEI_SUFFIX: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sei(gb, s->avctx, &s->sei, &s->ps, s->nal_unit_type); if (ret < 0) goto fail; break; case HEVC_NAL_TRAIL_R: case HEVC_NAL_TRAIL_N: case HEVC_NAL_TSA_N: case HEVC_NAL_TSA_R: case HEVC_NAL_STSA_N: case HEVC_NAL_STSA_R: case HEVC_NAL_BLA_W_LP: case HEVC_NAL_BLA_W_RADL: case HEVC_NAL_BLA_N_LP: case HEVC_NAL_IDR_W_RADL: case HEVC_NAL_IDR_N_LP: case HEVC_NAL_CRA_NUT: case HEVC_NAL_RADL_N: case HEVC_NAL_RADL_R: case HEVC_NAL_RASL_N: case HEVC_NAL_RASL_R: ret = hls_slice_header(s); if (ret < 0) return ret; if (ret == 1) { ret = AVERROR_INVALIDDATA; goto fail; } if ( (s->avctx->skip_frame >= AVDISCARD_BIDIR && s->sh.slice_type == HEVC_SLICE_B) || (s->avctx->skip_frame >= AVDISCARD_NONINTRA && s->sh.slice_type != HEVC_SLICE_I) || (s->avctx->skip_frame >= AVDISCARD_NONKEY && !IS_IRAP(s))) { break; } if (s->sh.first_slice_in_pic_flag) { if (s->max_ra == INT_MAX) { if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) { s->max_ra = s->poc; } else { if (IS_IDR(s)) s->max_ra = INT_MIN; } } if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) && s->poc <= s->max_ra) { s->is_decoded = 0; break; } else { if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra) s->max_ra = INT_MIN; } s->overlap ++; ret = hevc_frame_start(s); if (ret < 0) return ret; } else if (!s->ref) { av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n"); goto fail; } if (s->nal_unit_type != s->first_nal_type) { av_log(s->avctx, AV_LOG_ERROR, "Non-matching NAL types of the VCL NALUs: %d %d\n", s->first_nal_type, s->nal_unit_type); return AVERROR_INVALIDDATA; } if (!s->sh.dependent_slice_segment_flag && s->sh.slice_type != HEVC_SLICE_I) { ret = ff_hevc_slice_rpl(s); if (ret < 0) { av_log(s->avctx, AV_LOG_WARNING, "Error constructing the reference lists for the current slice.\n"); goto fail; } } if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) { ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0); if (ret < 0) goto fail; } if (s->avctx->hwaccel) { ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } else { if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0) ctb_addr_ts = hls_slice_data_wpp(s, nal); else ctb_addr_ts = hls_slice_data(s); if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) { s->is_decoded = 1; } if (ctb_addr_ts < 0) { ret = ctb_addr_ts; goto fail; } } break; case HEVC_NAL_EOS_NUT: case HEVC_NAL_EOB_NUT: s->seq_decode = (s->seq_decode + 1) & 0xff; s->max_ra = INT_MAX; break; case HEVC_NAL_AUD: case HEVC_NAL_FD_NUT: break; default: av_log(s->avctx, AV_LOG_INFO, "Skipping NAL unit %d\n", s->nal_unit_type); } return 0; fail: if (s->avctx->err_recognition & AV_EF_EXPLODE) return ret; return 0; }
169,706
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { u_int tlen, pdu_type, pdu_len; const u_char *tptr; const rpki_rtr_pdu *pdu_header; tptr = pptr; tlen = len; if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (tlen >= sizeof(rpki_rtr_pdu)) { ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); /* infinite loop check */ if (!pdu_type || !pdu_len) { break; } if (tlen < pdu_len) { goto trunc; } /* * Print the PDU. */ if (rpki_rtr_pdu_print(ndo, tptr, 8)) goto trunc; tlen -= pdu_len; tptr += pdu_len; } return; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); } Commit Message: CVE-2017-13050/RPKI-Router: fix a few bugs The decoder didn't properly check that the PDU length stored in the PDU header is correct. The only check in place was in rpki_rtr_print() and it tested whether the length is zero but that is not sufficient. Make all necessary length and bounds checks, both generic and type-specific, in rpki_rtr_pdu_print() and reduce rpki_rtr_print() to a simple loop. This also fixes a minor bug and PDU type 0 (Serial Notify from RFC 6810 Section 5.2) is valid again. In rpki_rtr_pdu_print() any protocol version was considered version 0, fix it to skip the rest of input if the PDU protocol version is unknown. Ibid, the PDU type 10 (Error Report from RFC 6810 Section 5.10) case block didn't consider the "Length of Error Text" data element mandatory, put it right. Ibid, when printing an encapsulated PDU, give itself (via recursion) respective buffer length to make it possible to tell whether the encapsulated PDU fits. Do not recurse deeper than 2nd level. Update prior RPKI-Router test cases that now stop to decode earlier because of the stricter checks. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (len) { u_int pdu_len = rpki_rtr_pdu_print(ndo, pptr, len, 1, 8); len -= pdu_len; pptr += pdu_len; } }
167,825
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static av_cold int rl2_read_header(AVFormatContext *s) { AVIOContext *pb = s->pb; AVStream *st; unsigned int frame_count; unsigned int audio_frame_counter = 0; unsigned int video_frame_counter = 0; unsigned int back_size; unsigned short sound_rate; unsigned short rate; unsigned short channels; unsigned short def_sound_size; unsigned int signature; unsigned int pts_den = 11025; /* video only case */ unsigned int pts_num = 1103; unsigned int* chunk_offset = NULL; int* chunk_size = NULL; int* audio_size = NULL; int i; int ret = 0; avio_skip(pb,4); /* skip FORM tag */ back_size = avio_rl32(pb); /**< get size of the background frame */ signature = avio_rb32(pb); avio_skip(pb, 4); /* data size */ frame_count = avio_rl32(pb); /* disallow back_sizes and frame_counts that may lead to overflows later */ if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t)) return AVERROR_INVALIDDATA; avio_skip(pb, 2); /* encoding method */ sound_rate = avio_rl16(pb); rate = avio_rl16(pb); channels = avio_rl16(pb); def_sound_size = avio_rl16(pb); /** setup video stream */ st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RL2; st->codecpar->codec_tag = 0; /* no fourcc */ st->codecpar->width = 320; st->codecpar->height = 200; /** allocate and fill extradata */ st->codecpar->extradata_size = EXTRADATA1_SIZE; if(signature == RLV3_TAG && back_size > 0) st->codecpar->extradata_size += back_size; if(ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); /** setup audio stream if present */ if(sound_rate){ if (!channels || channels > 42) { av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels); return AVERROR_INVALIDDATA; } pts_num = def_sound_size; pts_den = rate; st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_PCM_U8; st->codecpar->codec_tag = 1; st->codecpar->channels = channels; st->codecpar->bits_per_coded_sample = 8; st->codecpar->sample_rate = rate; st->codecpar->bit_rate = st->codecpar->channels * st->codecpar->sample_rate * st->codecpar->bits_per_coded_sample; st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample / 8; avpriv_set_pts_info(st,32,1,rate); } avpriv_set_pts_info(s->streams[0], 32, pts_num, pts_den); chunk_size = av_malloc(frame_count * sizeof(uint32_t)); audio_size = av_malloc(frame_count * sizeof(uint32_t)); chunk_offset = av_malloc(frame_count * sizeof(uint32_t)); if(!chunk_size || !audio_size || !chunk_offset){ av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return AVERROR(ENOMEM); } /** read offset and size tables */ for(i=0; i < frame_count;i++) chunk_size[i] = avio_rl32(pb); for(i=0; i < frame_count;i++) chunk_offset[i] = avio_rl32(pb); for(i=0; i < frame_count;i++) audio_size[i] = avio_rl32(pb) & 0xFFFF; /** build the sample index */ for(i=0;i<frame_count;i++){ if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){ ret = AVERROR_INVALIDDATA; break; } if(sound_rate && audio_size[i]){ av_add_index_entry(s->streams[1], chunk_offset[i], audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME); audio_frame_counter += audio_size[i] / channels; } av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i], video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME); ++video_frame_counter; } av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return ret; } Commit Message: avformat/rl2: Fix DoS due to lack of eof check Fixes: loop.rl2 Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static av_cold int rl2_read_header(AVFormatContext *s) { AVIOContext *pb = s->pb; AVStream *st; unsigned int frame_count; unsigned int audio_frame_counter = 0; unsigned int video_frame_counter = 0; unsigned int back_size; unsigned short sound_rate; unsigned short rate; unsigned short channels; unsigned short def_sound_size; unsigned int signature; unsigned int pts_den = 11025; /* video only case */ unsigned int pts_num = 1103; unsigned int* chunk_offset = NULL; int* chunk_size = NULL; int* audio_size = NULL; int i; int ret = 0; avio_skip(pb,4); /* skip FORM tag */ back_size = avio_rl32(pb); /**< get size of the background frame */ signature = avio_rb32(pb); avio_skip(pb, 4); /* data size */ frame_count = avio_rl32(pb); /* disallow back_sizes and frame_counts that may lead to overflows later */ if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t)) return AVERROR_INVALIDDATA; avio_skip(pb, 2); /* encoding method */ sound_rate = avio_rl16(pb); rate = avio_rl16(pb); channels = avio_rl16(pb); def_sound_size = avio_rl16(pb); /** setup video stream */ st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RL2; st->codecpar->codec_tag = 0; /* no fourcc */ st->codecpar->width = 320; st->codecpar->height = 200; /** allocate and fill extradata */ st->codecpar->extradata_size = EXTRADATA1_SIZE; if(signature == RLV3_TAG && back_size > 0) st->codecpar->extradata_size += back_size; if(ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); /** setup audio stream if present */ if(sound_rate){ if (!channels || channels > 42) { av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels); return AVERROR_INVALIDDATA; } pts_num = def_sound_size; pts_den = rate; st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_PCM_U8; st->codecpar->codec_tag = 1; st->codecpar->channels = channels; st->codecpar->bits_per_coded_sample = 8; st->codecpar->sample_rate = rate; st->codecpar->bit_rate = st->codecpar->channels * st->codecpar->sample_rate * st->codecpar->bits_per_coded_sample; st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample / 8; avpriv_set_pts_info(st,32,1,rate); } avpriv_set_pts_info(s->streams[0], 32, pts_num, pts_den); chunk_size = av_malloc(frame_count * sizeof(uint32_t)); audio_size = av_malloc(frame_count * sizeof(uint32_t)); chunk_offset = av_malloc(frame_count * sizeof(uint32_t)); if(!chunk_size || !audio_size || !chunk_offset){ av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return AVERROR(ENOMEM); } /** read offset and size tables */ for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; chunk_size[i] = avio_rl32(pb); } for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; chunk_offset[i] = avio_rl32(pb); } for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; audio_size[i] = avio_rl32(pb) & 0xFFFF; } /** build the sample index */ for(i=0;i<frame_count;i++){ if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){ ret = AVERROR_INVALIDDATA; break; } if(sound_rate && audio_size[i]){ av_add_index_entry(s->streams[1], chunk_offset[i], audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME); audio_frame_counter += audio_size[i] / channels; } av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i], video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME); ++video_frame_counter; } av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return ret; }
167,776
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_gray_to_rgb_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_gray_to_rgb_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) == 0; }
173,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PaymentRequest::Show(bool is_user_gesture) { if (!client_.is_bound() || !binding_.is_bound()) { LOG(ERROR) << "Attempted Show(), but binding(s) missing."; OnConnectionTerminated(); return; } display_handle_ = display_manager_->TryShow(delegate_.get()); if (!display_handle_) { LOG(ERROR) << "A PaymentRequest UI is already showing"; journey_logger_.SetNotShown( JourneyLogger::NOT_SHOWN_REASON_CONCURRENT_REQUESTS); client_->OnError(mojom::PaymentErrorReason::ALREADY_SHOWING); OnConnectionTerminated(); return; } if (!delegate_->IsBrowserWindowActive()) { LOG(ERROR) << "Cannot show PaymentRequest UI in a background tab"; journey_logger_.SetNotShown(JourneyLogger::NOT_SHOWN_REASON_OTHER); client_->OnError(mojom::PaymentErrorReason::USER_CANCEL); OnConnectionTerminated(); return; } if (!state_) { AreRequestedMethodsSupportedCallback(false); return; } is_show_user_gesture_ = is_user_gesture; display_handle_->Show(this); state_->AreRequestedMethodsSupported( base::BindOnce(&PaymentRequest::AreRequestedMethodsSupportedCallback, weak_ptr_factory_.GetWeakPtr())); } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189
void PaymentRequest::Show(bool is_user_gesture) { if (!IsInitialized()) { log_.Error("Attempted show without initialization"); OnConnectionTerminated(); return; } if (is_show_called_) { log_.Error("Attempted show twice"); OnConnectionTerminated(); return; } is_show_called_ = true; display_handle_ = display_manager_->TryShow(delegate_.get()); if (!display_handle_) { log_.Error("A PaymentRequest UI is already showing"); journey_logger_.SetNotShown( JourneyLogger::NOT_SHOWN_REASON_CONCURRENT_REQUESTS); client_->OnError(mojom::PaymentErrorReason::ALREADY_SHOWING); OnConnectionTerminated(); return; } if (!delegate_->IsBrowserWindowActive()) { log_.Error("Cannot show PaymentRequest UI in a background tab"); journey_logger_.SetNotShown(JourneyLogger::NOT_SHOWN_REASON_OTHER); client_->OnError(mojom::PaymentErrorReason::USER_CANCEL); OnConnectionTerminated(); return; } if (!state_) { // SSL is not valid. Reject show with NotSupportedError, disconnect the // mojo pipe, and destroy this object. AreRequestedMethodsSupportedCallback(false); return; } is_show_user_gesture_ = is_user_gesture; display_handle_->Show(this); state_->AreRequestedMethodsSupported( base::BindOnce(&PaymentRequest::AreRequestedMethodsSupportedCallback, weak_ptr_factory_.GetWeakPtr())); }
173,087
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void XSSAuditor::Init(Document* document, XSSAuditorDelegate* auditor_delegate) { DCHECK(IsMainThread()); if (state_ != kUninitialized) return; state_ = kFilteringTokens; if (Settings* settings = document->GetSettings()) is_enabled_ = settings->GetXSSAuditorEnabled(); if (!is_enabled_) return; document_url_ = document->Url().Copy(); if (!document->GetFrame()) { is_enabled_ = false; return; } if (document_url_.IsEmpty()) { is_enabled_ = false; return; } if (document_url_.ProtocolIsData()) { is_enabled_ = false; return; } if (document->Encoding().IsValid()) encoding_ = document->Encoding(); if (DocumentLoader* document_loader = document->GetFrame()->Loader().GetDocumentLoader()) { const AtomicString& header_value = document_loader->GetResponse().HttpHeaderField( HTTPNames::X_XSS_Protection); String error_details; unsigned error_position = 0; String report_url; KURL xss_protection_report_url; ReflectedXSSDisposition xss_protection_header = ParseXSSProtectionHeader( header_value, error_details, error_position, report_url); if (xss_protection_header == kAllowReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled); else if (xss_protection_header == kFilterReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter); else if (xss_protection_header == kBlockReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock); else if (xss_protection_header == kReflectedXSSInvalid) UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid); did_send_valid_xss_protection_header_ = xss_protection_header != kReflectedXSSUnset && xss_protection_header != kReflectedXSSInvalid; if ((xss_protection_header == kFilterReflectedXSS || xss_protection_header == kBlockReflectedXSS) && !report_url.IsEmpty()) { xss_protection_report_url = document->CompleteURL(report_url); if (MixedContentChecker::IsMixedContent(document->GetSecurityOrigin(), xss_protection_report_url)) { error_details = "insecure reporting URL for secure page"; xss_protection_header = kReflectedXSSInvalid; xss_protection_report_url = KURL(); } } if (xss_protection_header == kReflectedXSSInvalid) { document->AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Error parsing header X-XSS-Protection: " + header_value + ": " + error_details + " at character position " + String::Format("%u", error_position) + ". The default protections will be applied.")); } xss_protection_ = xss_protection_header; if (xss_protection_ == kReflectedXSSInvalid || xss_protection_ == kReflectedXSSUnset) { xss_protection_ = kBlockReflectedXSS; } if (auditor_delegate) auditor_delegate->SetReportURL(xss_protection_report_url.Copy()); EncodedFormData* http_body = document_loader->GetRequest().HttpBody(); if (http_body && !http_body->IsEmpty()) http_body_as_string_ = http_body->FlattenToString(); } SetEncoding(encoding_); } Commit Message: Restrict the xss audit report URL to same origin BUG=441275 [email protected],[email protected] Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d Reviewed-on: https://chromium-review.googlesource.com/768367 Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Mike West <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#516666} CWE ID: CWE-79
void XSSAuditor::Init(Document* document, XSSAuditorDelegate* auditor_delegate) { DCHECK(IsMainThread()); if (state_ != kUninitialized) return; state_ = kFilteringTokens; if (Settings* settings = document->GetSettings()) is_enabled_ = settings->GetXSSAuditorEnabled(); if (!is_enabled_) return; document_url_ = document->Url().Copy(); if (!document->GetFrame()) { is_enabled_ = false; return; } if (document_url_.IsEmpty()) { is_enabled_ = false; return; } if (document_url_.ProtocolIsData()) { is_enabled_ = false; return; } if (document->Encoding().IsValid()) encoding_ = document->Encoding(); if (DocumentLoader* document_loader = document->GetFrame()->Loader().GetDocumentLoader()) { const AtomicString& header_value = document_loader->GetResponse().HttpHeaderField( HTTPNames::X_XSS_Protection); String error_details; unsigned error_position = 0; String report_url; KURL xss_protection_report_url; ReflectedXSSDisposition xss_protection_header = ParseXSSProtectionHeader( header_value, error_details, error_position, report_url); if (xss_protection_header == kAllowReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled); else if (xss_protection_header == kFilterReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter); else if (xss_protection_header == kBlockReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock); else if (xss_protection_header == kReflectedXSSInvalid) UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid); did_send_valid_xss_protection_header_ = xss_protection_header != kReflectedXSSUnset && xss_protection_header != kReflectedXSSInvalid; if ((xss_protection_header == kFilterReflectedXSS || xss_protection_header == kBlockReflectedXSS) && !report_url.IsEmpty()) { xss_protection_report_url = document->CompleteURL(report_url); if (!SecurityOrigin::Create(xss_protection_report_url) ->IsSameSchemeHostPort(document->GetSecurityOrigin())) { error_details = "reporting URL is not same scheme, host, and port as page"; xss_protection_header = kReflectedXSSInvalid; xss_protection_report_url = KURL(); } if (MixedContentChecker::IsMixedContent(document->GetSecurityOrigin(), xss_protection_report_url)) { error_details = "insecure reporting URL for secure page"; xss_protection_header = kReflectedXSSInvalid; xss_protection_report_url = KURL(); } } if (xss_protection_header == kReflectedXSSInvalid) { document->AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Error parsing header X-XSS-Protection: " + header_value + ": " + error_details + " at character position " + String::Format("%u", error_position) + ". The default protections will be applied.")); } xss_protection_ = xss_protection_header; if (xss_protection_ == kReflectedXSSInvalid || xss_protection_ == kReflectedXSSUnset) { xss_protection_ = kBlockReflectedXSS; } if (auditor_delegate) auditor_delegate->SetReportURL(xss_protection_report_url.Copy()); EncodedFormData* http_body = document_loader->GetRequest().HttpBody(); if (http_body && !http_body->IsEmpty()) http_body_as_string_ = http_body->FlattenToString(); } SetEncoding(encoding_); }
172,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int pppol2tp_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int val; int err; if (level != SOL_PPPOL2TP) return udp_prot.setsockopt(sk, level, optname, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get session context from the socket */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_setsockopt(sk, session, optname, val); err = 0; end_put_sess: sock_put(sk); end: return err; } Commit Message: net/l2tp: don't fall back on UDP [get|set]sockopt The l2tp [get|set]sockopt() code has fallen back to the UDP functions for socket option levels != SOL_PPPOL2TP since day one, but that has never actually worked, since the l2tp socket isn't an inet socket. As David Miller points out: "If we wanted this to work, it'd have to look up the tunnel and then use tunnel->sk, but I wonder how useful that would be" Since this can never have worked so nobody could possibly have depended on that functionality, just remove the broken code and return -EINVAL. Reported-by: Sasha Levin <[email protected]> Acked-by: James Chapman <[email protected]> Acked-by: David Miller <[email protected]> Cc: Phil Turnbull <[email protected]> Cc: Vegard Nossum <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static int pppol2tp_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int val; int err; if (level != SOL_PPPOL2TP) return -EINVAL; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get session context from the socket */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_setsockopt(sk, session, optname, val); err = 0; end_put_sess: sock_put(sk); end: return err; }
166,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeRenderProcessObserver::OnControlMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess, OnSetIsIncognitoProcess) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities) IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup) #if defined(USE_TCMALLOC) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetTcmallocHeapProfiling, OnSetTcmallocHeapProfiling) IPC_MESSAGE_HANDLER(ChromeViewMsg_WriteTcmallocHeapProfile, OnWriteTcmallocHeapProfile) #endif IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats, OnGetCacheResourceStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules, OnSetContentSettingRules) IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer, OnToggleWebKitSharedTimer) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Disable tcmalloc profile files. BUG=154983 [email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChromeRenderProcessObserver::OnControlMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess, OnSetIsIncognitoProcess) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities) IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup) IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats, OnGetCacheResourceStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules, OnSetContentSettingRules) IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer, OnToggleWebKitSharedTimer) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; }
170,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static SharedMemorySupport DoQuerySharedMemorySupport(Display* dpy) { int dummy; Bool pixmaps_supported; if (!XShmQueryVersion(dpy, &dummy, &dummy, &pixmaps_supported)) return SHARED_MEMORY_NONE; #if defined(OS_FREEBSD) int allow_removed; size_t length = sizeof(allow_removed); if ((sysctlbyname("kern.ipc.shm_allow_removed", &allow_removed, &length, NULL, 0) < 0) || allow_removed < 1) { return SHARED_MEMORY_NONE; } #endif int shmkey = shmget(IPC_PRIVATE, 1, 0666); if (shmkey == -1) return SHARED_MEMORY_NONE; void* address = shmat(shmkey, NULL, 0); shmctl(shmkey, IPC_RMID, NULL); XShmSegmentInfo shminfo; memset(&shminfo, 0, sizeof(shminfo)); shminfo.shmid = shmkey; gdk_error_trap_push(); bool result = XShmAttach(dpy, &shminfo); XSync(dpy, False); if (gdk_error_trap_pop()) result = false; shmdt(address); if (!result) return SHARED_MEMORY_NONE; XShmDetach(dpy, &shminfo); return pixmaps_supported ? SHARED_MEMORY_PIXMAP : SHARED_MEMORY_PUTIMAGE; } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
static SharedMemorySupport DoQuerySharedMemorySupport(Display* dpy) { int dummy; Bool pixmaps_supported; if (!XShmQueryVersion(dpy, &dummy, &dummy, &pixmaps_supported)) return SHARED_MEMORY_NONE; #if defined(OS_FREEBSD) int allow_removed; size_t length = sizeof(allow_removed); if ((sysctlbyname("kern.ipc.shm_allow_removed", &allow_removed, &length, NULL, 0) < 0) || allow_removed < 1) { return SHARED_MEMORY_NONE; } #endif int shmkey = shmget(IPC_PRIVATE, 1, 0600); if (shmkey == -1) { LOG(WARNING) << "Failed to get shared memory segment."; return SHARED_MEMORY_NONE; } else { VLOG(1) << "Got shared memory segment " << shmkey; } void* address = shmat(shmkey, NULL, 0); shmctl(shmkey, IPC_RMID, NULL); XShmSegmentInfo shminfo; memset(&shminfo, 0, sizeof(shminfo)); shminfo.shmid = shmkey; gdk_error_trap_push(); bool result = XShmAttach(dpy, &shminfo); if (result) VLOG(1) << "X got shared memory segment " << shmkey; else LOG(WARNING) << "X failed to attach to shared memory segment " << shmkey; XSync(dpy, False); if (gdk_error_trap_pop()) result = false; shmdt(address); if (!result) { LOG(WARNING) << "X failed to attach to shared memory segment " << shmkey; return SHARED_MEMORY_NONE; } VLOG(1) << "X attached to shared memory segment " << shmkey; XShmDetach(dpy, &shminfo); return pixmaps_supported ? SHARED_MEMORY_PIXMAP : SHARED_MEMORY_PUTIMAGE; }
171,594
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } Commit Message: Fix for bug #72790 and bug #72799 CWE ID: CWE-476
static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } }
166,949
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LogoService::GetLogo(LogoCallbacks callbacks) { if (!template_url_service_) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider(); if (!template_url) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); GURL logo_url; if (command_line->HasSwitch(switches::kSearchProviderLogoURL)) { logo_url = GURL( command_line->GetSwitchValueASCII(switches::kSearchProviderLogoURL)); } else { #if defined(OS_ANDROID) logo_url = template_url->logo_url(); #endif } GURL base_url; GURL doodle_url; const bool is_google = template_url->url_ref().HasGoogleBaseURLs( template_url_service_->search_terms_data()); if (is_google) { base_url = GURL(template_url_service_->search_terms_data().GoogleBaseURLValue()); doodle_url = search_provider_logos::GetGoogleDoodleURL(base_url); } else if (base::FeatureList::IsEnabled(features::kThirdPartyDoodles)) { if (command_line->HasSwitch(switches::kThirdPartyDoodleURL)) { doodle_url = GURL( command_line->GetSwitchValueASCII(switches::kThirdPartyDoodleURL)); } else { std::string override_url = base::GetFieldTrialParamValueByFeature( features::kThirdPartyDoodles, features::kThirdPartyDoodlesOverrideUrlParam); if (!override_url.empty()) { doodle_url = GURL(override_url); } else { doodle_url = template_url->doodle_url(); } } base_url = doodle_url.GetOrigin(); } if (!logo_url.is_valid() && !doodle_url.is_valid()) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const bool use_fixed_logo = !doodle_url.is_valid(); if (!logo_tracker_) { std::unique_ptr<LogoCache> logo_cache = std::move(logo_cache_for_test_); if (!logo_cache) { logo_cache = std::make_unique<LogoCache>(cache_directory_); } std::unique_ptr<base::Clock> clock = std::move(clock_for_test_); if (!clock) { clock = std::make_unique<base::DefaultClock>(); } logo_tracker_ = std::make_unique<LogoTracker>( request_context_getter_, std::make_unique<LogoDelegateImpl>(std::move(image_decoder_)), std::move(logo_cache), std::move(clock)); } if (use_fixed_logo) { logo_tracker_->SetServerAPI( logo_url, base::Bind(&search_provider_logos::ParseFixedLogoResponse), base::Bind(&search_provider_logos::UseFixedLogoUrl)); } else if (is_google) { logo_tracker_->SetServerAPI( doodle_url, search_provider_logos::GetGoogleParseLogoResponseCallback(base_url), search_provider_logos::GetGoogleAppendQueryparamsCallback( use_gray_background_)); } else { logo_tracker_->SetServerAPI( doodle_url, base::Bind(&search_provider_logos::GoogleNewParseLogoResponse, base_url), base::Bind(&search_provider_logos::GoogleNewAppendQueryparamsToLogoURL, use_gray_background_)); } logo_tracker_->GetLogo(std::move(callbacks)); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void LogoService::GetLogo(LogoCallbacks callbacks) {
171,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < sizeof(struct eth_header)) { l2_hdr->iov_len = 0; return false; } l2_hdr->iov_len = sizeof(struct eth_header); switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) { case ETH_P_VLAN: l2_hdr->iov_len += sizeof(struct vlan_header); break; case ETH_P_DVLAN: l2_hdr->iov_len += 2 * sizeof(struct vlan_header); break; } if (bytes_read < l2_hdr->iov_len) { l2_hdr->iov_len = 0; return false; } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); switch (l3_proto) { case ETH_P_IP: l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, sizeof(struct ip_header)); if (bytes_read < sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; } Commit Message: CWE ID: CWE-119
static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < sizeof(struct eth_header)) { l2_hdr->iov_len = 0; return false; } l2_hdr->iov_len = sizeof(struct eth_header); switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) { case ETH_P_VLAN: l2_hdr->iov_len += sizeof(struct vlan_header); break; case ETH_P_DVLAN: l2_hdr->iov_len += 2 * sizeof(struct vlan_header); break; } if (bytes_read < l2_hdr->iov_len) { l2_hdr->iov_len = 0; return false; } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); switch (l3_proto) { case ETH_P_IP: l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, sizeof(struct ip_header)); if (bytes_read < sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); if(l3_hdr->iov_len < sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; }
164,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info, size_t* gc_info_index_slot) { DCHECK(gc_info); DCHECK(gc_info_index_slot); DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, ()); MutexLocker locker(mutex); if (*gc_info_index_slot) return; int index = ++gc_info_index_; size_t gc_info_index = static_cast<size_t>(index); CHECK(gc_info_index < GCInfoTable::kMaxIndex); if (gc_info_index >= gc_info_table_size_) Resize(); g_gc_info_table[gc_info_index] = gc_info; ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info, size_t* gc_info_index_slot) { DCHECK(gc_info); DCHECK(gc_info_index_slot); // Ensuring a new index involves current index adjustment as well // as potentially resizing the table, both operations that require // a lock. MutexLocker locker(table_mutex_); if (*gc_info_index_slot) return; int index = ++current_index_; size_t gc_info_index = static_cast<size_t>(index); CHECK(gc_info_index < GCInfoTable::kMaxIndex); if (current_index_ >= limit_) Resize(); table_[gc_info_index] = gc_info; ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index); }
173,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gimp_write_and_read_file (Gimp *gimp, gboolean with_unusual_stuff, gboolean compat_paths, gboolean use_gimp_2_8_features) { GimpImage *image; GimpImage *loaded_image; GimpPlugInProcedure *proc; gchar *filename; GFile *file; /* Create the image */ image = gimp_create_mainimage (gimp, with_unusual_stuff, compat_paths, use_gimp_2_8_features); /* Assert valid state */ gimp_assert_mainimage (image, with_unusual_stuff, compat_paths, use_gimp_2_8_features); /* Write to file */ filename = g_build_filename (g_get_tmp_dir (), "gimp-test.xcf", NULL); file = g_file_new_for_path (filename); g_free (filename); proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager, GIMP_FILE_PROCEDURE_GROUP_SAVE, file, NULL /*error*/); file_save (gimp, image, NULL /*progress*/, file, proc, GIMP_RUN_NONINTERACTIVE, FALSE /*change_saved_state*/, FALSE /*export_backward*/, FALSE /*export_forward*/, NULL /*error*/); /* Load from file */ loaded_image = gimp_test_load_image (image->gimp, file); /* Assert on the loaded file. If success, it means that there is no * significant information loss when we wrote the image to a file * and loaded it again */ gimp_assert_mainimage (loaded_image, with_unusual_stuff, compat_paths, use_gimp_2_8_features); g_file_delete (file, NULL, NULL); g_object_unref (file); } Commit Message: Issue #1689: create unique temporary file with g_file_open_tmp(). Not sure this is really solving the issue reported, which is that `g_get_tmp_dir()` uses environment variables (yet as g_file_open_tmp() uses g_get_tmp_dir()…). But at least g_file_open_tmp() should create unique temporary files, which prevents overriding existing files (which is most likely the only real attack possible here, or at least the only one I can think of unless some weird vulnerabilities exist in glib). CWE ID: CWE-20
gimp_write_and_read_file (Gimp *gimp, gboolean with_unusual_stuff, gboolean compat_paths, gboolean use_gimp_2_8_features) { GimpImage *image; GimpImage *loaded_image; GimpPlugInProcedure *proc; gchar *filename = NULL; gint file_handle; GFile *file; /* Create the image */ image = gimp_create_mainimage (gimp, with_unusual_stuff, compat_paths, use_gimp_2_8_features); /* Assert valid state */ gimp_assert_mainimage (image, with_unusual_stuff, compat_paths, use_gimp_2_8_features); /* Write to file */ file_handle = g_file_open_tmp ("gimp-test-XXXXXX.xcf", &filename, NULL); g_assert (file_handle != -1); close (file_handle); file = g_file_new_for_path (filename); g_free (filename); proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager, GIMP_FILE_PROCEDURE_GROUP_SAVE, file, NULL /*error*/); file_save (gimp, image, NULL /*progress*/, file, proc, GIMP_RUN_NONINTERACTIVE, FALSE /*change_saved_state*/, FALSE /*export_backward*/, FALSE /*export_forward*/, NULL /*error*/); /* Load from file */ loaded_image = gimp_test_load_image (image->gimp, file); /* Assert on the loaded file. If success, it means that there is no * significant information loss when we wrote the image to a file * and loaded it again */ gimp_assert_mainimage (loaded_image, with_unusual_stuff, compat_paths, use_gimp_2_8_features); g_file_delete (file, NULL, NULL); g_object_unref (file); }
169,187
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const { return x >= frameLeft && x <= frameRight && y >= frameTop && y <= frameBottom; } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264
bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const { return x >= frameLeft && x < frameRight && y >= frameTop && y < frameBottom; }
174,169
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FoFiType1C::convertToType0(char *psName, int *codeMap, int nCodes, FoFiOutputFunc outputFunc, void *outputStream) { int *cidMap; Type1CIndex subrIdx; Type1CIndexVal val; int nCIDs; GooString *buf; Type1CEexecBuf eb; GBool ok; int fd, i, j, k; if (codeMap) { nCIDs = nCodes; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCodes; ++i) { if (codeMap[i] >= 0 && codeMap[i] < nGlyphs) { cidMap[i] = codeMap[i]; } else { cidMap[i] = -1; } } } else if (topDict.firstOp == 0x0c1e) { nCIDs = 0; for (i = 0; i < nGlyphs && i < charsetLength; ++i) { if (charset[i] >= nCIDs) { nCIDs = charset[i] + 1; } } cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = -1; } for (i = 0; i < nGlyphs && i < charsetLength; ++i) { cidMap[charset[i]] = i; } } else { nCIDs = nGlyphs; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = i; } } if (privateDicts) { for (i = 0; i < nCIDs; i += 256) { fd = 0; if (fdSelect) { for (j = i==0 ? 1 : 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { fd = fdSelect[cidMap[i+j]]; break; } } } (*outputFunc)(outputStream, "16 dict begin\n", 14); (*outputFunc)(outputStream, "/FontName /", 11); delete buf; (*outputFunc)(outputStream, "/FontType 1 def\n", 16); if (privateDicts[fd].hasFontMatrix) { buf = GooString::format("/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\n", privateDicts[fd].fontMatrix[0], privateDicts[fd].fontMatrix[1], privateDicts[fd].fontMatrix[2], privateDicts[fd].fontMatrix[3], privateDicts[fd].fontMatrix[4], privateDicts[fd].fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else if (topDict.hasFontMatrix) { (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30); } else { (*outputFunc)(outputStream, "/FontMatrix [0.001 0 0 0.001 0 0] def\n", 38); } buf = GooString::format("/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] def\n", topDict.fontBBox[0], topDict.fontBBox[1], topDict.fontBBox[2], topDict.fontBBox[3]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; buf = GooString::format("/PaintType {0:d} def\n", topDict.paintType); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; if (topDict.paintType != 0) { buf = GooString::format("/StrokeWidth {0:.4g} def\n", topDict.strokeWidth); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "/Encoding 256 array\n", 20); for (j = 0; j < 256 && i+j < nCIDs; ++j) { buf = GooString::format("dup {0:d} /c{1:02x} put\n", j, j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } if (j < 256) { buf = GooString::format("{0:d} 1 255 {{ 1 index exch /.notdef put }} for\n", j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "readonly def\n", 13); (*outputFunc)(outputStream, "currentdict end\n", 16); (*outputFunc)(outputStream, "currentfile eexec\n", 18); eb.outputFunc = outputFunc; eb.outputStream = outputStream; eb.ascii = gTrue; eb.r1 = 55665; eb.line = 0; eexecWrite(&eb, "\x83\xca\x73\xd5"); eexecWrite(&eb, "dup /Private 32 dict dup begin\n"); eexecWrite(&eb, "/RD {string currentfile exch readstring pop}" " executeonly def\n"); eexecWrite(&eb, "/ND {noaccess def} executeonly def\n"); eexecWrite(&eb, "/NP {noaccess put} executeonly def\n"); eexecWrite(&eb, "/MinFeature {16 16} def\n"); eexecWrite(&eb, "/password 5839 def\n"); if (privateDicts[fd].nBlueValues) { eexecWrite(&eb, "/BlueValues ["); for (k = 0; k < privateDicts[fd].nBlueValues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].blueValues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nOtherBlues) { eexecWrite(&eb, "/OtherBlues ["); for (k = 0; k < privateDicts[fd].nOtherBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].otherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nFamilyBlues) { eexecWrite(&eb, "/FamilyBlues ["); for (k = 0; k < privateDicts[fd].nFamilyBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].familyBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nFamilyOtherBlues) { eexecWrite(&eb, "/FamilyOtherBlues ["); for (k = 0; k < privateDicts[fd].nFamilyOtherBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].familyOtherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].blueScale != 0.039625) { buf = GooString::format("/BlueScale {0:.4g} def\n", privateDicts[fd].blueScale); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueShift != 7) { buf = GooString::format("/BlueShift {0:d} def\n", privateDicts[fd].blueShift); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueFuzz != 1) { buf = GooString::format("/BlueFuzz {0:d} def\n", privateDicts[fd].blueFuzz); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdHW) { buf = GooString::format("/StdHW [{0:.4g}] def\n", privateDicts[fd].stdHW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdVW) { buf = GooString::format("/StdVW [{0:.4g}] def\n", privateDicts[fd].stdVW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].nStemSnapH) { eexecWrite(&eb, "/StemSnapH ["); for (k = 0; k < privateDicts[fd].nStemSnapH; ++k) { buf = GooString::format("{0:s}{1:.4g}", k > 0 ? " " : "", privateDicts[fd].stemSnapH[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nStemSnapV) { eexecWrite(&eb, "/StemSnapV ["); for (k = 0; k < privateDicts[fd].nStemSnapV; ++k) { buf = GooString::format("{0:s}{1:.4g}", k > 0 ? " " : "", privateDicts[fd].stemSnapV[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].hasForceBold) { buf = GooString::format("/ForceBold {0:s} def\n", privateDicts[fd].forceBold ? "true" : "false"); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].forceBoldThreshold != 0) { buf = GooString::format("/ForceBoldThreshold {0:.4g} def\n", privateDicts[fd].forceBoldThreshold); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].languageGroup != 0) { buf = GooString::format("/LanguageGroup {0:d} def\n", privateDicts[fd].languageGroup); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].expansionFactor != 0.06) { buf = GooString::format("/ExpansionFactor {0:.4g} def\n", privateDicts[fd].expansionFactor); eexecWrite(&eb, buf->getCString()); delete buf; } ok = gTrue; getIndex(privateDicts[fd].subrsOffset, &subrIdx, &ok); if (!ok) { subrIdx.pos = -1; } eexecWrite(&eb, "2 index /CharStrings 256 dict dup begin\n"); ok = gTrue; getIndexVal(&charStringsIdx, 0, &val, &ok); if (ok) { eexecCvtGlyph(&eb, ".notdef", val.pos, val.len, &subrIdx, &privateDicts[fd]); } for (j = 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { ok = gTrue; getIndexVal(&charStringsIdx, cidMap[i+j], &val, &ok); if (ok) { buf = GooString::format("c{0:02x}", j); eexecCvtGlyph(&eb, buf->getCString(), val.pos, val.len, &subrIdx, &privateDicts[fd]); delete buf; } } } eexecWrite(&eb, "end\n"); eexecWrite(&eb, "end\n"); eexecWrite(&eb, "readonly put\n"); eexecWrite(&eb, "noaccess put\n"); eexecWrite(&eb, "dup /FontName get exch definefont pop\n"); eexecWrite(&eb, "mark currentfile closefile\n"); if (eb.line > 0) { (*outputFunc)(outputStream, "\n", 1); } for (j = 0; j < 8; ++j) { (*outputFunc)(outputStream, "0000000000000000000000000000000000000000000000000000000000000000\n", 65); } (*outputFunc)(outputStream, "cleartomark\n", 12); } } else { error(errSyntaxError, -1, "FoFiType1C::convertToType0 without privateDicts"); } (*outputFunc)(outputStream, "16 dict begin\n", 14); (*outputFunc)(outputStream, "/FontName /", 11); (*outputFunc)(outputStream, psName, strlen(psName)); (*outputFunc)(outputStream, " def\n", 5); (*outputFunc)(outputStream, "/FontType 0 def\n", 16); if (topDict.hasFontMatrix) { buf = GooString::format("/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\n", topDict.fontMatrix[0], topDict.fontMatrix[1], topDict.fontMatrix[2], topDict.fontMatrix[3], topDict.fontMatrix[4], topDict.fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else { (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30); } (*outputFunc)(outputStream, "/FMapType 2 def\n", 16); (*outputFunc)(outputStream, "/Encoding [\n", 12); for (i = 0; i < nCIDs; i += 256) { buf = GooString::format("{0:d}\n", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "] def\n", 6); (*outputFunc)(outputStream, "/FDepVector [\n", 14); for (i = 0; i < nCIDs; i += 256) { (*outputFunc)(outputStream, "/", 1); (*outputFunc)(outputStream, psName, strlen(psName)); buf = GooString::format("_{0:02x} findfont\n", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "] def\n", 6); (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40); gfree(cidMap); } Commit Message: CWE ID: CWE-125
void FoFiType1C::convertToType0(char *psName, int *codeMap, int nCodes, FoFiOutputFunc outputFunc, void *outputStream) { int *cidMap; Type1CIndex subrIdx; Type1CIndexVal val; int nCIDs; GooString *buf; Type1CEexecBuf eb; GBool ok; int fd, i, j, k; if (codeMap) { nCIDs = nCodes; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCodes; ++i) { if (codeMap[i] >= 0 && codeMap[i] < nGlyphs) { cidMap[i] = codeMap[i]; } else { cidMap[i] = -1; } } } else if (topDict.firstOp == 0x0c1e) { nCIDs = 0; for (i = 0; i < nGlyphs && i < charsetLength; ++i) { if (charset[i] >= nCIDs) { nCIDs = charset[i] + 1; } } cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = -1; } for (i = 0; i < nGlyphs && i < charsetLength; ++i) { cidMap[charset[i]] = i; } } else { nCIDs = nGlyphs; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = i; } } if (privateDicts) { for (i = 0; i < nCIDs; i += 256) { fd = 0; if (fdSelect) { for (j = i==0 ? 1 : 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { fd = fdSelect[cidMap[i+j]]; break; } } } if (fd >= nFDs) continue; (*outputFunc)(outputStream, "16 dict begin\n", 14); (*outputFunc)(outputStream, "/FontName /", 11); delete buf; (*outputFunc)(outputStream, "/FontType 1 def\n", 16); if (privateDicts[fd].hasFontMatrix) { buf = GooString::format("/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\n", privateDicts[fd].fontMatrix[0], privateDicts[fd].fontMatrix[1], privateDicts[fd].fontMatrix[2], privateDicts[fd].fontMatrix[3], privateDicts[fd].fontMatrix[4], privateDicts[fd].fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else if (topDict.hasFontMatrix) { (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30); } else { (*outputFunc)(outputStream, "/FontMatrix [0.001 0 0 0.001 0 0] def\n", 38); } buf = GooString::format("/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] def\n", topDict.fontBBox[0], topDict.fontBBox[1], topDict.fontBBox[2], topDict.fontBBox[3]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; buf = GooString::format("/PaintType {0:d} def\n", topDict.paintType); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; if (topDict.paintType != 0) { buf = GooString::format("/StrokeWidth {0:.4g} def\n", topDict.strokeWidth); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "/Encoding 256 array\n", 20); for (j = 0; j < 256 && i+j < nCIDs; ++j) { buf = GooString::format("dup {0:d} /c{1:02x} put\n", j, j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } if (j < 256) { buf = GooString::format("{0:d} 1 255 {{ 1 index exch /.notdef put }} for\n", j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "readonly def\n", 13); (*outputFunc)(outputStream, "currentdict end\n", 16); (*outputFunc)(outputStream, "currentfile eexec\n", 18); eb.outputFunc = outputFunc; eb.outputStream = outputStream; eb.ascii = gTrue; eb.r1 = 55665; eb.line = 0; eexecWrite(&eb, "\x83\xca\x73\xd5"); eexecWrite(&eb, "dup /Private 32 dict dup begin\n"); eexecWrite(&eb, "/RD {string currentfile exch readstring pop}" " executeonly def\n"); eexecWrite(&eb, "/ND {noaccess def} executeonly def\n"); eexecWrite(&eb, "/NP {noaccess put} executeonly def\n"); eexecWrite(&eb, "/MinFeature {16 16} def\n"); eexecWrite(&eb, "/password 5839 def\n"); if (privateDicts[fd].nBlueValues) { eexecWrite(&eb, "/BlueValues ["); for (k = 0; k < privateDicts[fd].nBlueValues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].blueValues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nOtherBlues) { eexecWrite(&eb, "/OtherBlues ["); for (k = 0; k < privateDicts[fd].nOtherBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].otherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nFamilyBlues) { eexecWrite(&eb, "/FamilyBlues ["); for (k = 0; k < privateDicts[fd].nFamilyBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].familyBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nFamilyOtherBlues) { eexecWrite(&eb, "/FamilyOtherBlues ["); for (k = 0; k < privateDicts[fd].nFamilyOtherBlues; ++k) { buf = GooString::format("{0:s}{1:d}", k > 0 ? " " : "", privateDicts[fd].familyOtherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].blueScale != 0.039625) { buf = GooString::format("/BlueScale {0:.4g} def\n", privateDicts[fd].blueScale); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueShift != 7) { buf = GooString::format("/BlueShift {0:d} def\n", privateDicts[fd].blueShift); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueFuzz != 1) { buf = GooString::format("/BlueFuzz {0:d} def\n", privateDicts[fd].blueFuzz); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdHW) { buf = GooString::format("/StdHW [{0:.4g}] def\n", privateDicts[fd].stdHW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdVW) { buf = GooString::format("/StdVW [{0:.4g}] def\n", privateDicts[fd].stdVW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].nStemSnapH) { eexecWrite(&eb, "/StemSnapH ["); for (k = 0; k < privateDicts[fd].nStemSnapH; ++k) { buf = GooString::format("{0:s}{1:.4g}", k > 0 ? " " : "", privateDicts[fd].stemSnapH[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].nStemSnapV) { eexecWrite(&eb, "/StemSnapV ["); for (k = 0; k < privateDicts[fd].nStemSnapV; ++k) { buf = GooString::format("{0:s}{1:.4g}", k > 0 ? " " : "", privateDicts[fd].stemSnapV[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, "] def\n"); } if (privateDicts[fd].hasForceBold) { buf = GooString::format("/ForceBold {0:s} def\n", privateDicts[fd].forceBold ? "true" : "false"); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].forceBoldThreshold != 0) { buf = GooString::format("/ForceBoldThreshold {0:.4g} def\n", privateDicts[fd].forceBoldThreshold); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].languageGroup != 0) { buf = GooString::format("/LanguageGroup {0:d} def\n", privateDicts[fd].languageGroup); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].expansionFactor != 0.06) { buf = GooString::format("/ExpansionFactor {0:.4g} def\n", privateDicts[fd].expansionFactor); eexecWrite(&eb, buf->getCString()); delete buf; } ok = gTrue; getIndex(privateDicts[fd].subrsOffset, &subrIdx, &ok); if (!ok) { subrIdx.pos = -1; } eexecWrite(&eb, "2 index /CharStrings 256 dict dup begin\n"); ok = gTrue; getIndexVal(&charStringsIdx, 0, &val, &ok); if (ok) { eexecCvtGlyph(&eb, ".notdef", val.pos, val.len, &subrIdx, &privateDicts[fd]); } for (j = 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { ok = gTrue; getIndexVal(&charStringsIdx, cidMap[i+j], &val, &ok); if (ok) { buf = GooString::format("c{0:02x}", j); eexecCvtGlyph(&eb, buf->getCString(), val.pos, val.len, &subrIdx, &privateDicts[fd]); delete buf; } } } eexecWrite(&eb, "end\n"); eexecWrite(&eb, "end\n"); eexecWrite(&eb, "readonly put\n"); eexecWrite(&eb, "noaccess put\n"); eexecWrite(&eb, "dup /FontName get exch definefont pop\n"); eexecWrite(&eb, "mark currentfile closefile\n"); if (eb.line > 0) { (*outputFunc)(outputStream, "\n", 1); } for (j = 0; j < 8; ++j) { (*outputFunc)(outputStream, "0000000000000000000000000000000000000000000000000000000000000000\n", 65); } (*outputFunc)(outputStream, "cleartomark\n", 12); } } else { error(errSyntaxError, -1, "FoFiType1C::convertToType0 without privateDicts"); } (*outputFunc)(outputStream, "16 dict begin\n", 14); (*outputFunc)(outputStream, "/FontName /", 11); (*outputFunc)(outputStream, psName, strlen(psName)); (*outputFunc)(outputStream, " def\n", 5); (*outputFunc)(outputStream, "/FontType 0 def\n", 16); if (topDict.hasFontMatrix) { buf = GooString::format("/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\n", topDict.fontMatrix[0], topDict.fontMatrix[1], topDict.fontMatrix[2], topDict.fontMatrix[3], topDict.fontMatrix[4], topDict.fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else { (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30); } (*outputFunc)(outputStream, "/FMapType 2 def\n", 16); (*outputFunc)(outputStream, "/Encoding [\n", 12); for (i = 0; i < nCIDs; i += 256) { buf = GooString::format("{0:d}\n", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "] def\n", 6); (*outputFunc)(outputStream, "/FDepVector [\n", 14); for (i = 0; i < nCIDs; i += 256) { (*outputFunc)(outputStream, "/", 1); (*outputFunc)(outputStream, psName, strlen(psName)); buf = GooString::format("_{0:02x} findfont\n", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, "] def\n", 6); (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40); gfree(cidMap); }
164,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitFrameMetadata( const H264SPS* sps, const H264PPS* pps, const H264DPB& dpb, const H264Picture::Vector& ref_pic_listp0, const H264Picture::Vector& ref_pic_listb0, const H264Picture::Vector& ref_pic_listb1, const scoped_refptr<H264Picture>& pic) { VAPictureParameterBufferH264 pic_param; memset(&pic_param, 0, sizeof(pic_param)); #define FROM_SPS_TO_PP(a) pic_param.a = sps->a #define FROM_SPS_TO_PP2(a, b) pic_param.b = sps->a FROM_SPS_TO_PP2(pic_width_in_mbs_minus1, picture_width_in_mbs_minus1); FROM_SPS_TO_PP2(pic_height_in_map_units_minus1, picture_height_in_mbs_minus1); FROM_SPS_TO_PP(bit_depth_luma_minus8); FROM_SPS_TO_PP(bit_depth_chroma_minus8); #undef FROM_SPS_TO_PP #undef FROM_SPS_TO_PP2 #define FROM_SPS_TO_PP_SF(a) pic_param.seq_fields.bits.a = sps->a #define FROM_SPS_TO_PP_SF2(a, b) pic_param.seq_fields.bits.b = sps->a FROM_SPS_TO_PP_SF(chroma_format_idc); FROM_SPS_TO_PP_SF2(separate_colour_plane_flag, residual_colour_transform_flag); FROM_SPS_TO_PP_SF(gaps_in_frame_num_value_allowed_flag); FROM_SPS_TO_PP_SF(frame_mbs_only_flag); FROM_SPS_TO_PP_SF(mb_adaptive_frame_field_flag); FROM_SPS_TO_PP_SF(direct_8x8_inference_flag); pic_param.seq_fields.bits.MinLumaBiPredSize8x8 = (sps->level_idc >= 31); FROM_SPS_TO_PP_SF(log2_max_frame_num_minus4); FROM_SPS_TO_PP_SF(pic_order_cnt_type); FROM_SPS_TO_PP_SF(log2_max_pic_order_cnt_lsb_minus4); FROM_SPS_TO_PP_SF(delta_pic_order_always_zero_flag); #undef FROM_SPS_TO_PP_SF #undef FROM_SPS_TO_PP_SF2 #define FROM_PPS_TO_PP(a) pic_param.a = pps->a FROM_PPS_TO_PP(pic_init_qp_minus26); FROM_PPS_TO_PP(pic_init_qs_minus26); FROM_PPS_TO_PP(chroma_qp_index_offset); FROM_PPS_TO_PP(second_chroma_qp_index_offset); #undef FROM_PPS_TO_PP #define FROM_PPS_TO_PP_PF(a) pic_param.pic_fields.bits.a = pps->a #define FROM_PPS_TO_PP_PF2(a, b) pic_param.pic_fields.bits.b = pps->a FROM_PPS_TO_PP_PF(entropy_coding_mode_flag); FROM_PPS_TO_PP_PF(weighted_pred_flag); FROM_PPS_TO_PP_PF(weighted_bipred_idc); FROM_PPS_TO_PP_PF(transform_8x8_mode_flag); pic_param.pic_fields.bits.field_pic_flag = 0; FROM_PPS_TO_PP_PF(constrained_intra_pred_flag); FROM_PPS_TO_PP_PF2(bottom_field_pic_order_in_frame_present_flag, pic_order_present_flag); FROM_PPS_TO_PP_PF(deblocking_filter_control_present_flag); FROM_PPS_TO_PP_PF(redundant_pic_cnt_present_flag); pic_param.pic_fields.bits.reference_pic_flag = pic->ref; #undef FROM_PPS_TO_PP_PF #undef FROM_PPS_TO_PP_PF2 pic_param.frame_num = pic->frame_num; InitVAPicture(&pic_param.CurrPic); FillVAPicture(&pic_param.CurrPic, pic); for (int i = 0; i < 16; ++i) InitVAPicture(&pic_param.ReferenceFrames[i]); FillVARefFramesFromDPB(dpb, pic_param.ReferenceFrames, arraysize(pic_param.ReferenceFrames)); pic_param.num_ref_frames = sps->max_num_ref_frames; if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, sizeof(pic_param), &pic_param)) return false; VAIQMatrixBufferH264 iq_matrix_buf; memset(&iq_matrix_buf, 0, sizeof(iq_matrix_buf)); if (pps->pic_scaling_matrix_present_flag) { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][kZigzagScan4x4[j]] = pps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][kZigzagScan8x8[j]] = pps->scaling_list8x8[i][j]; } } else { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][kZigzagScan4x4[j]] = sps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][kZigzagScan8x8[j]] = sps->scaling_list8x8[i][j]; } } return vaapi_wrapper_->SubmitBuffer(VAIQMatrixBufferType, sizeof(iq_matrix_buf), &iq_matrix_buf); } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitFrameMetadata( const H264SPS* sps, const H264PPS* pps, const H264DPB& dpb, const H264Picture::Vector& ref_pic_listp0, const H264Picture::Vector& ref_pic_listb0, const H264Picture::Vector& ref_pic_listb1, const scoped_refptr<H264Picture>& pic) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); VAPictureParameterBufferH264 pic_param; memset(&pic_param, 0, sizeof(pic_param)); #define FROM_SPS_TO_PP(a) pic_param.a = sps->a #define FROM_SPS_TO_PP2(a, b) pic_param.b = sps->a FROM_SPS_TO_PP2(pic_width_in_mbs_minus1, picture_width_in_mbs_minus1); FROM_SPS_TO_PP2(pic_height_in_map_units_minus1, picture_height_in_mbs_minus1); FROM_SPS_TO_PP(bit_depth_luma_minus8); FROM_SPS_TO_PP(bit_depth_chroma_minus8); #undef FROM_SPS_TO_PP #undef FROM_SPS_TO_PP2 #define FROM_SPS_TO_PP_SF(a) pic_param.seq_fields.bits.a = sps->a #define FROM_SPS_TO_PP_SF2(a, b) pic_param.seq_fields.bits.b = sps->a FROM_SPS_TO_PP_SF(chroma_format_idc); FROM_SPS_TO_PP_SF2(separate_colour_plane_flag, residual_colour_transform_flag); FROM_SPS_TO_PP_SF(gaps_in_frame_num_value_allowed_flag); FROM_SPS_TO_PP_SF(frame_mbs_only_flag); FROM_SPS_TO_PP_SF(mb_adaptive_frame_field_flag); FROM_SPS_TO_PP_SF(direct_8x8_inference_flag); pic_param.seq_fields.bits.MinLumaBiPredSize8x8 = (sps->level_idc >= 31); FROM_SPS_TO_PP_SF(log2_max_frame_num_minus4); FROM_SPS_TO_PP_SF(pic_order_cnt_type); FROM_SPS_TO_PP_SF(log2_max_pic_order_cnt_lsb_minus4); FROM_SPS_TO_PP_SF(delta_pic_order_always_zero_flag); #undef FROM_SPS_TO_PP_SF #undef FROM_SPS_TO_PP_SF2 #define FROM_PPS_TO_PP(a) pic_param.a = pps->a FROM_PPS_TO_PP(pic_init_qp_minus26); FROM_PPS_TO_PP(pic_init_qs_minus26); FROM_PPS_TO_PP(chroma_qp_index_offset); FROM_PPS_TO_PP(second_chroma_qp_index_offset); #undef FROM_PPS_TO_PP #define FROM_PPS_TO_PP_PF(a) pic_param.pic_fields.bits.a = pps->a #define FROM_PPS_TO_PP_PF2(a, b) pic_param.pic_fields.bits.b = pps->a FROM_PPS_TO_PP_PF(entropy_coding_mode_flag); FROM_PPS_TO_PP_PF(weighted_pred_flag); FROM_PPS_TO_PP_PF(weighted_bipred_idc); FROM_PPS_TO_PP_PF(transform_8x8_mode_flag); pic_param.pic_fields.bits.field_pic_flag = 0; FROM_PPS_TO_PP_PF(constrained_intra_pred_flag); FROM_PPS_TO_PP_PF2(bottom_field_pic_order_in_frame_present_flag, pic_order_present_flag); FROM_PPS_TO_PP_PF(deblocking_filter_control_present_flag); FROM_PPS_TO_PP_PF(redundant_pic_cnt_present_flag); pic_param.pic_fields.bits.reference_pic_flag = pic->ref; #undef FROM_PPS_TO_PP_PF #undef FROM_PPS_TO_PP_PF2 pic_param.frame_num = pic->frame_num; InitVAPicture(&pic_param.CurrPic); FillVAPicture(&pic_param.CurrPic, pic); for (int i = 0; i < 16; ++i) InitVAPicture(&pic_param.ReferenceFrames[i]); FillVARefFramesFromDPB(dpb, pic_param.ReferenceFrames, arraysize(pic_param.ReferenceFrames)); pic_param.num_ref_frames = sps->max_num_ref_frames; if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, sizeof(pic_param), &pic_param)) return false; VAIQMatrixBufferH264 iq_matrix_buf; memset(&iq_matrix_buf, 0, sizeof(iq_matrix_buf)); if (pps->pic_scaling_matrix_present_flag) { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][kZigzagScan4x4[j]] = pps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][kZigzagScan8x8[j]] = pps->scaling_list8x8[i][j]; } } else { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][kZigzagScan4x4[j]] = sps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][kZigzagScan8x8[j]] = sps->scaling_list8x8[i][j]; } } return vaapi_wrapper_->SubmitBuffer(VAIQMatrixBufferType, sizeof(iq_matrix_buf), &iq_matrix_buf); }
172,811
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_set_end(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { UNUSED(this) UNUSED(that) UNUSED(pp) UNUSED(pi) } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_set_end(PNG_CONST image_transform *this, image_transform_set_end(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { UNUSED(this) UNUSED(that) UNUSED(pp) UNUSED(pi) }
173,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PasswordAutofillAgent::TryToShowTouchToFill( const WebFormControlElement& control_element) { const WebInputElement* element = ToWebInputElement(&control_element); if (!element || (!base::Contains(web_input_to_password_info_, *element) && !base::Contains(password_to_username_, *element))) { return false; } if (was_touch_to_fill_ui_shown_) return false; was_touch_to_fill_ui_shown_ = true; GetPasswordManagerDriver()->ShowTouchToFill(); return true; } Commit Message: [Android][TouchToFill] Use FindPasswordInfoForElement for triggering Use for TouchToFill the same triggering logic that is used for regular suggestions. Bug: 1010233 Change-Id: I111d4eac4ce94dd94b86097b6b6c98e08875e11a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1834230 Commit-Queue: Boris Sazonov <[email protected]> Reviewed-by: Vadym Doroshenko <[email protected]> Cr-Commit-Position: refs/heads/master@{#702058} CWE ID: CWE-125
bool PasswordAutofillAgent::TryToShowTouchToFill( const WebFormControlElement& control_element) { const WebInputElement* element = ToWebInputElement(&control_element); WebInputElement username_element; WebInputElement password_element; PasswordInfo* password_info = nullptr; if (!element || !FindPasswordInfoForElement(*element, &username_element, &password_element, &password_info)) { return false; } if (was_touch_to_fill_ui_shown_) return false; was_touch_to_fill_ui_shown_ = true; GetPasswordManagerDriver()->ShowTouchToFill(); return true; }
172,407
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaStreamManager::CancelRequest(int render_process_id, int render_frame_id, int page_request_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (const LabeledDeviceRequest& labeled_request : requests_) { DeviceRequest* const request = labeled_request.second; if (request->requesting_process_id == render_process_id && request->requesting_frame_id == render_frame_id && request->page_request_id == page_request_id) { CancelRequest(labeled_request.first); return; } } } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void MediaStreamManager::CancelRequest(int render_process_id, int render_frame_id, int requester_id, int page_request_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (const LabeledDeviceRequest& labeled_request : requests_) { DeviceRequest* const request = labeled_request.second; if (request->requesting_process_id == render_process_id && request->requesting_frame_id == render_frame_id && request->requester_id == requester_id && request->page_request_id == page_request_id) { CancelRequest(labeled_request.first); return; } } }
173,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: TabsCustomBindings::TabsCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("OpenChannelToTab", base::Bind(&TabsCustomBindings::OpenChannelToTab, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
TabsCustomBindings::TabsCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("OpenChannelToTab", "tabs", base::Bind(&TabsCustomBindings::OpenChannelToTab, base::Unretained(this))); }
172,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start) { int res, bytes, i, indexes, index_bytes, ids; long long *index, start, end; struct squashfs_xattr_table id_table; TRACE("read_xattrs_from_disk\n"); if(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK) return SQUASHFS_INVALID_BLK; /* * Read xattr id table, containing start of xattr metadata and the * number of xattrs in the file system */ res = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table), &id_table); if(res == 0) return 0; SQUASHFS_INSWAP_XATTR_TABLE(&id_table); if(flag) { /* * id_table.xattr_table_start stores the start of the compressed xattr * * metadata blocks. This by definition is also the end of the previous * filesystem table - the id lookup table. */ *table_start = id_table.xattr_table_start; return id_table.xattr_ids; } /* * Allocate and read the index to the xattr id table metadata * blocks */ ids = id_table.xattr_ids; xattr_table_start = id_table.xattr_table_start; index_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids); indexes = SQUASHFS_XATTR_BLOCKS(ids); index = malloc(index_bytes); if(index == NULL) MEM_ERROR(); res = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table), index_bytes, index); if(res ==0) goto failed1; SQUASHFS_INSWAP_LONG_LONGS(index, indexes); /* * Allocate enough space for the uncompressed xattr id table, and * read and decompress it */ bytes = SQUASHFS_XATTR_BYTES(ids); xattr_ids = malloc(bytes); if(xattr_ids == NULL) MEM_ERROR(); for(i = 0; i < indexes; i++) { int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE : bytes & (SQUASHFS_METADATA_SIZE - 1); int length = read_block(fd, index[i], NULL, expected, ((unsigned char *) xattr_ids) + (i * SQUASHFS_METADATA_SIZE)); TRACE("Read xattr id table block %d, from 0x%llx, length " "%d\n", i, index[i], length); if(length == 0) { ERROR("Failed to read xattr id table block %d, " "from 0x%llx, length %d\n", i, index[i], length); goto failed2; } } /* * Read and decompress the xattr metadata * * Note the first xattr id table metadata block is immediately after * the last xattr metadata block, so we can use index[0] to work out * the end of the xattr metadata */ start = xattr_table_start; end = index[0]; for(i = 0; start < end; i++) { int length; xattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE); if(xattrs == NULL) MEM_ERROR(); /* store mapping from location of compressed block in fs -> * location of uncompressed block in memory */ save_xattr_block(start, i * SQUASHFS_METADATA_SIZE); length = read_block(fd, start, &start, 0, ((unsigned char *) xattrs) + (i * SQUASHFS_METADATA_SIZE)); TRACE("Read xattr block %d, length %d\n", i, length); if(length == 0) { ERROR("Failed to read xattr block %d\n", i); goto failed3; } /* * If this is not the last metadata block in the xattr metadata * then it should be SQUASHFS_METADATA_SIZE in size. * Note, we can't use expected in read_block() above for this * because we don't know if this is the last block until * after reading. */ if(start != end && length != SQUASHFS_METADATA_SIZE) { ERROR("Xattr block %d should be %d bytes in length, " "it is %d bytes\n", i, SQUASHFS_METADATA_SIZE, length); goto failed3; } } /* swap if necessary the xattr id entries */ for(i = 0; i < ids; i++) SQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]); free(index); return ids; failed3: free(xattrs); failed2: free(xattr_ids); failed1: free(index); return 0; } Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6 Add more filesystem table sanity checks to Unsquashfs-4 and also properly fix CVE-2015-4645 and CVE-2015-4646. The CVEs were raised due to Unsquashfs having variable oveflow and stack overflow in a number of vulnerable functions. The suggested patch only "fixed" one such function and fixed it badly, and so it was buggy and introduced extra bugs! The suggested patch was not only buggy, but, it used the essentially wrong approach too. It was "fixing" the symptom but not the cause. The symptom is wrong values causing overflow, the cause is filesystem corruption. This corruption should be detected and the filesystem rejected *before* trying to allocate memory. This patch applies the following fixes: 1. The filesystem super-block tables are checked, and the values must match across the filesystem. This will trap corrupted filesystems created by Mksquashfs. 2. The maximum (theorectical) size the filesystem tables could grow to, were analysed, and some variables were increased from int to long long. This analysis has been added as comments. 3. Stack allocation was removed, and a shared buffer (which is checked and increased as necessary) is used to read the table indexes. Signed-off-by: Phillip Lougher <[email protected]> CWE ID: CWE-190
int read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start) { /* * Note on overflow limits: * Size of ids (id_table.xattr_ids) is 2^32 (unsigned int) * Max size of bytes is 2^32*16 or 2^36 * Max indexes is (2^32*16)/8K or 2^23 * Max index_bytes is ((2^32*16)/8K)*8 or 2^26 or 64M */ int res, i, indexes, index_bytes; unsigned int ids; long long bytes; long long *index, start, end; struct squashfs_xattr_table id_table; TRACE("read_xattrs_from_disk\n"); if(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK) return SQUASHFS_INVALID_BLK; /* * Read xattr id table, containing start of xattr metadata and the * number of xattrs in the file system */ res = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table), &id_table); if(res == 0) return 0; SQUASHFS_INSWAP_XATTR_TABLE(&id_table); /* * Compute index table values */ ids = id_table.xattr_ids; xattr_table_start = id_table.xattr_table_start; index_bytes = SQUASHFS_XATTR_BLOCK_BYTES((long long) ids); indexes = SQUASHFS_XATTR_BLOCKS((long long) ids); /* * The size of the index table (index_bytes) should match the * table start and end points */ if(index_bytes != (sBlk->bytes_used - (sBlk->xattr_id_table_start + sizeof(id_table)))) { ERROR("read_xattrs_from_disk: Bad xattr_ids count in super block\n"); return 0; } /* * id_table.xattr_table_start stores the start of the compressed xattr * metadata blocks. This by definition is also the end of the previous * filesystem table - the id lookup table. */ if(table_start != NULL) *table_start = id_table.xattr_table_start; /* * If flag is set then return once we've read the above * table_start. That value is necessary for sanity checking, * but we don't actually want to extract the xattrs, and so * stop here. */ if(flag) return id_table.xattr_ids; /* * Allocate and read the index to the xattr id table metadata * blocks */ index = malloc(index_bytes); if(index == NULL) MEM_ERROR(); res = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table), index_bytes, index); if(res ==0) goto failed1; SQUASHFS_INSWAP_LONG_LONGS(index, indexes); /* * Allocate enough space for the uncompressed xattr id table, and * read and decompress it */ bytes = SQUASHFS_XATTR_BYTES((long long) ids); xattr_ids = malloc(bytes); if(xattr_ids == NULL) MEM_ERROR(); for(i = 0; i < indexes; i++) { int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE : bytes & (SQUASHFS_METADATA_SIZE - 1); int length = read_block(fd, index[i], NULL, expected, ((unsigned char *) xattr_ids) + ((long long) i * SQUASHFS_METADATA_SIZE)); TRACE("Read xattr id table block %d, from 0x%llx, length " "%d\n", i, index[i], length); if(length == 0) { ERROR("Failed to read xattr id table block %d, " "from 0x%llx, length %d\n", i, index[i], length); goto failed2; } } /* * Read and decompress the xattr metadata * * Note the first xattr id table metadata block is immediately after * the last xattr metadata block, so we can use index[0] to work out * the end of the xattr metadata */ start = xattr_table_start; end = index[0]; for(i = 0; start < end; i++) { int length; xattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE); if(xattrs == NULL) MEM_ERROR(); /* store mapping from location of compressed block in fs -> * location of uncompressed block in memory */ save_xattr_block(start, i * SQUASHFS_METADATA_SIZE); length = read_block(fd, start, &start, 0, ((unsigned char *) xattrs) + (i * SQUASHFS_METADATA_SIZE)); TRACE("Read xattr block %d, length %d\n", i, length); if(length == 0) { ERROR("Failed to read xattr block %d\n", i); goto failed3; } /* * If this is not the last metadata block in the xattr metadata * then it should be SQUASHFS_METADATA_SIZE in size. * Note, we can't use expected in read_block() above for this * because we don't know if this is the last block until * after reading. */ if(start != end && length != SQUASHFS_METADATA_SIZE) { ERROR("Xattr block %d should be %d bytes in length, " "it is %d bytes\n", i, SQUASHFS_METADATA_SIZE, length); goto failed3; } } /* swap if necessary the xattr id entries */ for(i = 0; i < ids; i++) SQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]); free(index); return ids; failed3: free(xattrs); failed2: free(xattr_ids); failed1: free(index); return 0; }
168,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int _yr_scan_verify_re_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { CALLBACK_ARGS callback_args; RE_EXEC_FUNC exec; int forward_matches = -1; int backward_matches = -1; int flags = 0; if (STRING_IS_GREEDY_REGEXP(ac_match->string)) flags |= RE_FLAGS_GREEDY; if (STRING_IS_NO_CASE(ac_match->string)) flags |= RE_FLAGS_NO_CASE; if (STRING_IS_DOT_ALL(ac_match->string)) flags |= RE_FLAGS_DOT_ALL; if (STRING_IS_FAST_REGEXP(ac_match->string)) exec = yr_re_fast_exec; else exec = yr_re_exec; if (STRING_IS_ASCII(ac_match->string)) { forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset > 0 ? flags | RE_FLAGS_NOT_AT_START : flags, NULL, NULL); } if (STRING_IS_WIDE(ac_match->string) && forward_matches == -1) { flags |= RE_FLAGS_WIDE; forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset > 0 ? flags | RE_FLAGS_NOT_AT_START : flags, NULL, NULL); } switch(forward_matches) { case -1: return ERROR_SUCCESS; case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } if (forward_matches == 0 && ac_match->backward_code == NULL) return ERROR_SUCCESS; callback_args.string = ac_match->string; callback_args.context = context; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(ac_match->string); if (ac_match->backward_code != NULL) { backward_matches = exec( ac_match->backward_code, data + offset, offset, flags | RE_FLAGS_BACKWARDS | RE_FLAGS_EXHAUSTIVE, _yr_scan_match_callback, (void*) &callback_args); switch(backward_matches) { case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } } else { FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); } return ERROR_SUCCESS; } Commit Message: Fix issue #646 (#648) * Fix issue #646 and some edge cases with wide regexps using \b and \B * Rename function IS_WORD_CHAR to _yr_re_is_word_char CWE ID: CWE-125
int _yr_scan_verify_re_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { CALLBACK_ARGS callback_args; RE_EXEC_FUNC exec; int forward_matches = -1; int backward_matches = -1; int flags = 0; if (STRING_IS_GREEDY_REGEXP(ac_match->string)) flags |= RE_FLAGS_GREEDY; if (STRING_IS_NO_CASE(ac_match->string)) flags |= RE_FLAGS_NO_CASE; if (STRING_IS_DOT_ALL(ac_match->string)) flags |= RE_FLAGS_DOT_ALL; if (STRING_IS_FAST_REGEXP(ac_match->string)) exec = yr_re_fast_exec; else exec = yr_re_exec; if (STRING_IS_ASCII(ac_match->string)) { forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset, flags, NULL, NULL); } if (STRING_IS_WIDE(ac_match->string) && forward_matches == -1) { flags |= RE_FLAGS_WIDE; forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset, flags, NULL, NULL); } switch(forward_matches) { case -1: return ERROR_SUCCESS; case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } if (forward_matches == 0 && ac_match->backward_code == NULL) return ERROR_SUCCESS; callback_args.string = ac_match->string; callback_args.context = context; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(ac_match->string); if (ac_match->backward_code != NULL) { backward_matches = exec( ac_match->backward_code, data + offset, data_size - offset, offset, flags | RE_FLAGS_BACKWARDS | RE_FLAGS_EXHAUSTIVE, _yr_scan_match_callback, (void*) &callback_args); switch(backward_matches) { case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } } else { FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); } return ERROR_SUCCESS; }
168,204