instruction
stringclasses
1 value
input
stringlengths
222
112k
output
stringlengths
21
113k
__index_level_0__
int64
15
30k
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.
Code: void install_local_socket(asocket* s) { adb_mutex_lock(&socket_list_lock); s->id = local_socket_next_id++; if (local_socket_next_id == 0) { local_socket_next_id = 1; } insert_local_socket(s, &local_socket_list); adb_mutex_unlock(&socket_list_lock); } Commit Message: adb: switch the socket list mutex to a recursive_mutex. sockets.cpp was branching on whether a socket close function was local_socket_close in order to avoid a potential deadlock if the socket list lock was held while closing a peer socket. Bug: http://b/28347842 Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3 (cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa) CWE ID: CWE-264
void install_local_socket(asocket* s) { std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); s->id = local_socket_next_id++; if (local_socket_next_id == 0) { fatal("local socket id overflow"); } insert_local_socket(s, &local_socket_list); }
5,394
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.
Code: void PrintPreviewMessageHandler::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { int page_number = params.page_number; if (page_number < FIRST_PAGE_INDEX || !params.data_size) return; PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; scoped_refptr<base::RefCountedBytes> data_bytes = GetDataFromHandle(params.metafile_data_handle, params.data_size); DCHECK(data_bytes); print_preview_ui->SetPrintPreviewDataForIndex(page_number, std::move(data_bytes)); print_preview_ui->OnDidPreviewPage(page_number, params.preview_request_id); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. TBR=jzfeng@chromium.org BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <weili@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
void PrintPreviewMessageHandler::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { int page_number = params.page_number; if (page_number < FIRST_PAGE_INDEX || !params.data_size) return; PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; if (IsOopifEnabled() && print_preview_ui->source_is_modifiable()) { auto* client = PrintCompositeClient::FromWebContents(web_contents()); DCHECK(client); // Use utility process to convert skia metafile to pdf. client->DoComposite( params.metafile_data_handle, params.data_size, base::BindOnce(&PrintPreviewMessageHandler::OnCompositePdfPageDone, weak_ptr_factory_.GetWeakPtr(), params.page_number, params.preview_request_id)); } else { NotifyUIPreviewPageReady( page_number, params.preview_request_id, GetDataFromHandle(params.metafile_data_handle, params.data_size)); } }
15,860
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.
Code: void NormalPageArena::promptlyFreeObject(HeapObjectHeader* header) { ASSERT(!getThreadState()->sweepForbidden()); ASSERT(header->checkHeader()); Address address = reinterpret_cast<Address>(header); Address payload = header->payload(); size_t size = header->size(); size_t payloadSize = header->payloadSize(); ASSERT(size > 0); ASSERT(pageFromObject(address) == findPageFromAddress(address)); { ThreadState::SweepForbiddenScope forbiddenScope(getThreadState()); header->finalize(payload, payloadSize); if (address + size == m_currentAllocationPoint) { m_currentAllocationPoint = address; setRemainingAllocationSize(m_remainingAllocationSize + size); SET_MEMORY_INACCESSIBLE(address, size); return; } SET_MEMORY_INACCESSIBLE(payload, payloadSize); header->markPromptlyFreed(); } m_promptlyFreedSize += size; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
void NormalPageArena::promptlyFreeObject(HeapObjectHeader* header) { ASSERT(!getThreadState()->sweepForbidden()); header->checkHeader(); Address address = reinterpret_cast<Address>(header); Address payload = header->payload(); size_t size = header->size(); size_t payloadSize = header->payloadSize(); ASSERT(size > 0); ASSERT(pageFromObject(address) == findPageFromAddress(address)); { ThreadState::SweepForbiddenScope forbiddenScope(getThreadState()); header->finalize(payload, payloadSize); if (address + size == m_currentAllocationPoint) { m_currentAllocationPoint = address; setRemainingAllocationSize(m_remainingAllocationSize + size); SET_MEMORY_INACCESSIBLE(address, size); return; } SET_MEMORY_INACCESSIBLE(payload, payloadSize); header->markPromptlyFreed(); } m_promptlyFreedSize += size; }
13,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.
Code: static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); unsigned int mss; unsigned int unfrag_ip6hlen, unfrag_len; struct frag_hdr *fptr; u8 *packet_start, *prevhdr; u8 nexthdr; u8 frag_hdr_sz = sizeof(struct frag_hdr); int offset; __wsum csum; int tnl_hlen; mss = skb_shinfo(skb)->gso_size; if (unlikely(skb->len <= mss)) goto out; if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) { /* Packet is from an untrusted source, reset gso_segs. */ int type = skb_shinfo(skb)->gso_type; if (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY | SKB_GSO_UDP_TUNNEL | SKB_GSO_GRE | SKB_GSO_IPIP | SKB_GSO_SIT | SKB_GSO_MPLS) || !(type & (SKB_GSO_UDP)))) goto out; skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss); segs = NULL; goto out; } if (skb->encapsulation && skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL) segs = skb_udp_tunnel_segment(skb, features); else { /* Do software UFO. Complete and fill in the UDP checksum as HW cannot * do checksum of UDP packets sent as multiple IP fragments. */ offset = skb_checksum_start_offset(skb); csum = skb_checksum(skb, offset, skb->len - offset, 0); offset += skb->csum_offset; *(__sum16 *)(skb->data + offset) = csum_fold(csum); skb->ip_summed = CHECKSUM_NONE; /* Check if there is enough headroom to insert fragment header. */ tnl_hlen = skb_tnl_header_len(skb); if (skb_headroom(skb) < (tnl_hlen + frag_hdr_sz)) { if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz)) goto out; } /* Find the unfragmentable header and shift it left by frag_hdr_sz * bytes to insert fragment header. */ unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; *prevhdr = NEXTHDR_FRAGMENT; unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) + unfrag_ip6hlen + tnl_hlen; packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset; memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len); SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz; skb->mac_header -= frag_hdr_sz; skb->network_header -= frag_hdr_sz; fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen); fptr->nexthdr = nexthdr; fptr->reserved = 0; ipv6_select_ident(fptr, (struct rt6_info *)skb_dst(skb)); /* Fragment the skb. ipv6 header and the remaining fields of the * fragment header are updated in ipv6_gso_segment() */ segs = skb_segment(skb, features); } out: return segs; } Commit Message: ipv6: fix headroom calculation in udp6_ufo_fragment Commit 1e2bd517c108816220f262d7954b697af03b5f9c ("udp6: Fix udp fragmentation for tunnel traffic.") changed the calculation if there is enough space to include a fragment header in the skb from a skb->mac_header dervived one to skb_headroom. Because we already peeled off the skb to transport_header this is wrong. Change this back to check if we have enough room before the mac_header. This fixes a panic Saran Neti reported. He used the tbf scheduler which skb_gso_segments the skb. The offsets get negative and we panic in memcpy because the skb was erroneously not expanded at the head. Reported-by: Saran Neti <Saran.Neti@telus.com> Cc: Pravin B Shelar <pshelar@nicira.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-189
static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); unsigned int mss; unsigned int unfrag_ip6hlen, unfrag_len; struct frag_hdr *fptr; u8 *packet_start, *prevhdr; u8 nexthdr; u8 frag_hdr_sz = sizeof(struct frag_hdr); int offset; __wsum csum; int tnl_hlen; mss = skb_shinfo(skb)->gso_size; if (unlikely(skb->len <= mss)) goto out; if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) { /* Packet is from an untrusted source, reset gso_segs. */ int type = skb_shinfo(skb)->gso_type; if (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY | SKB_GSO_UDP_TUNNEL | SKB_GSO_GRE | SKB_GSO_IPIP | SKB_GSO_SIT | SKB_GSO_MPLS) || !(type & (SKB_GSO_UDP)))) goto out; skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss); segs = NULL; goto out; } if (skb->encapsulation && skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL) segs = skb_udp_tunnel_segment(skb, features); else { /* Do software UFO. Complete and fill in the UDP checksum as HW cannot * do checksum of UDP packets sent as multiple IP fragments. */ offset = skb_checksum_start_offset(skb); csum = skb_checksum(skb, offset, skb->len - offset, 0); offset += skb->csum_offset; *(__sum16 *)(skb->data + offset) = csum_fold(csum); skb->ip_summed = CHECKSUM_NONE; /* Check if there is enough headroom to insert fragment header. */ tnl_hlen = skb_tnl_header_len(skb); if (skb->mac_header < (tnl_hlen + frag_hdr_sz)) { if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz)) goto out; } /* Find the unfragmentable header and shift it left by frag_hdr_sz * bytes to insert fragment header. */ unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; *prevhdr = NEXTHDR_FRAGMENT; unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) + unfrag_ip6hlen + tnl_hlen; packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset; memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len); SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz; skb->mac_header -= frag_hdr_sz; skb->network_header -= frag_hdr_sz; fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen); fptr->nexthdr = nexthdr; fptr->reserved = 0; ipv6_select_ident(fptr, (struct rt6_info *)skb_dst(skb)); /* Fragment the skb. ipv6 header and the remaining fields of the * fragment header are updated in ipv6_gso_segment() */ segs = skb_segment(skb, features); } out: return segs; }
23,136
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.
Code: static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { memmove(s+j, s+qs, blen - qs); j += blen - qs; } buffer_string_set_length(b, j); return qs; } Commit Message: [core] fix abort in http-parseopts (fixes #2945) fix abort in server.http-parseopts with url-path-2f-decode enabled (thx stze) x-ref: "Security - SIGABRT during GET request handling with url-path-2f-decode enabled" https://redmine.lighttpd.net/issues/2945 CWE ID: CWE-190
static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { const int qslen = blen - qs; memmove(s+j, s+qs, (size_t)qslen); qs = j; j += qslen; } buffer_string_set_length(b, j); return qs; }
18,762
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.
Code: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (!mTimeToSample.empty() || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } return OK; } Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug 28076789. Detail: Before the original fix (Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the code allowed a time-to-sample table size to be 0. The change made in that fix disallowed such situation, which in fact should be allowed. This current patch allows it again while maintaining the security of the previous fix. Bug: 28288202 Bug: 28076789 Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295 CWE ID: CWE-20
status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mHasTimeToSample || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } mHasTimeToSample = true; return OK; }
11,521
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.
Code: IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() { if (g_idb_dispatcher_tls.Pointer()->Get()) return g_idb_dispatcher_tls.Pointer()->Get(); IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher; if (WorkerTaskRunner::Instance()->CurrentWorkerId()) webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher); return dispatcher; } Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created. This could happen if there are IDB objects that survive the call to didStopWorkerRunLoop. BUG=121734 TEST= Review URL: http://codereview.chromium.org/9999035 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() { if (g_idb_dispatcher_tls.Pointer()->Get() == HAS_BEEN_DELETED) { NOTREACHED() << "Re-instantiating TLS IndexedDBDispatcher."; g_idb_dispatcher_tls.Pointer()->Set(NULL); } if (g_idb_dispatcher_tls.Pointer()->Get()) return g_idb_dispatcher_tls.Pointer()->Get(); IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher; if (WorkerTaskRunner::Instance()->CurrentWorkerId()) webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher); return dispatcher; }
1,067
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.
Code: void ChromeMockRenderThread::OnDidGetPrintedPagesCount( int cookie, int number_pages) { if (printer_.get()) printer_->SetPrintedPagesCount(cookie, number_pages); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnDidGetPrintedPagesCount( int cookie, int number_pages) { printer_->SetPrintedPagesCount(cookie, number_pages); }
2,168
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.
Code: static int raw_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct net *net = sock_net(sk); struct ipcm_cookie ipc; struct rtable *rt = NULL; struct flowi4 fl4; int free = 0; __be32 daddr; __be32 saddr; u8 tos; int err; struct ip_options_data opt_copy; struct raw_frag_vec rfv; err = -EMSGSIZE; if (len > 0xFFFF) goto out; /* * Check the flags. */ err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */ goto out; /* compatibility */ /* * Get and verify the address. */ if (msg->msg_namelen) { DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name); err = -EINVAL; if (msg->msg_namelen < sizeof(*usin)) goto out; if (usin->sin_family != AF_INET) { pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n", __func__, current->comm); err = -EAFNOSUPPORT; if (usin->sin_family) goto out; } daddr = usin->sin_addr.s_addr; /* ANK: I did not forget to get protocol from port field. * I just do not know, who uses this weirdness. * IP_HDRINCL is much more convenient. */ } else { err = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; } ipc.sockc.tsflags = sk->sk_tsflags; ipc.addr = inet->inet_saddr; ipc.opt = NULL; ipc.tx_flags = 0; ipc.ttl = 0; ipc.tos = -1; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(sk, msg, &ipc, false); if (unlikely(err)) { kfree(ipc.opt); goto out; } if (ipc.opt) free = 1; } saddr = ipc.addr; ipc.addr = daddr; if (!ipc.opt) { struct ip_options_rcu *inet_opt; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt) { memcpy(&opt_copy, inet_opt, sizeof(*inet_opt) + inet_opt->opt.optlen); ipc.opt = &opt_copy.opt; } rcu_read_unlock(); } if (ipc.opt) { err = -EINVAL; /* Linux does not mangle headers on raw sockets, * so that IP options + IP_HDRINCL is non-sense. */ if (inet->hdrincl) goto done; if (ipc.opt->opt.srr) { if (!daddr) goto done; daddr = ipc.opt->opt.faddr; } } tos = get_rtconn_flags(&ipc, sk); if (msg->msg_flags & MSG_DONTROUTE) tos |= RTO_ONLINK; if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; } else if (!ipc.oif) ipc.oif = inet->uc_index; flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk) | (inet->hdrincl ? FLOWI_FLAG_KNOWN_NH : 0), daddr, saddr, 0, 0, sk->sk_uid); if (!inet->hdrincl) { rfv.msg = msg; rfv.hlen = 0; err = raw_probe_proto_opt(&rfv, &fl4); if (err) goto done; } security_sk_classify_flow(sk, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto done; } err = -EACCES; if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST)) goto done; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: if (inet->hdrincl) err = raw_send_hdrinc(sk, &fl4, msg, len, &rt, msg->msg_flags, &ipc.sockc); else { sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags); if (!ipc.addr) ipc.addr = fl4.daddr; lock_sock(sk); err = ip_append_data(sk, &fl4, raw_getfrag, &rfv, len, 0, &ipc, &rt, msg->msg_flags); if (err) ip_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) { err = ip_push_pending_frames(sk, &fl4); if (err == -ENOBUFS && !inet->recverr) err = 0; } release_sock(sk); } done: if (free) kfree(ipc.opt); ip_rt_put(rt); out: if (err < 0) return err; return len; do_confirm: if (msg->msg_flags & MSG_PROBE) dst_confirm_neigh(&rt->dst, &fl4.daddr); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } Commit Message: net: ipv4: fix for a race condition in raw_sendmsg inet->hdrincl is racy, and could lead to uninitialized stack pointer usage, so its value should be read only once. Fixes: c008ba5bdc9f ("ipv4: Avoid reading user iov twice after raw_probe_proto_opt") Signed-off-by: Mohamed Ghannam <simo.ghannam@gmail.com> Reviewed-by: Eric Dumazet <edumazet@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-362
static int raw_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct net *net = sock_net(sk); struct ipcm_cookie ipc; struct rtable *rt = NULL; struct flowi4 fl4; int free = 0; __be32 daddr; __be32 saddr; u8 tos; int err; struct ip_options_data opt_copy; struct raw_frag_vec rfv; int hdrincl; err = -EMSGSIZE; if (len > 0xFFFF) goto out; /* hdrincl should be READ_ONCE(inet->hdrincl) * but READ_ONCE() doesn't work with bit fields */ hdrincl = inet->hdrincl; /* * Check the flags. */ err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */ goto out; /* compatibility */ /* * Get and verify the address. */ if (msg->msg_namelen) { DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name); err = -EINVAL; if (msg->msg_namelen < sizeof(*usin)) goto out; if (usin->sin_family != AF_INET) { pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n", __func__, current->comm); err = -EAFNOSUPPORT; if (usin->sin_family) goto out; } daddr = usin->sin_addr.s_addr; /* ANK: I did not forget to get protocol from port field. * I just do not know, who uses this weirdness. * IP_HDRINCL is much more convenient. */ } else { err = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; } ipc.sockc.tsflags = sk->sk_tsflags; ipc.addr = inet->inet_saddr; ipc.opt = NULL; ipc.tx_flags = 0; ipc.ttl = 0; ipc.tos = -1; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(sk, msg, &ipc, false); if (unlikely(err)) { kfree(ipc.opt); goto out; } if (ipc.opt) free = 1; } saddr = ipc.addr; ipc.addr = daddr; if (!ipc.opt) { struct ip_options_rcu *inet_opt; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt) { memcpy(&opt_copy, inet_opt, sizeof(*inet_opt) + inet_opt->opt.optlen); ipc.opt = &opt_copy.opt; } rcu_read_unlock(); } if (ipc.opt) { err = -EINVAL; /* Linux does not mangle headers on raw sockets, * so that IP options + IP_HDRINCL is non-sense. */ if (hdrincl) goto done; if (ipc.opt->opt.srr) { if (!daddr) goto done; daddr = ipc.opt->opt.faddr; } } tos = get_rtconn_flags(&ipc, sk); if (msg->msg_flags & MSG_DONTROUTE) tos |= RTO_ONLINK; if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; } else if (!ipc.oif) ipc.oif = inet->uc_index; flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk) | (hdrincl ? FLOWI_FLAG_KNOWN_NH : 0), daddr, saddr, 0, 0, sk->sk_uid); if (!hdrincl) { rfv.msg = msg; rfv.hlen = 0; err = raw_probe_proto_opt(&rfv, &fl4); if (err) goto done; } security_sk_classify_flow(sk, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto done; } err = -EACCES; if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST)) goto done; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: if (hdrincl) err = raw_send_hdrinc(sk, &fl4, msg, len, &rt, msg->msg_flags, &ipc.sockc); else { sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags); if (!ipc.addr) ipc.addr = fl4.daddr; lock_sock(sk); err = ip_append_data(sk, &fl4, raw_getfrag, &rfv, len, 0, &ipc, &rt, msg->msg_flags); if (err) ip_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) { err = ip_push_pending_frames(sk, &fl4); if (err == -ENOBUFS && !inet->recverr) err = 0; } release_sock(sk); } done: if (free) kfree(ipc.opt); ip_rt_put(rt); out: if (err < 0) return err; return len; do_confirm: if (msg->msg_flags & MSG_PROBE) dst_confirm_neigh(&rt->dst, &fl4.daddr); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; }
7,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.
Code: OMX_ERRORTYPE omx_video::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr) { unsigned int index = 0; OMX_U8 *temp_buff ; if (bufferHdr == NULL || m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: free_input: Invalid bufferHdr[%p] or m_inp_mem_ptr[%p]", bufferHdr, m_inp_mem_ptr); return OMX_ErrorBadParameter; } index = bufferHdr - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr); #ifdef _ANDROID_ICS_ if (meta_mode_enable) { if (index < m_sInPortDef.nBufferCountActual) { memset(&meta_buffer_hdr[index], 0, sizeof(meta_buffer_hdr[index])); memset(&meta_buffers[index], 0, sizeof(meta_buffers[index])); } if (!mUseProxyColorFormat) return OMX_ErrorNone; else { c2d_conv.close(); opaque_buffer_hdr[index] = NULL; } } #endif if (index < m_sInPortDef.nBufferCountActual && !mUseProxyColorFormat && dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_LOW("ERROR: dev_free_buf() Failed for i/p buf"); } if (index < m_sInPortDef.nBufferCountActual && m_pInput_pmem) { if (m_pInput_pmem[index].fd > 0 && input_use_buffer == false) { DEBUG_PRINT_LOW("FreeBuffer:: i/p AllocateBuffer case"); if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); } else { free(m_pInput_pmem[index].buffer); } close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else if (m_pInput_pmem[index].fd > 0 && (input_use_buffer == true && m_use_input_pmem == OMX_FALSE)) { DEBUG_PRINT_LOW("FreeBuffer:: i/p Heap UseBuffer case"); if (dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_ERROR("ERROR: dev_free_buf() Failed for i/p buf"); } if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); } close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else { DEBUG_PRINT_ERROR("FreeBuffer:: fd is invalid or i/p PMEM UseBuffer case"); } } return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27903498 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVenc problem #3) CRs-Fixed: 1010088 Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3 CWE ID:
OMX_ERRORTYPE omx_video::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr) { unsigned int index = 0; OMX_U8 *temp_buff ; if (bufferHdr == NULL || m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: free_input: Invalid bufferHdr[%p] or m_inp_mem_ptr[%p]", bufferHdr, m_inp_mem_ptr); return OMX_ErrorBadParameter; } index = bufferHdr - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr); #ifdef _ANDROID_ICS_ if (meta_mode_enable) { if (index < m_sInPortDef.nBufferCountActual) { memset(&meta_buffer_hdr[index], 0, sizeof(meta_buffer_hdr[index])); memset(&meta_buffers[index], 0, sizeof(meta_buffers[index])); } if (!mUseProxyColorFormat) return OMX_ErrorNone; else { c2d_conv.close(); opaque_buffer_hdr[index] = NULL; } } #endif if (index < m_sInPortDef.nBufferCountActual && !mUseProxyColorFormat && dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_LOW("ERROR: dev_free_buf() Failed for i/p buf"); } if (index < m_sInPortDef.nBufferCountActual && m_pInput_pmem) { auto_lock l(m_lock); if (m_pInput_pmem[index].fd > 0 && input_use_buffer == false) { DEBUG_PRINT_LOW("FreeBuffer:: i/p AllocateBuffer case"); if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); } else { free(m_pInput_pmem[index].buffer); } m_pInput_pmem[index].buffer = NULL; close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else if (m_pInput_pmem[index].fd > 0 && (input_use_buffer == true && m_use_input_pmem == OMX_FALSE)) { DEBUG_PRINT_LOW("FreeBuffer:: i/p Heap UseBuffer case"); if (dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_ERROR("ERROR: dev_free_buf() Failed for i/p buf"); } if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); m_pInput_pmem[index].buffer = NULL; } close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else { DEBUG_PRINT_ERROR("FreeBuffer:: fd is invalid or i/p PMEM UseBuffer case"); } } return OMX_ErrorNone; }
20,316
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.
Code: long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) { assert(m_pos < 0); assert(m_pUnknownSize); #if 0 assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this const long long element_start = m_pUnknownSize->m_element_start; pos = -m_pos; assert(pos > element_start); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long element_size = -1; for (;;) { //determine cluster size if ((total >= 0) && (pos >= total)) { element_size = total - element_start; assert(element_size > 0); break; } if ((segment_stop >= 0) && (pos >= segment_stop)) { element_size = segment_stop - element_start; assert(element_size > 0); break; } if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) //error (or underflow) return static_cast<long>(id); if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { //Cluster ID or Cues ID element_size = pos - element_start; assert(element_size > 0); break; } #ifdef _DEBUG switch (id) { case 0x20: //BlockGroup case 0x23: //Simple Block case 0x67: //TimeCode case 0x2B: //PrevSize break; default: assert(false); break; } #endif pos += len; //consume ID (of sub-element) if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume size field of element if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not allowed for sub-elements if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird return E_FILE_FORMAT_INVALID; pos += size; //consume payload of sub-element assert((segment_stop < 0) || (pos <= segment_stop)); } //determine cluster size assert(element_size >= 0); m_pos = element_start + element_size; m_pUnknownSize = 0; return 2; //continue parsing #else const long status = m_pUnknownSize->Parse(pos, len); if (status < 0) // error or underflow return status; if (status == 0) // parsed a block return 2; // continue parsing assert(status > 0); // nothing left to parse of this cluster const long long start = m_pUnknownSize->m_element_start; const long long size = m_pUnknownSize->GetElementSize(); assert(size >= 0); pos = start + size; m_pos = pos; m_pUnknownSize = 0; return 2; // continue parsing #endif } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) { if (m_pos >= 0 || m_pUnknownSize == NULL) return E_PARSE_FAILED; const long status = m_pUnknownSize->Parse(pos, len); if (status < 0) // error or underflow return status; if (status == 0) // parsed a block return 2; // continue parsing const long long start = m_pUnknownSize->m_element_start; const long long size = m_pUnknownSize->GetElementSize(); if (size < 0) return E_FILE_FORMAT_INVALID; pos = start + size; m_pos = pos; m_pUnknownSize = 0; return 2; // continue parsing }
24,439
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.
Code: long vorbis_book_decodev_set(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j; if (!v) return -1; for(i=0;i<n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim;j++) a[i++]=v[j]; } }else{ int i,j; for(i=0;i<n;){ for (j=0;j<book->dim;j++) a[i++]=0; } } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
long vorbis_book_decodev_set(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j; if (!v) return -1; for(i=0;i<n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim && i < n;j++) a[i++]=v[j]; } }else{ int i,j; for(i=0;i<n;){ for (j=0;j<book->dim && i < n;j++) a[i++]=0; } } return 0; }
6,596
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.
Code: int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct rxrpc_skb_priv *sp; struct rxrpc_call *call = NULL, *continue_call = NULL; struct rxrpc_sock *rx = rxrpc_sk(sock->sk); struct sk_buff *skb; long timeo; int copy, ret, ullen, offset, copied = 0; u32 abort_code; DEFINE_WAIT(wait); _enter(",,,%zu,%d", len, flags); if (flags & (MSG_OOB | MSG_TRUNC)) return -EOPNOTSUPP; ullen = msg->msg_flags & MSG_CMSG_COMPAT ? 4 : sizeof(unsigned long); timeo = sock_rcvtimeo(&rx->sk, flags & MSG_DONTWAIT); msg->msg_flags |= MSG_MORE; lock_sock(&rx->sk); for (;;) { /* return immediately if a client socket has no outstanding * calls */ if (RB_EMPTY_ROOT(&rx->calls)) { if (copied) goto out; if (rx->sk.sk_state != RXRPC_SERVER_LISTENING) { release_sock(&rx->sk); if (continue_call) rxrpc_put_call(continue_call); return -ENODATA; } } /* get the next message on the Rx queue */ skb = skb_peek(&rx->sk.sk_receive_queue); if (!skb) { /* nothing remains on the queue */ if (copied && (msg->msg_flags & MSG_PEEK || timeo == 0)) goto out; /* wait for a message to turn up */ release_sock(&rx->sk); prepare_to_wait_exclusive(sk_sleep(&rx->sk), &wait, TASK_INTERRUPTIBLE); ret = sock_error(&rx->sk); if (ret) goto wait_error; if (skb_queue_empty(&rx->sk.sk_receive_queue)) { if (signal_pending(current)) goto wait_interrupted; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(&rx->sk), &wait); lock_sock(&rx->sk); continue; } peek_next_packet: sp = rxrpc_skb(skb); call = sp->call; ASSERT(call != NULL); _debug("next pkt %s", rxrpc_pkts[sp->hdr.type]); /* make sure we wait for the state to be updated in this call */ spin_lock_bh(&call->lock); spin_unlock_bh(&call->lock); if (test_bit(RXRPC_CALL_RELEASED, &call->flags)) { _debug("packet from released call"); if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); continue; } /* determine whether to continue last data receive */ if (continue_call) { _debug("maybe cont"); if (call != continue_call || skb->mark != RXRPC_SKB_MARK_DATA) { release_sock(&rx->sk); rxrpc_put_call(continue_call); _leave(" = %d [noncont]", copied); return copied; } } rxrpc_get_call(call); /* copy the peer address and timestamp */ if (!continue_call) { if (msg->msg_name && msg->msg_namelen > 0) memcpy(msg->msg_name, &call->conn->trans->peer->srx, sizeof(call->conn->trans->peer->srx)); sock_recv_ts_and_drops(msg, &rx->sk, skb); } /* receive the message */ if (skb->mark != RXRPC_SKB_MARK_DATA) goto receive_non_data_message; _debug("recvmsg DATA #%u { %d, %d }", ntohl(sp->hdr.seq), skb->len, sp->offset); if (!continue_call) { /* only set the control data once per recvmsg() */ ret = put_cmsg(msg, SOL_RXRPC, RXRPC_USER_CALL_ID, ullen, &call->user_call_ID); if (ret < 0) goto copy_error; ASSERT(test_bit(RXRPC_CALL_HAS_USERID, &call->flags)); } ASSERTCMP(ntohl(sp->hdr.seq), >=, call->rx_data_recv); ASSERTCMP(ntohl(sp->hdr.seq), <=, call->rx_data_recv + 1); call->rx_data_recv = ntohl(sp->hdr.seq); ASSERTCMP(ntohl(sp->hdr.seq), >, call->rx_data_eaten); offset = sp->offset; copy = skb->len - offset; if (copy > len - copied) copy = len - copied; if (skb->ip_summed == CHECKSUM_UNNECESSARY) { ret = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, copy); } else { ret = skb_copy_and_csum_datagram_iovec(skb, offset, msg->msg_iov); if (ret == -EINVAL) goto csum_copy_error; } if (ret < 0) goto copy_error; /* handle piecemeal consumption of data packets */ _debug("copied %d+%d", copy, copied); offset += copy; copied += copy; if (!(flags & MSG_PEEK)) sp->offset = offset; if (sp->offset < skb->len) { _debug("buffer full"); ASSERTCMP(copied, ==, len); break; } /* we transferred the whole data packet */ if (sp->hdr.flags & RXRPC_LAST_PACKET) { _debug("last"); if (call->conn->out_clientflag) { /* last byte of reply received */ ret = copied; goto terminal_message; } /* last bit of request received */ if (!(flags & MSG_PEEK)) { _debug("eat packet"); if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); } msg->msg_flags &= ~MSG_MORE; break; } /* move on to the next data message */ _debug("next"); if (!continue_call) continue_call = sp->call; else rxrpc_put_call(call); call = NULL; if (flags & MSG_PEEK) { _debug("peek next"); skb = skb->next; if (skb == (struct sk_buff *) &rx->sk.sk_receive_queue) break; goto peek_next_packet; } _debug("eat packet"); if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); } /* end of non-terminal data packet reception for the moment */ _debug("end rcv data"); out: release_sock(&rx->sk); if (call) rxrpc_put_call(call); if (continue_call) rxrpc_put_call(continue_call); _leave(" = %d [data]", copied); return copied; /* handle non-DATA messages such as aborts, incoming connections and * final ACKs */ receive_non_data_message: _debug("non-data"); if (skb->mark == RXRPC_SKB_MARK_NEW_CALL) { _debug("RECV NEW CALL"); ret = put_cmsg(msg, SOL_RXRPC, RXRPC_NEW_CALL, 0, &abort_code); if (ret < 0) goto copy_error; if (!(flags & MSG_PEEK)) { if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); } goto out; } ret = put_cmsg(msg, SOL_RXRPC, RXRPC_USER_CALL_ID, ullen, &call->user_call_ID); if (ret < 0) goto copy_error; ASSERT(test_bit(RXRPC_CALL_HAS_USERID, &call->flags)); switch (skb->mark) { case RXRPC_SKB_MARK_DATA: BUG(); case RXRPC_SKB_MARK_FINAL_ACK: ret = put_cmsg(msg, SOL_RXRPC, RXRPC_ACK, 0, &abort_code); break; case RXRPC_SKB_MARK_BUSY: ret = put_cmsg(msg, SOL_RXRPC, RXRPC_BUSY, 0, &abort_code); break; case RXRPC_SKB_MARK_REMOTE_ABORT: abort_code = call->abort_code; ret = put_cmsg(msg, SOL_RXRPC, RXRPC_ABORT, 4, &abort_code); break; case RXRPC_SKB_MARK_NET_ERROR: _debug("RECV NET ERROR %d", sp->error); abort_code = sp->error; ret = put_cmsg(msg, SOL_RXRPC, RXRPC_NET_ERROR, 4, &abort_code); break; case RXRPC_SKB_MARK_LOCAL_ERROR: _debug("RECV LOCAL ERROR %d", sp->error); abort_code = sp->error; ret = put_cmsg(msg, SOL_RXRPC, RXRPC_LOCAL_ERROR, 4, &abort_code); break; default: BUG(); break; } if (ret < 0) goto copy_error; terminal_message: _debug("terminal"); msg->msg_flags &= ~MSG_MORE; msg->msg_flags |= MSG_EOR; if (!(flags & MSG_PEEK)) { _net("free terminal skb %p", skb); if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); rxrpc_remove_user_ID(rx, call); } release_sock(&rx->sk); rxrpc_put_call(call); if (continue_call) rxrpc_put_call(continue_call); _leave(" = %d", ret); return ret; copy_error: _debug("copy error"); release_sock(&rx->sk); rxrpc_put_call(call); if (continue_call) rxrpc_put_call(continue_call); _leave(" = %d", ret); return ret; csum_copy_error: _debug("csum error"); release_sock(&rx->sk); if (continue_call) rxrpc_put_call(continue_call); rxrpc_kill_skb(skb); skb_kill_datagram(&rx->sk, skb, flags); rxrpc_put_call(call); return -EAGAIN; wait_interrupted: ret = sock_intr_errno(timeo); wait_error: finish_wait(sk_sleep(&rx->sk), &wait); if (continue_call) rxrpc_put_call(continue_call); if (copied) copied = ret; _leave(" = %d [waitfail %d]", copied, ret); return copied; } 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 <davem@davemloft.net> Suggested-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct rxrpc_skb_priv *sp; struct rxrpc_call *call = NULL, *continue_call = NULL; struct rxrpc_sock *rx = rxrpc_sk(sock->sk); struct sk_buff *skb; long timeo; int copy, ret, ullen, offset, copied = 0; u32 abort_code; DEFINE_WAIT(wait); _enter(",,,%zu,%d", len, flags); if (flags & (MSG_OOB | MSG_TRUNC)) return -EOPNOTSUPP; ullen = msg->msg_flags & MSG_CMSG_COMPAT ? 4 : sizeof(unsigned long); timeo = sock_rcvtimeo(&rx->sk, flags & MSG_DONTWAIT); msg->msg_flags |= MSG_MORE; lock_sock(&rx->sk); for (;;) { /* return immediately if a client socket has no outstanding * calls */ if (RB_EMPTY_ROOT(&rx->calls)) { if (copied) goto out; if (rx->sk.sk_state != RXRPC_SERVER_LISTENING) { release_sock(&rx->sk); if (continue_call) rxrpc_put_call(continue_call); return -ENODATA; } } /* get the next message on the Rx queue */ skb = skb_peek(&rx->sk.sk_receive_queue); if (!skb) { /* nothing remains on the queue */ if (copied && (msg->msg_flags & MSG_PEEK || timeo == 0)) goto out; /* wait for a message to turn up */ release_sock(&rx->sk); prepare_to_wait_exclusive(sk_sleep(&rx->sk), &wait, TASK_INTERRUPTIBLE); ret = sock_error(&rx->sk); if (ret) goto wait_error; if (skb_queue_empty(&rx->sk.sk_receive_queue)) { if (signal_pending(current)) goto wait_interrupted; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(&rx->sk), &wait); lock_sock(&rx->sk); continue; } peek_next_packet: sp = rxrpc_skb(skb); call = sp->call; ASSERT(call != NULL); _debug("next pkt %s", rxrpc_pkts[sp->hdr.type]); /* make sure we wait for the state to be updated in this call */ spin_lock_bh(&call->lock); spin_unlock_bh(&call->lock); if (test_bit(RXRPC_CALL_RELEASED, &call->flags)) { _debug("packet from released call"); if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); continue; } /* determine whether to continue last data receive */ if (continue_call) { _debug("maybe cont"); if (call != continue_call || skb->mark != RXRPC_SKB_MARK_DATA) { release_sock(&rx->sk); rxrpc_put_call(continue_call); _leave(" = %d [noncont]", copied); return copied; } } rxrpc_get_call(call); /* copy the peer address and timestamp */ if (!continue_call) { if (msg->msg_name) { size_t len = sizeof(call->conn->trans->peer->srx); memcpy(msg->msg_name, &call->conn->trans->peer->srx, len); msg->msg_namelen = len; } sock_recv_ts_and_drops(msg, &rx->sk, skb); } /* receive the message */ if (skb->mark != RXRPC_SKB_MARK_DATA) goto receive_non_data_message; _debug("recvmsg DATA #%u { %d, %d }", ntohl(sp->hdr.seq), skb->len, sp->offset); if (!continue_call) { /* only set the control data once per recvmsg() */ ret = put_cmsg(msg, SOL_RXRPC, RXRPC_USER_CALL_ID, ullen, &call->user_call_ID); if (ret < 0) goto copy_error; ASSERT(test_bit(RXRPC_CALL_HAS_USERID, &call->flags)); } ASSERTCMP(ntohl(sp->hdr.seq), >=, call->rx_data_recv); ASSERTCMP(ntohl(sp->hdr.seq), <=, call->rx_data_recv + 1); call->rx_data_recv = ntohl(sp->hdr.seq); ASSERTCMP(ntohl(sp->hdr.seq), >, call->rx_data_eaten); offset = sp->offset; copy = skb->len - offset; if (copy > len - copied) copy = len - copied; if (skb->ip_summed == CHECKSUM_UNNECESSARY) { ret = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, copy); } else { ret = skb_copy_and_csum_datagram_iovec(skb, offset, msg->msg_iov); if (ret == -EINVAL) goto csum_copy_error; } if (ret < 0) goto copy_error; /* handle piecemeal consumption of data packets */ _debug("copied %d+%d", copy, copied); offset += copy; copied += copy; if (!(flags & MSG_PEEK)) sp->offset = offset; if (sp->offset < skb->len) { _debug("buffer full"); ASSERTCMP(copied, ==, len); break; } /* we transferred the whole data packet */ if (sp->hdr.flags & RXRPC_LAST_PACKET) { _debug("last"); if (call->conn->out_clientflag) { /* last byte of reply received */ ret = copied; goto terminal_message; } /* last bit of request received */ if (!(flags & MSG_PEEK)) { _debug("eat packet"); if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); } msg->msg_flags &= ~MSG_MORE; break; } /* move on to the next data message */ _debug("next"); if (!continue_call) continue_call = sp->call; else rxrpc_put_call(call); call = NULL; if (flags & MSG_PEEK) { _debug("peek next"); skb = skb->next; if (skb == (struct sk_buff *) &rx->sk.sk_receive_queue) break; goto peek_next_packet; } _debug("eat packet"); if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); } /* end of non-terminal data packet reception for the moment */ _debug("end rcv data"); out: release_sock(&rx->sk); if (call) rxrpc_put_call(call); if (continue_call) rxrpc_put_call(continue_call); _leave(" = %d [data]", copied); return copied; /* handle non-DATA messages such as aborts, incoming connections and * final ACKs */ receive_non_data_message: _debug("non-data"); if (skb->mark == RXRPC_SKB_MARK_NEW_CALL) { _debug("RECV NEW CALL"); ret = put_cmsg(msg, SOL_RXRPC, RXRPC_NEW_CALL, 0, &abort_code); if (ret < 0) goto copy_error; if (!(flags & MSG_PEEK)) { if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); } goto out; } ret = put_cmsg(msg, SOL_RXRPC, RXRPC_USER_CALL_ID, ullen, &call->user_call_ID); if (ret < 0) goto copy_error; ASSERT(test_bit(RXRPC_CALL_HAS_USERID, &call->flags)); switch (skb->mark) { case RXRPC_SKB_MARK_DATA: BUG(); case RXRPC_SKB_MARK_FINAL_ACK: ret = put_cmsg(msg, SOL_RXRPC, RXRPC_ACK, 0, &abort_code); break; case RXRPC_SKB_MARK_BUSY: ret = put_cmsg(msg, SOL_RXRPC, RXRPC_BUSY, 0, &abort_code); break; case RXRPC_SKB_MARK_REMOTE_ABORT: abort_code = call->abort_code; ret = put_cmsg(msg, SOL_RXRPC, RXRPC_ABORT, 4, &abort_code); break; case RXRPC_SKB_MARK_NET_ERROR: _debug("RECV NET ERROR %d", sp->error); abort_code = sp->error; ret = put_cmsg(msg, SOL_RXRPC, RXRPC_NET_ERROR, 4, &abort_code); break; case RXRPC_SKB_MARK_LOCAL_ERROR: _debug("RECV LOCAL ERROR %d", sp->error); abort_code = sp->error; ret = put_cmsg(msg, SOL_RXRPC, RXRPC_LOCAL_ERROR, 4, &abort_code); break; default: BUG(); break; } if (ret < 0) goto copy_error; terminal_message: _debug("terminal"); msg->msg_flags &= ~MSG_MORE; msg->msg_flags |= MSG_EOR; if (!(flags & MSG_PEEK)) { _net("free terminal skb %p", skb); if (skb_dequeue(&rx->sk.sk_receive_queue) != skb) BUG(); rxrpc_free_skb(skb); rxrpc_remove_user_ID(rx, call); } release_sock(&rx->sk); rxrpc_put_call(call); if (continue_call) rxrpc_put_call(continue_call); _leave(" = %d", ret); return ret; copy_error: _debug("copy error"); release_sock(&rx->sk); rxrpc_put_call(call); if (continue_call) rxrpc_put_call(continue_call); _leave(" = %d", ret); return ret; csum_copy_error: _debug("csum error"); release_sock(&rx->sk); if (continue_call) rxrpc_put_call(continue_call); rxrpc_kill_skb(skb); skb_kill_datagram(&rx->sk, skb, flags); rxrpc_put_call(call); return -EAGAIN; wait_interrupted: ret = sock_intr_errno(timeo); wait_error: finish_wait(sk_sleep(&rx->sk), &wait); if (continue_call) rxrpc_put_call(continue_call); if (copied) copied = ret; _leave(" = %d [waitfail %d]", copied, ret); return copied; }
25,516
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.
Code: long Chapters::Atom::ParseDisplay( IMkvReader* pReader, long long pos, long long size) { if (!ExpandDisplaysArray()) return -1; Display& d = m_displays[m_displays_count++]; d.Init(); return d.Parse(pReader, pos, size); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Atom::ParseDisplay(
11,767
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.
Code: static u32 svc_rdma_get_inv_rkey(struct rpcrdma_msg *rdma_argp, struct rpcrdma_write_array *wr_ary, struct rpcrdma_write_array *rp_ary) { struct rpcrdma_read_chunk *rd_ary; struct rpcrdma_segment *arg_ch; rd_ary = (struct rpcrdma_read_chunk *)&rdma_argp->rm_body.rm_chunks[0]; if (rd_ary->rc_discrim != xdr_zero) return be32_to_cpu(rd_ary->rc_target.rs_handle); if (wr_ary && be32_to_cpu(wr_ary->wc_nchunks)) { arg_ch = &wr_ary->wc_array[0].wc_target; return be32_to_cpu(arg_ch->rs_handle); } if (rp_ary && be32_to_cpu(rp_ary->wc_nchunks)) { arg_ch = &rp_ary->wc_array[0].wc_target; return be32_to_cpu(arg_ch->rs_handle); } return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static u32 svc_rdma_get_inv_rkey(struct rpcrdma_msg *rdma_argp, static u32 svc_rdma_get_inv_rkey(__be32 *rdma_argp, __be32 *wr_lst, __be32 *rp_ch) { __be32 *p; p = rdma_argp + rpcrdma_fixed_maxsz; if (*p != xdr_zero) p += 2; else if (wr_lst && be32_to_cpup(wr_lst + 1)) p = wr_lst + 2; else if (rp_ch && be32_to_cpup(rp_ch + 1)) p = rp_ch + 2; else return 0; return be32_to_cpup(p); } /* ib_dma_map_page() is used here because svc_rdma_dma_unmap() * is used during completion to DMA-unmap this memory, and * it uses ib_dma_unmap_page() exclusively. */ static int svc_rdma_dma_map_buf(struct svcxprt_rdma *rdma, struct svc_rdma_op_ctxt *ctxt, unsigned int sge_no, unsigned char *base, unsigned int len) { unsigned long offset = (unsigned long)base & ~PAGE_MASK; struct ib_device *dev = rdma->sc_cm_id->device; dma_addr_t dma_addr; dma_addr = ib_dma_map_page(dev, virt_to_page(base), offset, len, DMA_TO_DEVICE); if (ib_dma_mapping_error(dev, dma_addr)) return -EIO; ctxt->sge[sge_no].addr = dma_addr; ctxt->sge[sge_no].length = len; ctxt->sge[sge_no].lkey = rdma->sc_pd->local_dma_lkey; svc_rdma_count_mappings(rdma, ctxt); return 0; }
4,423
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.
Code: void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */ { const char *s; while ((s = zend_memrchr(filename, '/', filename_len))) { filename_len = s - filename; if (FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) { break; } } } /* }}} */ Commit Message: CWE ID: CWE-189
void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */ { const char *s; while ((s = zend_memrchr(filename, '/', filename_len))) { filename_len = s - filename; if (!filename_len || FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) { break; } } } /* }}} */
4,160
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.
Code: void EC_GROUP_clear_free(EC_GROUP *group) { if (!group) return; if (group->meth->group_clear_finish != 0) group->meth->group_clear_finish(group); else if (group->meth->group_finish != 0) group->meth->group_finish(group); EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_POINT_clear_free(group->generator); BN_clear_free(&group->order); OPENSSL_cleanse(group, sizeof *group); OPENSSL_free(group); } Commit Message: CWE ID: CWE-320
void EC_GROUP_clear_free(EC_GROUP *group) { if (!group) return; if (group->meth->group_clear_finish != 0) group->meth->group_clear_finish(group); else if (group->meth->group_finish != 0) group->meth->group_finish(group); EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->mont_data) BN_MONT_CTX_free(group->mont_data); if (group->generator != NULL) EC_POINT_clear_free(group->generator); BN_clear_free(&group->order); OPENSSL_cleanse(group, sizeof *group); OPENSSL_free(group); }
23,147
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.
Code: static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) { if (!buf || !sz || sz == UT64_MAX) { return NULL; } RBuffer *tbuf = r_buf_new (); r_buf_set_bytes (tbuf, buf, sz); struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf); r_buf_free (tbuf); return res ? res : NULL; } Commit Message: Fix #6829 oob write because of using wrong struct CWE ID: CWE-119
static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) { if (!buf || !sz || sz == UT64_MAX) { return NULL; } RBuffer *tbuf = r_buf_new (); if (!tbuf) { return NULL; } r_buf_set_bytes (tbuf, buf, sz); struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf); r_buf_free (tbuf); return res ? res : NULL; }
27,503
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.
Code: pimv2_addr_print(netdissect_options *ndo, const u_char *bp, enum pimv2_addrtype at, int silent) { int af; int len, hdrlen; ND_TCHECK(bp[0]); if (pimv2_addr_len == 0) { ND_TCHECK(bp[1]); switch (bp[0]) { case 1: af = AF_INET; len = sizeof(struct in_addr); break; case 2: af = AF_INET6; len = sizeof(struct in6_addr); break; default: return -1; } if (bp[1] != 0) return -1; hdrlen = 2; } else { switch (pimv2_addr_len) { case sizeof(struct in_addr): af = AF_INET; break; case sizeof(struct in6_addr): af = AF_INET6; break; default: return -1; break; } len = pimv2_addr_len; hdrlen = 0; } bp += hdrlen; switch (at) { case pimv2_unicast: ND_TCHECK2(bp[0], len); if (af == AF_INET) { if (!silent) ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp))); } else if (af == AF_INET6) { if (!silent) ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp))); } return hdrlen + len; case pimv2_group: case pimv2_source: ND_TCHECK2(bp[0], len + 2); if (af == AF_INET) { if (!silent) { ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp + 2))); if (bp[1] != 32) ND_PRINT((ndo, "/%u", bp[1])); } } else if (af == AF_INET6) { if (!silent) { ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp + 2))); if (bp[1] != 128) ND_PRINT((ndo, "/%u", bp[1])); } } if (bp[0] && !silent) { if (at == pimv2_group) { ND_PRINT((ndo, "(0x%02x)", bp[0])); } else { ND_PRINT((ndo, "(%s%s%s", bp[0] & 0x04 ? "S" : "", bp[0] & 0x02 ? "W" : "", bp[0] & 0x01 ? "R" : "")); if (bp[0] & 0xf8) { ND_PRINT((ndo, "+0x%02x", bp[0] & 0xf8)); } ND_PRINT((ndo, ")")); } } return hdrlen + 2 + len; default: return -1; } trunc: return -1; } Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks. Use ND_TCHECK macros to do bounds checking, and add length checks before the bounds checks. Add a bounds check that the review process found was missing. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. Update one test output file to reflect the changes. CWE ID: CWE-125
pimv2_addr_print(netdissect_options *ndo, const u_char *bp, u_int len, enum pimv2_addrtype at, u_int addr_len, int silent) { int af; int hdrlen; if (addr_len == 0) { if (len < 2) goto trunc; ND_TCHECK(bp[1]); switch (bp[0]) { case 1: af = AF_INET; addr_len = (u_int)sizeof(struct in_addr); break; case 2: af = AF_INET6; addr_len = (u_int)sizeof(struct in6_addr); break; default: return -1; } if (bp[1] != 0) return -1; hdrlen = 2; } else { switch (addr_len) { case sizeof(struct in_addr): af = AF_INET; break; case sizeof(struct in6_addr): af = AF_INET6; break; default: return -1; break; } hdrlen = 0; } bp += hdrlen; len -= hdrlen; switch (at) { case pimv2_unicast: if (len < addr_len) goto trunc; ND_TCHECK2(bp[0], addr_len); if (af == AF_INET) { if (!silent) ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp))); } else if (af == AF_INET6) { if (!silent) ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp))); } return hdrlen + addr_len; case pimv2_group: case pimv2_source: if (len < addr_len + 2) goto trunc; ND_TCHECK2(bp[0], addr_len + 2); if (af == AF_INET) { if (!silent) { ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp + 2))); if (bp[1] != 32) ND_PRINT((ndo, "/%u", bp[1])); } } else if (af == AF_INET6) { if (!silent) { ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp + 2))); if (bp[1] != 128) ND_PRINT((ndo, "/%u", bp[1])); } } if (bp[0] && !silent) { if (at == pimv2_group) { ND_PRINT((ndo, "(0x%02x)", bp[0])); } else { ND_PRINT((ndo, "(%s%s%s", bp[0] & 0x04 ? "S" : "", bp[0] & 0x02 ? "W" : "", bp[0] & 0x01 ? "R" : "")); if (bp[0] & 0xf8) { ND_PRINT((ndo, "+0x%02x", bp[0] & 0xf8)); } ND_PRINT((ndo, ")")); } } return hdrlen + 2 + addr_len; default: return -1; } trunc: return -1; }
23,363
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.
Code: static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { const char *client_name; Display *display; float pixels_per_point; Image *image; int sans, status; Pixmap pixmap; register IndexPacket *indexes; register ssize_t i; register PixelPacket *q; register size_t pixel; Screen *screen; ssize_t x, y; XColor *colors; XImage *dps_image; XRectangle page, bits_per_pixel; XResourceInfo resource_info; XrmDatabase resource_database; XStandardColormap *map_info; XVisualInfo *visual_info; /* Open X server connection. */ 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); display=XOpenDisplay(image_info->server_name); if (display == (Display *) NULL) return((Image *) NULL); /* Set our forgiving exception handler. */ (void) XSetErrorHandler(XError); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Get user defaults from X resource database. */ client_name=GetClientName(); resource_database=XGetResourceDatabase(display,client_name); XGetResourceInfo(image_info,resource_database,client_name,&resource_info); /* Allocate standard colormap. */ map_info=XAllocStandardColormap(); visual_info=(XVisualInfo *) NULL; if (map_info == (XStandardColormap *) NULL) ThrowReaderException(ResourceLimitError,"UnableToCreateStandardColormap") else { /* Initialize visual info. */ (void) CloneString(&resource_info.visual_type,"default"); visual_info=XBestVisualInfo(display,map_info,&resource_info); map_info->colormap=(Colormap) NULL; } if ((map_info == (XStandardColormap *) NULL) || (visual_info == (XVisualInfo *) NULL)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Create a pixmap the appropriate size for the image. */ screen=ScreenOfDisplay(display,visual_info->screen); pixels_per_point=XDPSPixelsPerPoint(screen); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/ DefaultResolution; status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap, &bits_per_pixel,&page); if ((status == dps_status_failure) || (status == dps_status_no_extension)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Rasterize the file into the pixmap. */ status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth, &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue, &sans); if (status != dps_status_success) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Initialize DPS X image. */ dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (dps_image == (XImage *) NULL) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Get the colormap colors. */ colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size, sizeof(*colors)); if (colors == (XColor *) NULL) { image=DestroyImage(image); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor)) for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=(size_t) i; colors[i].pad=0; } else { size_t blue, blue_bit, green, green_bit, red, red_bit; /* DirectColor or TrueColor visual. */ red=0; green=0; blue=0; red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1); green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1); blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1); for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=red | green | blue; colors[i].pad=0; red+=red_bit; if (red > visual_info->red_mask) red=0; green+=green_bit; if (green > visual_info->green_mask) green=0; blue+=blue_bit; if (blue > visual_info->blue_mask) blue=0; } } (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen), colors,visual_info->colormap_size); /* Convert X image to MIFF format. */ if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor)) image->storage_class=PseudoClass; image->columns=(size_t) dps_image->width; image->rows=(size_t) dps_image->height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } switch (image->storage_class) { case DirectClass: default: { register size_t color, index; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=visual_info->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=visual_info->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=visual_info->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((visual_info->colormap_size > 0) && (visual_info->klass == DirectColor)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); index=(pixel >> red_shift) & red_mask; SetPixelRed(q,ScaleShortToQuantum(colors[index].red)); index=(pixel >> green_shift) & green_mask; SetPixelGreen(q,ScaleShortToQuantum(colors[index].green)); index=(pixel >> blue_shift) & blue_mask; SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); color=(pixel >> red_shift) & red_mask; color=(color*65535L)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; color=(color*65535L)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; color=(color*65535L)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } case PseudoClass: { /* Create colormap. */ if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse) { image=DestroyImage(image); colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red); image->colormap[colors[i].pixel].green= ScaleShortToQuantum(colors[i].green); image->colormap[colors[i].pixel].blue= ScaleShortToQuantum(colors[i].blue); } /* Convert X image to PseudoClass packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,(unsigned short) XGetPixel(dps_image,x,y)); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } } colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); if (image->storage_class == PseudoClass) (void) SyncImage(image); /* Rasterize matte image. */ status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page); if ((status != dps_status_failure) && (status != dps_status_no_extension)) { status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x, -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans); if (status == dps_status_success) { XImage *matte_image; /* Initialize image matte. */ matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (matte_image != (XImage *) NULL) { image->storage_class=DirectClass; image->matte=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,OpaqueOpacity); if (XGetPixel(matte_image,x,y) == 0) SetPixelOpacity(q,TransparentOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } XDestroyImage(matte_image); } } } /* Relinquish resources. */ XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { const char *client_name; Display *display; float pixels_per_point; Image *image; int sans, status; Pixmap pixmap; register IndexPacket *indexes; register ssize_t i; register PixelPacket *q; register size_t pixel; Screen *screen; ssize_t x, y; XColor *colors; XImage *dps_image; XRectangle page, bits_per_pixel; XResourceInfo resource_info; XrmDatabase resource_database; XStandardColormap *map_info; XVisualInfo *visual_info; /* Open X server connection. */ 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); display=XOpenDisplay(image_info->server_name); if (display == (Display *) NULL) return((Image *) NULL); /* Set our forgiving exception handler. */ (void) XSetErrorHandler(XError); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Get user defaults from X resource database. */ client_name=GetClientName(); resource_database=XGetResourceDatabase(display,client_name); XGetResourceInfo(image_info,resource_database,client_name,&resource_info); /* Allocate standard colormap. */ map_info=XAllocStandardColormap(); visual_info=(XVisualInfo *) NULL; if (map_info == (XStandardColormap *) NULL) ThrowReaderException(ResourceLimitError,"UnableToCreateStandardColormap") else { /* Initialize visual info. */ (void) CloneString(&resource_info.visual_type,"default"); visual_info=XBestVisualInfo(display,map_info,&resource_info); map_info->colormap=(Colormap) NULL; } if ((map_info == (XStandardColormap *) NULL) || (visual_info == (XVisualInfo *) NULL)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Create a pixmap the appropriate size for the image. */ screen=ScreenOfDisplay(display,visual_info->screen); pixels_per_point=XDPSPixelsPerPoint(screen); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/ DefaultResolution; status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap, &bits_per_pixel,&page); if ((status == dps_status_failure) || (status == dps_status_no_extension)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Rasterize the file into the pixmap. */ status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth, &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue, &sans); if (status != dps_status_success) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Initialize DPS X image. */ dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (dps_image == (XImage *) NULL) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Get the colormap colors. */ colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size, sizeof(*colors)); if (colors == (XColor *) NULL) { image=DestroyImage(image); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor)) for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=(size_t) i; colors[i].pad=0; } else { size_t blue, blue_bit, green, green_bit, red, red_bit; /* DirectColor or TrueColor visual. */ red=0; green=0; blue=0; red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1); green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1); blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1); for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=red | green | blue; colors[i].pad=0; red+=red_bit; if (red > visual_info->red_mask) red=0; green+=green_bit; if (green > visual_info->green_mask) green=0; blue+=blue_bit; if (blue > visual_info->blue_mask) blue=0; } } (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen), colors,visual_info->colormap_size); /* Convert X image to MIFF format. */ if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor)) image->storage_class=PseudoClass; image->columns=(size_t) dps_image->width; image->rows=(size_t) dps_image->height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } switch (image->storage_class) { case DirectClass: default: { register size_t color, index; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=visual_info->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=visual_info->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=visual_info->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((visual_info->colormap_size > 0) && (visual_info->klass == DirectColor)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); index=(pixel >> red_shift) & red_mask; SetPixelRed(q,ScaleShortToQuantum(colors[index].red)); index=(pixel >> green_shift) & green_mask; SetPixelGreen(q,ScaleShortToQuantum(colors[index].green)); index=(pixel >> blue_shift) & blue_mask; SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); color=(pixel >> red_shift) & red_mask; color=(color*65535L)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; color=(color*65535L)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; color=(color*65535L)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } case PseudoClass: { /* Create colormap. */ if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse) { image=DestroyImage(image); colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red); image->colormap[colors[i].pixel].green= ScaleShortToQuantum(colors[i].green); image->colormap[colors[i].pixel].blue= ScaleShortToQuantum(colors[i].blue); } /* Convert X image to PseudoClass packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,(unsigned short) XGetPixel(dps_image,x,y)); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } } colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); if (image->storage_class == PseudoClass) (void) SyncImage(image); /* Rasterize matte image. */ status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page); if ((status != dps_status_failure) && (status != dps_status_no_extension)) { status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x, -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans); if (status == dps_status_success) { XImage *matte_image; /* Initialize image matte. */ matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (matte_image != (XImage *) NULL) { image->storage_class=DirectClass; image->matte=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,OpaqueOpacity); if (XGetPixel(matte_image,x,y) == 0) SetPixelOpacity(q,TransparentOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } XDestroyImage(matte_image); } } } /* Relinquish resources. */ XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
2,121
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.
Code: load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, char immediate_load) { static const int intoffset[] = { 0, 4, 2, 1 }; static const int intjump[] = { 8, 8, 4, 2 }; int rc; DATA32 *ptr; GifFileType *gif; GifRowType *rows; GifRecordType rec; ColorMapObject *cmap; int i, j, done, bg, r, g, b, w = 0, h = 0; float per = 0.0, per_inc; int last_per = 0, last_y = 0; int transp; int fd; done = 0; rows = NULL; transp = -1; /* if immediate_load is 1, then dont delay image laoding as below, or */ /* already data in this image - dont load it again */ if (im->data) return 0; fd = open(im->real_file, O_RDONLY); if (fd < 0) return 0; #if GIFLIB_MAJOR >= 5 gif = DGifOpenFileHandle(fd, NULL); #else gif = DGifOpenFileHandle(fd); #endif if (!gif) { close(fd); return 0; } rc = 0; /* Failure */ do { if (DGifGetRecordType(gif, &rec) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) { if (DGifGetImageDesc(gif) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } w = gif->Image.Width; h = gif->Image.Height; if (!IMAGE_DIMENSIONS_OK(w, h)) goto quit2; rows = calloc(h, sizeof(GifRowType *)); if (!rows) goto quit2; for (i = 0; i < h; i++) { rows[i] = malloc(w * sizeof(GifPixelType)); if (!rows[i]) goto quit; } if (gif->Image.Interlace) { for (i = 0; i < 4; i++) { for (j = intoffset[i]; j < h; j += intjump[i]) { DGifGetLine(gif, rows[j], w); } } } else { for (i = 0; i < h; i++) { DGifGetLine(gif, rows[i], w); } } done = 1; } else if (rec == EXTENSION_RECORD_TYPE) { int ext_code; GifByteType *ext; ext = NULL; DGifGetExtension(gif, &ext_code, &ext); while (ext) { if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) { transp = (int)ext[4]; } ext = NULL; DGifGetExtensionNext(gif, &ext); } } } while (rec != TERMINATE_RECORD_TYPE); if (transp >= 0) { SET_FLAG(im->flags, F_HAS_ALPHA); } else { UNSET_FLAG(im->flags, F_HAS_ALPHA); } /* set the format string member to the lower-case full extension */ /* name for the format - so example names would be: */ /* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */ im->w = w; im->h = h; if (!im->format) im->format = strdup("gif"); if (im->loader || immediate_load || progress) { bg = gif->SBackGroundColor; cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap); im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h); if (!im->data) goto quit; ptr = im->data; per_inc = 100.0 / (((float)w) * h); for (i = 0; i < h; i++) *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; } per += per_inc; if (progress && (((int)per) != last_per) && (((int)per) % progress_granularity == 0)) { last_per = (int)per; if (!(progress(im, (int)per, 0, last_y, w, i))) { rc = 2; goto quit; } last_y = i; } } Commit Message: CWE ID: CWE-20
load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, char immediate_load) { static const int intoffset[] = { 0, 4, 2, 1 }; static const int intjump[] = { 8, 8, 4, 2 }; int rc; DATA32 *ptr; GifFileType *gif; GifRowType *rows; GifRecordType rec; ColorMapObject *cmap; int i, j, done, bg, r, g, b, w = 0, h = 0; float per = 0.0, per_inc; int last_per = 0, last_y = 0; int transp; int fd; done = 0; rows = NULL; transp = -1; /* if immediate_load is 1, then dont delay image laoding as below, or */ /* already data in this image - dont load it again */ if (im->data) return 0; fd = open(im->real_file, O_RDONLY); if (fd < 0) return 0; #if GIFLIB_MAJOR >= 5 gif = DGifOpenFileHandle(fd, NULL); #else gif = DGifOpenFileHandle(fd); #endif if (!gif) { close(fd); return 0; } rc = 0; /* Failure */ do { if (DGifGetRecordType(gif, &rec) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) { if (DGifGetImageDesc(gif) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } w = gif->Image.Width; h = gif->Image.Height; if (!IMAGE_DIMENSIONS_OK(w, h)) goto quit2; rows = calloc(h, sizeof(GifRowType *)); if (!rows) goto quit2; for (i = 0; i < h; i++) { rows[i] = malloc(w * sizeof(GifPixelType)); if (!rows[i]) goto quit; } if (gif->Image.Interlace) { for (i = 0; i < 4; i++) { for (j = intoffset[i]; j < h; j += intjump[i]) { DGifGetLine(gif, rows[j], w); } } } else { for (i = 0; i < h; i++) { DGifGetLine(gif, rows[i], w); } } done = 1; } else if (rec == EXTENSION_RECORD_TYPE) { int ext_code; GifByteType *ext; ext = NULL; DGifGetExtension(gif, &ext_code, &ext); while (ext) { if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) { transp = (int)ext[4]; } ext = NULL; DGifGetExtensionNext(gif, &ext); } } } while (rec != TERMINATE_RECORD_TYPE); if (transp >= 0) { SET_FLAG(im->flags, F_HAS_ALPHA); } else { UNSET_FLAG(im->flags, F_HAS_ALPHA); } /* set the format string member to the lower-case full extension */ /* name for the format - so example names would be: */ /* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */ im->w = w; im->h = h; if (!im->format) im->format = strdup("gif"); if (im->loader || immediate_load || progress) { bg = gif->SBackGroundColor; cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap); im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h); if (!im->data) goto quit; if (!cmap) { /* No colormap? Now what?? Let's clear the image (and not segv) */ memset(im->data, 0, sizeof(DATA32) * w * h); rc = 1; goto finish; } ptr = im->data; per_inc = 100.0 / (((float)w) * h); for (i = 0; i < h; i++) *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; } per += per_inc; if (progress && (((int)per) != last_per) && (((int)per) % progress_granularity == 0)) { last_per = (int)per; if (!(progress(im, (int)per, 0, last_y, w, i))) { rc = 2; goto quit; } last_y = i; } }
14,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.
Code: void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) { void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride); }
26,408
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.
Code: long Track::GetNumber() const { return m_info.number; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Track::GetNumber() const
343
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.
Code: pvscsi_convert_sglist(PVSCSIRequest *r) { int chunk_size; uint64_t data_length = r->req.dataLen; PVSCSISGState sg = r->sg; while (data_length) { while (!sg.resid) { pvscsi_get_next_sg_elem(&sg); trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr, r->sg.resid); } assert(data_length > 0); chunk_size = MIN((unsigned) data_length, sg.resid); if (chunk_size) { qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size); } sg.dataAddr += chunk_size; data_length -= chunk_size; sg.resid -= chunk_size; } } Commit Message: CWE ID: CWE-399
pvscsi_convert_sglist(PVSCSIRequest *r) { uint32_t chunk_size, elmcnt = 0; uint64_t data_length = r->req.dataLen; PVSCSISGState sg = r->sg; while (data_length && elmcnt < PVSCSI_MAX_SG_ELEM) { while (!sg.resid && elmcnt++ < PVSCSI_MAX_SG_ELEM) { pvscsi_get_next_sg_elem(&sg); trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr, r->sg.resid); } chunk_size = MIN(data_length, sg.resid); if (chunk_size) { qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size); } sg.dataAddr += chunk_size; data_length -= chunk_size; sg.resid -= chunk_size; } }
18,774
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.
Code: static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu) { const struct usb_cdc_union_desc *union_desc; struct usb_host_interface *alt; union_desc = ims_pcu_get_cdc_union_desc(intf); if (!union_desc) return -EINVAL; pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev, union_desc->bMasterInterface0); alt = pcu->ctrl_intf->cur_altsetting; pcu->ep_ctrl = &alt->endpoint[0].desc; pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl); pcu->data_intf = usb_ifnum_to_if(pcu->udev, union_desc->bSlaveInterface0); alt = pcu->data_intf->cur_altsetting; if (alt->desc.bNumEndpoints != 2) { dev_err(pcu->dev, "Incorrect number of endpoints on data interface (%d)\n", alt->desc.bNumEndpoints); return -EINVAL; } pcu->ep_out = &alt->endpoint[0].desc; if (!usb_endpoint_is_bulk_out(pcu->ep_out)) { dev_err(pcu->dev, "First endpoint on data interface is not BULK OUT\n"); return -EINVAL; } pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out); if (pcu->max_out_size < 8) { dev_err(pcu->dev, "Max OUT packet size is too small (%zd)\n", pcu->max_out_size); return -EINVAL; } pcu->ep_in = &alt->endpoint[1].desc; if (!usb_endpoint_is_bulk_in(pcu->ep_in)) { dev_err(pcu->dev, "Second endpoint on data interface is not BULK IN\n"); return -EINVAL; } pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in); if (pcu->max_in_size < 8) { dev_err(pcu->dev, "Max IN packet size is too small (%zd)\n", pcu->max_in_size); return -EINVAL; } return 0; } Commit Message: Input: ims-pcu - sanity check against missing interfaces A malicious device missing interface can make the driver oops. Add sanity checking. Signed-off-by: Oliver Neukum <ONeukum@suse.com> CC: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com> CWE ID:
static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu) { const struct usb_cdc_union_desc *union_desc; struct usb_host_interface *alt; union_desc = ims_pcu_get_cdc_union_desc(intf); if (!union_desc) return -EINVAL; pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev, union_desc->bMasterInterface0); if (!pcu->ctrl_intf) return -EINVAL; alt = pcu->ctrl_intf->cur_altsetting; pcu->ep_ctrl = &alt->endpoint[0].desc; pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl); pcu->data_intf = usb_ifnum_to_if(pcu->udev, union_desc->bSlaveInterface0); if (!pcu->data_intf) return -EINVAL; alt = pcu->data_intf->cur_altsetting; if (alt->desc.bNumEndpoints != 2) { dev_err(pcu->dev, "Incorrect number of endpoints on data interface (%d)\n", alt->desc.bNumEndpoints); return -EINVAL; } pcu->ep_out = &alt->endpoint[0].desc; if (!usb_endpoint_is_bulk_out(pcu->ep_out)) { dev_err(pcu->dev, "First endpoint on data interface is not BULK OUT\n"); return -EINVAL; } pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out); if (pcu->max_out_size < 8) { dev_err(pcu->dev, "Max OUT packet size is too small (%zd)\n", pcu->max_out_size); return -EINVAL; } pcu->ep_in = &alt->endpoint[1].desc; if (!usb_endpoint_is_bulk_in(pcu->ep_in)) { dev_err(pcu->dev, "Second endpoint on data interface is not BULK IN\n"); return -EINVAL; } pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in); if (pcu->max_in_size < 8) { dev_err(pcu->dev, "Max IN packet size is too small (%zd)\n", pcu->max_in_size); return -EINVAL; } return 0; }
19,698
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.
Code: void gdImageJpegCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; int i, j, jidx; /* volatile so we can gdFree it on return from longjmp */ volatile JSAMPROW row = 0; JSAMPROW rowptr[1]; jmpbuf_wrapper jmpbufw; JDIMENSION nlines; char comment[255]; memset (&cinfo, 0, sizeof (cinfo)); memset (&jerr, 0, sizeof (jerr)); cinfo.err = jpeg_std_error (&jerr); cinfo.client_data = &jmpbufw; if (setjmp (jmpbufw.jmpbuf) != 0) { /* we're here courtesy of longjmp */ if (row) { gdFree (row); } return; } cinfo.err->error_exit = fatal_jpeg_error; jpeg_create_compress (&cinfo); cinfo.image_width = im->sx; cinfo.image_height = im->sy; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults (&cinfo); cinfo.density_unit = 1; cinfo.X_density = im->res_x; cinfo.Y_density = im->res_y; if (quality >= 0) { jpeg_set_quality (&cinfo, quality, TRUE); } /* If user requests interlace, translate that to progressive JPEG */ if (gdImageGetInterlaced (im)) { jpeg_simple_progression (&cinfo); } jpeg_gdIOCtx_dest (&cinfo, outfile); row = (JSAMPROW) safe_emalloc(cinfo.image_width * cinfo.input_components, sizeof(JSAMPLE), 0); memset(row, 0, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE)); rowptr[0] = row; jpeg_start_compress (&cinfo, TRUE); if (quality >= 0) { snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), quality = %d\n", GD_JPEG_VERSION, JPEG_LIB_VERSION, quality); } else { snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), default quality\n", GD_JPEG_VERSION, JPEG_LIB_VERSION); } jpeg_write_marker (&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int) strlen (comment)); if (im->trueColor) { #if BITS_IN_JSAMPLE == 12 gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry"); goto error; #endif /* BITS_IN_JSAMPLE == 12 */ for (i = 0; i < im->sy; i++) { for (jidx = 0, j = 0; j < im->sx; j++) { int val = im->tpixels[i][j]; row[jidx++] = gdTrueColorGetRed (val); row[jidx++] = gdTrueColorGetGreen (val); row[jidx++] = gdTrueColorGetBlue (val); } nlines = jpeg_write_scanlines (&cinfo, rowptr, 1); if (nlines != 1) { gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines); } } } else { for (i = 0; i < im->sy; i++) { for (jidx = 0, j = 0; j < im->sx; j++) { int idx = im->pixels[i][j]; /* NB: Although gd RGB values are ints, their max value is * 255 (see the documentation for gdImageColorAllocate()) * -- perfect for 8-bit JPEG encoding (which is the norm) */ #if BITS_IN_JSAMPLE == 8 row[jidx++] = im->red[idx]; row[jidx++] = im->green[idx]; row[jidx++] = im->blue[idx]; #elif BITS_IN_JSAMPLE == 12 row[jidx++] = im->red[idx] << 4; row[jidx++] = im->green[idx] << 4; row[jidx++] = im->blue[idx] << 4; #else #error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12 #endif } nlines = jpeg_write_scanlines (&cinfo, rowptr, 1); if (nlines != 1) { gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines); } } } jpeg_finish_compress (&cinfo); jpeg_destroy_compress (&cinfo); gdFree (row); } Commit Message: Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here. CWE ID: CWE-415
void gdImageJpegCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { _gdImageJpegCtx(im, outfile, quality); } /* returns 0 on success, 1 on failure */ static int _gdImageJpegCtx(gdImagePtr im, gdIOCtx *outfile, int quality) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; int i, j, jidx; /* volatile so we can gdFree it on return from longjmp */ volatile JSAMPROW row = 0; JSAMPROW rowptr[1]; jmpbuf_wrapper jmpbufw; JDIMENSION nlines; char comment[255]; memset (&cinfo, 0, sizeof (cinfo)); memset (&jerr, 0, sizeof (jerr)); cinfo.err = jpeg_std_error (&jerr); cinfo.client_data = &jmpbufw; if (setjmp (jmpbufw.jmpbuf) != 0) { /* we're here courtesy of longjmp */ if (row) { gdFree (row); } return 1; } cinfo.err->error_exit = fatal_jpeg_error; jpeg_create_compress (&cinfo); cinfo.image_width = im->sx; cinfo.image_height = im->sy; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults (&cinfo); cinfo.density_unit = 1; cinfo.X_density = im->res_x; cinfo.Y_density = im->res_y; if (quality >= 0) { jpeg_set_quality (&cinfo, quality, TRUE); } /* If user requests interlace, translate that to progressive JPEG */ if (gdImageGetInterlaced (im)) { jpeg_simple_progression (&cinfo); } jpeg_gdIOCtx_dest (&cinfo, outfile); row = (JSAMPROW) safe_emalloc(cinfo.image_width * cinfo.input_components, sizeof(JSAMPLE), 0); memset(row, 0, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE)); rowptr[0] = row; jpeg_start_compress (&cinfo, TRUE); if (quality >= 0) { snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), quality = %d\n", GD_JPEG_VERSION, JPEG_LIB_VERSION, quality); } else { snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), default quality\n", GD_JPEG_VERSION, JPEG_LIB_VERSION); } jpeg_write_marker (&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int) strlen (comment)); if (im->trueColor) { #if BITS_IN_JSAMPLE == 12 gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry"); goto error; #endif /* BITS_IN_JSAMPLE == 12 */ for (i = 0; i < im->sy; i++) { for (jidx = 0, j = 0; j < im->sx; j++) { int val = im->tpixels[i][j]; row[jidx++] = gdTrueColorGetRed (val); row[jidx++] = gdTrueColorGetGreen (val); row[jidx++] = gdTrueColorGetBlue (val); } nlines = jpeg_write_scanlines (&cinfo, rowptr, 1); if (nlines != 1) { gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines); } } } else { for (i = 0; i < im->sy; i++) { for (jidx = 0, j = 0; j < im->sx; j++) { int idx = im->pixels[i][j]; /* NB: Although gd RGB values are ints, their max value is * 255 (see the documentation for gdImageColorAllocate()) * -- perfect for 8-bit JPEG encoding (which is the norm) */ #if BITS_IN_JSAMPLE == 8 row[jidx++] = im->red[idx]; row[jidx++] = im->green[idx]; row[jidx++] = im->blue[idx]; #elif BITS_IN_JSAMPLE == 12 row[jidx++] = im->red[idx] << 4; row[jidx++] = im->green[idx] << 4; row[jidx++] = im->blue[idx] << 4; #else #error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12 #endif } nlines = jpeg_write_scanlines (&cinfo, rowptr, 1); if (nlines != 1) { gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines); } } } jpeg_finish_compress (&cinfo); jpeg_destroy_compress (&cinfo); gdFree (row); return 0; }
15,243
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.
Code: BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } gdImageWebpCtx(im, out, -1); out->gd_free(out); } Commit Message: Fix double-free in gdImageWebPtr() The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and the other WebP output functions to do the real work) does not return whether it succeeded or failed, so this is not checked in gdImageWebpPtr() and the function wrongly assumes everything is okay, which is not, in this case, because there is a size limitation for WebP, namely that the width and height must by less than 16383. We can't change the signature of gdImageWebpCtx() for API compatibility reasons, so we introduce the static helper _gdImageWebpCtx() which returns success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can check the return value. We leave it solely to libwebp for now to report warnings regarding the failing write. This issue had been reported by Ibrahim El-Sayed to security@libgd.org. CVE-2016-6912 CWE ID: CWE-415
BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } _gdImageWebpCtx(im, out, -1); out->gd_free(out); }
5,174
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.
Code: void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { RenderBlock::styleDidChange(diff, oldStyle); bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats(); if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) { RenderBlockFlow* parentBlockFlow = this; const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); FloatingObjectSetIterator end = floatingObjectSet.end(); for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) { if (curr->isRenderBlockFlow()) { RenderBlockFlow* currBlock = toRenderBlockFlow(curr); if (currBlock->hasOverhangingFloats()) { for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) { RenderBox* renderer = (*it)->renderer(); if (currBlock->hasOverhangingFloat(renderer)) { parentBlockFlow = currBlock; break; } } } } } parentBlockFlow->markAllDescendantsWithFloatsForLayout(); parentBlockFlow->markSiblingsWithFloatsForLayout(); } if (diff == StyleDifferenceLayout || !oldStyle) createOrDestroyMultiColumnFlowThreadIfNeeded(); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. R=eseidel@chromium.org, esprehn@chromium.org, jchaffraix@chromium.org Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { RenderBlock::styleDidChange(diff, oldStyle); bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats(); if (diff.needsFullLayout() && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) { RenderBlockFlow* parentBlockFlow = this; const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); FloatingObjectSetIterator end = floatingObjectSet.end(); for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) { if (curr->isRenderBlockFlow()) { RenderBlockFlow* currBlock = toRenderBlockFlow(curr); if (currBlock->hasOverhangingFloats()) { for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) { RenderBox* renderer = (*it)->renderer(); if (currBlock->hasOverhangingFloat(renderer)) { parentBlockFlow = currBlock; break; } } } } } parentBlockFlow->markAllDescendantsWithFloatsForLayout(); parentBlockFlow->markSiblingsWithFloatsForLayout(); } if (diff.needsFullLayout() || !oldStyle) createOrDestroyMultiColumnFlowThreadIfNeeded(); }
6,548
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.
Code: int qcow2_snapshot_load_tmp(BlockDriverState *bs, const char *snapshot_id, const char *name, Error **errp) { int i, snapshot_index; BDRVQcowState *s = bs->opaque; QCowSnapshot *sn; uint64_t *new_l1_table; int new_l1_bytes; int ret; assert(bs->read_only); /* Search the snapshot */ snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name); if (snapshot_index < 0) { error_setg(errp, "Can't find snapshot"); return -ENOENT; } sn = &s->snapshots[snapshot_index]; /* Allocate and read in the snapshot's L1 table */ new_l1_bytes = sn->l1_size * sizeof(uint64_t); new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512)); return ret; } Commit Message: CWE ID: CWE-190
int qcow2_snapshot_load_tmp(BlockDriverState *bs, const char *snapshot_id, const char *name, Error **errp) { int i, snapshot_index; BDRVQcowState *s = bs->opaque; QCowSnapshot *sn; uint64_t *new_l1_table; int new_l1_bytes; int ret; assert(bs->read_only); /* Search the snapshot */ snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name); if (snapshot_index < 0) { error_setg(errp, "Can't find snapshot"); return -ENOENT; } sn = &s->snapshots[snapshot_index]; /* Allocate and read in the snapshot's L1 table */ if (sn->l1_size > QCOW_MAX_L1_SIZE) { error_setg(errp, "Snapshot L1 table too large"); return -EFBIG; } new_l1_bytes = sn->l1_size * sizeof(uint64_t); new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512)); return ret; }
12,058
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.
Code: juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ND_TCHECK2(p[0], 2); extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_pppoe_atm]")); return l2info.header_len; }
6,151
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.
Code: nfs41_callback_svc(void *vrqstp) { struct svc_rqst *rqstp = vrqstp; struct svc_serv *serv = rqstp->rq_server; struct rpc_rqst *req; int error; DEFINE_WAIT(wq); set_freezable(); while (!kthread_should_stop()) { if (try_to_freeze()) continue; prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE); spin_lock_bh(&serv->sv_cb_lock); if (!list_empty(&serv->sv_cb_list)) { req = list_first_entry(&serv->sv_cb_list, struct rpc_rqst, rq_bc_list); list_del(&req->rq_bc_list); spin_unlock_bh(&serv->sv_cb_lock); finish_wait(&serv->sv_cb_waitq, &wq); dprintk("Invoking bc_svc_process()\n"); error = bc_svc_process(serv, req, rqstp); dprintk("bc_svc_process() returned w/ error code= %d\n", error); } else { spin_unlock_bh(&serv->sv_cb_lock); schedule(); finish_wait(&serv->sv_cb_waitq, &wq); } flush_signals(current); } return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfs41_callback_svc(void *vrqstp) { struct svc_rqst *rqstp = vrqstp; struct svc_serv *serv = rqstp->rq_server; struct rpc_rqst *req; int error; DEFINE_WAIT(wq); set_freezable(); while (!kthread_freezable_should_stop(NULL)) { if (signal_pending(current)) flush_signals(current); prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE); spin_lock_bh(&serv->sv_cb_lock); if (!list_empty(&serv->sv_cb_list)) { req = list_first_entry(&serv->sv_cb_list, struct rpc_rqst, rq_bc_list); list_del(&req->rq_bc_list); spin_unlock_bh(&serv->sv_cb_lock); finish_wait(&serv->sv_cb_waitq, &wq); dprintk("Invoking bc_svc_process()\n"); error = bc_svc_process(serv, req, rqstp); dprintk("bc_svc_process() returned w/ error code= %d\n", error); } else { spin_unlock_bh(&serv->sv_cb_lock); if (!kthread_should_stop()) schedule(); finish_wait(&serv->sv_cb_waitq, &wq); } } svc_exit_thread(rqstp); module_put_and_exit(0); return 0; }
21,185
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.
Code: void DiscardAndActivateTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); background_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false)); tab_strip_model_->ActivateTabAt(0, true); testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DiscardAndActivateTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); background_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false)); tab_strip_model_->ActivateTabAt(0, true); ::testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); }
10,839
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.
Code: void WebBluetoothServiceImpl::ClearState() { characteristic_id_to_notify_session_.clear(); pending_primary_services_requests_.clear(); descriptor_id_to_characteristic_id_.clear(); characteristic_id_to_service_id_.clear(); service_id_to_device_address_.clear(); connected_devices_.reset( new FrameConnectedBluetoothDevices(render_frame_host_)); device_chooser_controller_.reset(); BluetoothAdapterFactoryWrapper::Get().ReleaseAdapter(this); } Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <reillyg@chromium.org> Reviewed-by: Michael Wasserman <msw@chromium.org> Reviewed-by: Jeffrey Yasskin <jyasskin@chromium.org> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362
void WebBluetoothServiceImpl::ClearState() { // Releasing the adapter will drop references to callbacks that have not yet // been executed. The binding must be closed first so that this is allowed. binding_.Close(); characteristic_id_to_notify_session_.clear(); pending_primary_services_requests_.clear(); descriptor_id_to_characteristic_id_.clear(); characteristic_id_to_service_id_.clear(); service_id_to_device_address_.clear(); connected_devices_.reset( new FrameConnectedBluetoothDevices(render_frame_host_)); device_chooser_controller_.reset(); BluetoothAdapterFactoryWrapper::Get().ReleaseAdapter(this); }
21,529
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.
Code: scoped_refptr<PermissionSet> UnpackPermissionSet( const Permissions& permissions, std::string* error) { APIPermissionSet apis; std::vector<std::string>* permissions_list = permissions.permissions.get(); if (permissions_list) { PermissionsInfo* info = PermissionsInfo::GetInstance(); for (std::vector<std::string>::iterator it = permissions_list->begin(); it != permissions_list->end(); ++it) { if (it->find(kDelimiter) != std::string::npos) { size_t delimiter = it->find(kDelimiter); std::string permission_name = it->substr(0, delimiter); std::string permission_arg = it->substr(delimiter + 1); scoped_ptr<base::Value> permission_json( base::JSONReader::Read(permission_arg)); if (!permission_json.get()) { *error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it); return NULL; } APIPermission* permission = NULL; const APIPermissionInfo* bluetooth_device_permission_info = info->GetByID(APIPermission::kBluetoothDevice); const APIPermissionInfo* usb_device_permission_info = info->GetByID(APIPermission::kUsbDevice); if (permission_name == bluetooth_device_permission_info->name()) { permission = new BluetoothDevicePermission( bluetooth_device_permission_info); } else if (permission_name == usb_device_permission_info->name()) { permission = new UsbDevicePermission(usb_device_permission_info); } else { *error = kUnsupportedPermissionId; return NULL; } CHECK(permission); if (!permission->FromValue(permission_json.get())) { *error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it); return NULL; } apis.insert(permission); } else { const APIPermissionInfo* permission_info = info->GetByName(*it); if (!permission_info) { *error = ErrorUtils::FormatErrorMessage( kUnknownPermissionError, *it); return NULL; } apis.insert(permission_info->id()); } } } URLPatternSet origins; if (permissions.origins.get()) { for (std::vector<std::string>::iterator it = permissions.origins->begin(); it != permissions.origins->end(); ++it) { URLPattern origin(Extension::kValidHostPermissionSchemes); URLPattern::ParseResult parse_result = origin.Parse(*it); if (URLPattern::PARSE_SUCCESS != parse_result) { *error = ErrorUtils::FormatErrorMessage( kInvalidOrigin, *it, URLPattern::GetParseResultString(parse_result)); return NULL; } origins.AddPattern(origin); } } return scoped_refptr<PermissionSet>( new PermissionSet(apis, origins, URLPatternSet())); } Commit Message: Check prefs before allowing extension file access in the permissions API. R=mpcomplete@chromium.org BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
scoped_refptr<PermissionSet> UnpackPermissionSet( const Permissions& permissions, bool allow_file_access, std::string* error) { APIPermissionSet apis; std::vector<std::string>* permissions_list = permissions.permissions.get(); if (permissions_list) { PermissionsInfo* info = PermissionsInfo::GetInstance(); for (std::vector<std::string>::iterator it = permissions_list->begin(); it != permissions_list->end(); ++it) { if (it->find(kDelimiter) != std::string::npos) { size_t delimiter = it->find(kDelimiter); std::string permission_name = it->substr(0, delimiter); std::string permission_arg = it->substr(delimiter + 1); scoped_ptr<base::Value> permission_json( base::JSONReader::Read(permission_arg)); if (!permission_json.get()) { *error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it); return NULL; } APIPermission* permission = NULL; const APIPermissionInfo* bluetooth_device_permission_info = info->GetByID(APIPermission::kBluetoothDevice); const APIPermissionInfo* usb_device_permission_info = info->GetByID(APIPermission::kUsbDevice); if (permission_name == bluetooth_device_permission_info->name()) { permission = new BluetoothDevicePermission( bluetooth_device_permission_info); } else if (permission_name == usb_device_permission_info->name()) { permission = new UsbDevicePermission(usb_device_permission_info); } else { *error = kUnsupportedPermissionId; return NULL; } CHECK(permission); if (!permission->FromValue(permission_json.get())) { *error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it); return NULL; } apis.insert(permission); } else { const APIPermissionInfo* permission_info = info->GetByName(*it); if (!permission_info) { *error = ErrorUtils::FormatErrorMessage( kUnknownPermissionError, *it); return NULL; } apis.insert(permission_info->id()); } } } URLPatternSet origins; if (permissions.origins.get()) { for (std::vector<std::string>::iterator it = permissions.origins->begin(); it != permissions.origins->end(); ++it) { int allowed_schemes = Extension::kValidHostPermissionSchemes; if (!allow_file_access) allowed_schemes &= ~URLPattern::SCHEME_FILE; URLPattern origin(allowed_schemes); URLPattern::ParseResult parse_result = origin.Parse(*it); if (URLPattern::PARSE_SUCCESS != parse_result) { *error = ErrorUtils::FormatErrorMessage( kInvalidOrigin, *it, URLPattern::GetParseResultString(parse_result)); return NULL; } origins.AddPattern(origin); } } return scoped_refptr<PermissionSet>( new PermissionSet(apis, origins, URLPatternSet())); }
19,006
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.
Code: SchedulerObject::hold(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Hold: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!holdJob(id.cluster, id.proc, reason.c_str(), true, // Always perform this action within a transaction true, // Always notify the shadow of the hold false, // Do not email the user about this action false, // Do not email admin about this action false // This is not a system related (internal) hold )) { text = "Failed to hold job"; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::hold(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Hold: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!holdJob(id.cluster, id.proc, reason.c_str(), true, // Always perform this action within a transaction true, // Always notify the shadow of the hold false, // Do not email the user about this action false, // Do not email admin about this action false // This is not a system related (internal) hold )) { text = "Failed to hold job"; return false; } return true; }
27,567
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.
Code: static void mark_object(struct object *obj, struct strbuf *path, const char *name, void *data) { update_progress(data); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com> CWE ID: CWE-119
static void mark_object(struct object *obj, struct strbuf *path, static void mark_object(struct object *obj, const char *name, void *data) { update_progress(data); }
15,806
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.
Code: fbOver (CARD32 x, CARD32 y) { PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); CARD32 fbOver (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o,p; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); p = FbOverU(x,y,24,a,t); return m|n|o|p; } CARD32 fbOver24 (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); return m|n|o; } CARD32 fbIn (CARD32 x, CARD8 y) { CARD16 a = y; CARD16 t; CARD32 m,n,o,p; m = FbInU(x,0,a,t); n = FbInU(x,8,a,t); o = FbInU(x,16,a,t); p = FbInU(x,24,a,t); return m|n|o|p; } #define genericCombine24(a,b,c,d) (((a)*(c)+(b)*(d))) /* * This macro does src IN mask OVER dst when src and dst are 0888. * If src has alpha, this will not work */ #define inOver0888(alpha, source, destval, dest) { \ CARD32 dstrb=destval&0xFF00FF; CARD32 dstag=(destval>>8)&0xFF00FF; \ CARD32 drb=((source&0xFF00FF)-dstrb)*alpha; CARD32 dag=(((source>>8)&0xFF00FF)-dstag)*alpha; \ WRITE(dest, ((((drb>>8) + dstrb) & 0x00FF00FF) | ((((dag>>8) + dstag) << 8) & 0xFF00FF00))); \ } /* * This macro does src IN mask OVER dst when src and dst are 0565 and * mask is a 5-bit alpha value. Again, if src has alpha, this will not * work. */ #define inOver0565(alpha, source, destval, dest) { \ CARD16 dstrb = destval & 0xf81f; CARD16 dstg = destval & 0x7e0; \ CARD32 drb = ((source&0xf81f)-dstrb)*alpha; CARD32 dg=((source & 0x7e0)-dstg)*alpha; \ WRITE(dest, ((((drb>>5) + dstrb)&0xf81f) | (((dg>>5) + dstg) & 0x7e0))); \ } #define inOver2x0565(alpha, source, destval, dest) { \ CARD32 dstrb = destval & 0x07e0f81f; CARD32 dstg = (destval & 0xf81f07e0)>>5; \ CARD32 drb = ((source&0x07e0f81f)-dstrb)*alpha; CARD32 dg=(((source & 0xf81f07e0)>>5)-dstg)*alpha; \ WRITE(dest, ((((drb>>5) + dstrb)&0x07e0f81f) | ((((dg>>5) + dstg)<<5) & 0xf81f07e0))); \ } #if IMAGE_BYTE_ORDER == LSBFirst #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \ temp=count&3; \ where-=temp; \ workingWhere=(CARD32 *)where; \ workingVal=READ(workingWhere++); \ count=4-temp; \ workingVal>>=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)&0xff; (y)>>=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest>>=8; workingoDest|=(what<<24); ww--; if(!ww) { ww=4; WRITE (wodst++, workingoDest); } #else #warning "I havn't tested fbCompositeTrans_0888xnx0888() on big endian yet!" #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \ temp=count&3; \ where-=temp; \ workingWhere=(CARD32 *)where; \ workingVal=READ(workingWhere++); \ count=4-temp; \ workingVal<<=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)>>24; (y)<<=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest<<=8; workingoDest|=what; ww--; if(!ww) { ww=4; WRITE(wodst++, workingoDest); } #endif /* * Naming convention: * * opSRCxMASKxDST */ void fbCompositeSolidMask_nx8x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0xff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (m) { d = fbIn (src, m); WRITE(dst, fbOver (d, READ(dst)) & dstMask); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8888x8888C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o, p; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (ma) { d = READ(dst); #define FbInOverC(src,srca,msk,dst,i,result) { \ CARD16 __a = FbGet8(msk,i); \ CARD32 __t, __ta; \ CARD32 __i; \ __t = FbIntMult (FbGet8(src,i), __a,__i); \ __ta = (CARD8) ~FbIntMult (srca, __a,__i); \ __t = __t + FbIntMult(FbGet8(dst,i),__ta,__i); \ __t = (CARD32) (CARD8) (__t | (-(__t >> 8))); \ result = __t << (i); \ } FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); FbInOverC (src, srca, ma, d, 24, p); WRITE(dst, m|n|o|p); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } #define srcAlphaCombine24(a,b) genericCombine24(a,b,srca,srcia) void fbCompositeSolidMask_nx8x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca, srcia; CARD8 *dstLine, *dst, *edst; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; CARD32 rs,gs,bs,rd,gd,bd; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; srcia = 255-srca; if (src == 0) return; rs=src&0xff; gs=(src>>8)&0xff; bs=(src>>16)&0xff; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { /* fixme: cleanup unused */ unsigned long wt, wd; CARD32 workingiDest; CARD32 *widst; edst = dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; #ifndef NO_MASKED_PACKED_READ setupPackedReader(wd,wt,edst,widst,workingiDest); #endif while (w--) { #ifndef NO_MASKED_PACKED_READ readPackedDest(rd); readPackedDest(gd); readPackedDest(bd); #else rd = READ(edst++); gd = READ(edst++); bd = READ(edst++); #endif m = READ(mask++); if (m == 0xff) { if (srca == 0xff) { WRITE(dst++, rs); WRITE(dst++, gs); WRITE(dst++, bs); } else { WRITE(dst++, (srcAlphaCombine24(rs, rd)>>8)); WRITE(dst++, (srcAlphaCombine24(gs, gd)>>8)); WRITE(dst++, (srcAlphaCombine24(bs, bd)>>8)); } } else if (m) { int na=(srca*(int)m)>>8; int nia=255-na; WRITE(dst++, (genericCombine24(rs, rd, na, nia)>>8)); WRITE(dst++, (genericCombine24(gs, gd, na, nia)>>8)); WRITE(dst++, (genericCombine24(bs, bd, na, nia)>>8)); } else { dst+=3; } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 t; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w,src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = (src >> 24); srca5 = (srca8 >> 3); src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { d = READ(dst); if (m == 0xff) { t = fbOver24 (src, cvt0565to0888 (d)); } else { t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); } WRITE(dst++, cvt8888to0565 (t)); } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } static void fbCompositeSolidMask_nx8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 *maskLine, *mask; CARD32 t; CARD8 m; FbStride dstStride, maskStride; CARD16 w, src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = src >> 24; srca5 = srca8 >> 3; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++) >> 24; if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { if (m == 0xff) { d = READ(dst); t = fbOver24 (src, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } else { d = READ(dst); t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } } } } } void fbCompositeSolidMask_nx8888x0565C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD16 src16; CARD16 *dstLine, *dst; CARD32 d; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; if (src == 0) return; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) { WRITE(dst, src16); } else { d = READ(dst); d = fbOver24 (src, cvt0565to0888(d)); WRITE(dst, cvt8888to0565(d)); } } else if (ma) { d = READ(dst); d = cvt0565to0888(d); FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); d = m|n|o; WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst, dstMask; CARD32 *srcLine, *src, s; FbStride dstStride, srcStride; CARD8 a; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); dstMask = FbFullMask (pDst->pDrawable->depth); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a == 0xff) WRITE(dst, s & dstMask); else if (a) WRITE(dst, fbOver (s, READ(dst)) & dstMask); dst++; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else d = fbOver24 (s, Fetch24(dst)); Store24(dst,d); } dst += 3; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else { d = READ(dst); d = fbOver24 (s, cvt0565to0888(d)); } WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8000x8000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD8 s, d; CARD16 t; fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xff) { d = READ(dst); t = d + s; s = t | (0 - (t >> 8)); } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst; CARD32 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD32 s, d; CARD16 t; CARD32 m,n,o,p; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xffffffff) { d = READ(dst); if (d) { m = FbAdd(s,d,0,t); n = FbAdd(s,d,8,t); o = FbAdd(s,d,16,t); p = FbAdd(s,d,24,t); s = m|n|o|p; } } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } static void fbCompositeSrcAdd_8888x8x8 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *maskLine, *mask; FbStride dstStride, maskStride; CARD16 w; CARD32 src; CARD8 sa; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); fbComposeGetSolid (pSrc, src, pDst->format); sa = (src >> 24); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { CARD16 tmp; CARD16 a; CARD32 m, d; CARD32 r; a = READ(mask++); d = READ(dst); m = FbInU (sa, 0, a, tmp); r = FbAdd (m, d, 0, tmp); WRITE(dst++, r); } } fbFinishAccess(pDst->pDrawable); fbFinishAccess(pMask->pDrawable); } void fbCompositeSrcAdd_1000x1000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits, *srcBits; FbStride dstStride, srcStride; int dstBpp, srcBpp; int dstXoff, dstYoff; int srcXoff, srcYoff; fbGetDrawable(pSrc->pDrawable, srcBits, srcStride, srcBpp, srcXoff, srcYoff); fbGetDrawable(pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); fbBlt (srcBits + srcStride * (ySrc + srcYoff), srcStride, xSrc + srcXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, xDst + dstXoff, width, height, GXor, FB_ALLONES, srcBpp, FALSE, FALSE); fbFinishAccess(pDst->pDrawable); fbFinishAccess(pSrc->pDrawable); } void fbCompositeSolidMask_nx1xn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits; FbStip *maskBits; FbStride dstStride, maskStride; int dstBpp, maskBpp; int dstXoff, dstYoff; int maskXoff, maskYoff; FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); fbGetStipDrawable (pMask->pDrawable, maskBits, maskStride, maskBpp, maskXoff, maskYoff); fbGetDrawable (pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); switch (dstBpp) { case 32: break; case 24: break; case 16: src = cvt8888to0565(src); break; } src = fbReplicatePixel (src, dstBpp); fbBltOne (maskBits + maskStride * (yMask + maskYoff), maskStride, xMask + maskXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, (xDst + dstXoff) * dstBpp, dstBpp, width * dstBpp, height, 0x0, src, FB_ALLONES, 0x0); fbFinishAccess (pDst->pDrawable); fbFinishAccess (pMask->pDrawable); } # define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b)) /* * Apply a constant alpha value in an over computation */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); static void fbCompositeTrans_0565xnx0565(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD16 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD8 maskAlpha; CARD16 s_16, d_16; CARD32 s_32, d_32; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 27; if (!maskAlpha) return; if (maskAlpha == 0xff) { fbCompositeSrcSrc_nxn (PictOpSrc, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } fbComposeGetStart (pSrc, xSrc, ySrc, CARD16, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { CARD32 *isrc, *idst; dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; if(((long)src&1)==1) { s_16 = READ(src++); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w--; } isrc=(CARD32 *)src; if(((long)dst&1)==0) { idst=(CARD32 *)dst; while (w>1) { s_32 = READ(isrc++); d_32 = READ(idst); inOver2x0565(maskAlpha, s_32, d_32, idst++); w-=2; } dst=(CARD16 *)idst; } else { while (w > 1) { s_32 = READ(isrc++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32&0xffff; #else s_16=s_32>>16; #endif d_16 = READ(dst); inOver0565 (maskAlpha, s_16, d_16, dst++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32>>16; #else s_16=s_32&0xffff; #endif d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w-=2; } } src=(CARD16 *)isrc; if(w!=0) { s_16 = READ(src); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst); } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } /* macros for "i can't believe it's not fast" packed pixel handling */ #define alphamaskCombine24(a,b) genericCombine24(a,b,maskAlpha,maskiAlpha) static void fbCompositeTrans_0888xnx0888(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst,*idst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD16 maskAlpha,maskiAlpha; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 24; maskiAlpha= 255-maskAlpha; if (!maskAlpha) return; /* if (maskAlpha == 0xff) { fbCompositeSrc_0888x0888 (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } */ fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 3); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); { unsigned long ws,wt; CARD32 workingSource; CARD32 *wsrc, *wdst, *widst; CARD32 rs, rd, nd; CARD8 *isrc; /* are xSrc and xDst at the same alignment? if not, we need to be complicated :) */ /* if(0==0) */ if ((((xSrc * 3) & 3) != ((xDst * 3) & 3)) || ((srcStride & 3) != (dstStride & 3))) { while (height--) { dst = dstLine; dstLine += dstStride; isrc = src = srcLine; srcLine += srcStride; w = width*3; setupPackedReader(ws,wt,isrc,wsrc,workingSource); /* get to word aligned */ switch(~(long)dst&3) { case 1: readPackedSource(rs); /* *dst++=alphamaskCombine24(rs, *dst)>>8; */ rd = READ(dst); /* make gcc happy. hope it doens't cost us too much performance*/ WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 3: readPackedSource(rs); rd = READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; } wdst=(CARD32 *)dst; while (w>3) { rs=READ(wsrc++); /* FIXME: write a special readPackedWord macro, which knows how to * halfword combine */ #if IMAGE_BYTE_ORDER == LSBFirst rd=READ(wdst); readPackedSource(nd); readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<24; #else readPackedSource(nd); nd<<=24; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs; #endif inOver0888(maskAlpha, nd, rd, wdst++); w-=4; } src=(CARD8 *)wdst; switch(w) { case 3: readPackedSource(rs); rd=READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd)>>8); case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); case 1: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); } } } else { while (height--) { idst=dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width*3; /* get to word aligned */ switch(~(long)src&3) { case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; } wsrc=(CARD32 *)src; widst=(CARD32 *)dst; while(w>3) { rs = READ(wsrc++); rd = READ(widst); inOver0888 (maskAlpha, rs, rd, widst++); w-=4; } src=(CARD8 *)wsrc; dst=(CARD8 *)widst; switch(w) { case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); } } } } } /* * Simple bitblt */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dst; FbBits *src; FbStride dstStride, srcStride; int srcXoff, srcYoff; int dstXoff, dstYoff; int srcBpp; int dstBpp; Bool reverse = FALSE; Bool upsidedown = FALSE; fbGetDrawable(pSrc->pDrawable,src,srcStride,srcBpp,srcXoff,srcYoff); fbGetDrawable(pDst->pDrawable,dst,dstStride,dstBpp,dstXoff,dstYoff); fbBlt (src + (ySrc + srcYoff) * srcStride, srcStride, (xSrc + srcXoff) * srcBpp, dst + (yDst + dstYoff) * dstStride, dstStride, (xDst + dstXoff) * dstBpp, (width) * dstBpp, (height), GXcopy, FB_ALLONES, dstBpp, reverse, upsidedown); fbFinishAccess(pSrc->pDrawable); fbFinishAccess(pDst->pDrawable); } /* * Solid fill void fbCompositeSolidSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { } */ #define SCANLINE_BUFFER_LENGTH 2048 static void fbCompositeRectWrapper (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH * 3]; CARD32 *scanline_buffer = _scanline_buffer; FbComposeData data; data.op = op; data.src = pSrc; data.mask = pMask; data.dest = pDst; data.xSrc = xSrc; data.ySrc = ySrc; data.xMask = xMask; } void fbComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x8888mmx; else CARD16 width, CARD16 height) { RegionRec region; int n; BoxPtr pbox; CompositeFunc func = NULL; Bool srcRepeat = pSrc->pDrawable && pSrc->repeatType == RepeatNormal; Bool maskRepeat = FALSE; Bool srcTransform = pSrc->transform != 0; break; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; int w, h, w_this, h_this; #ifdef USE_MMX static Bool mmx_setup = FALSE; func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif } #endif xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; if (pSrc->pDrawable) { xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; } if (srcRepeat && srcTransform && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) else if (pMask && pMask->pDrawable) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; maskRepeat = pMask->repeatType == RepeatNormal; if (pMask->filter == PictFilterConvolution) } else { switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; default: break; } } else { switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: { FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); if ((src & 0xff000000) == 0xff000000) func = fbCompositeSolidMask_nx1xn; break; } default: break; } break; default: break; } Commit Message: CWE ID: CWE-189
fbOver (CARD32 x, CARD32 y) { PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); CARD32 fbOver (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o,p; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); p = FbOverU(x,y,24,a,t); return m|n|o|p; } CARD32 fbOver24 (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); return m|n|o; } CARD32 fbIn (CARD32 x, CARD8 y) { CARD16 a = y; CARD16 t; CARD32 m,n,o,p; m = FbInU(x,0,a,t); n = FbInU(x,8,a,t); o = FbInU(x,16,a,t); p = FbInU(x,24,a,t); return m|n|o|p; } #define genericCombine24(a,b,c,d) (((a)*(c)+(b)*(d))) /* * This macro does src IN mask OVER dst when src and dst are 0888. * If src has alpha, this will not work */ #define inOver0888(alpha, source, destval, dest) { \ CARD32 dstrb=destval&0xFF00FF; CARD32 dstag=(destval>>8)&0xFF00FF; \ CARD32 drb=((source&0xFF00FF)-dstrb)*alpha; CARD32 dag=(((source>>8)&0xFF00FF)-dstag)*alpha; \ WRITE(dest, ((((drb>>8) + dstrb) & 0x00FF00FF) | ((((dag>>8) + dstag) << 8) & 0xFF00FF00))); \ } /* * This macro does src IN mask OVER dst when src and dst are 0565 and * mask is a 5-bit alpha value. Again, if src has alpha, this will not * work. */ #define inOver0565(alpha, source, destval, dest) { \ CARD16 dstrb = destval & 0xf81f; CARD16 dstg = destval & 0x7e0; \ CARD32 drb = ((source&0xf81f)-dstrb)*alpha; CARD32 dg=((source & 0x7e0)-dstg)*alpha; \ WRITE(dest, ((((drb>>5) + dstrb)&0xf81f) | (((dg>>5) + dstg) & 0x7e0))); \ } #define inOver2x0565(alpha, source, destval, dest) { \ CARD32 dstrb = destval & 0x07e0f81f; CARD32 dstg = (destval & 0xf81f07e0)>>5; \ CARD32 drb = ((source&0x07e0f81f)-dstrb)*alpha; CARD32 dg=(((source & 0xf81f07e0)>>5)-dstg)*alpha; \ WRITE(dest, ((((drb>>5) + dstrb)&0x07e0f81f) | ((((dg>>5) + dstg)<<5) & 0xf81f07e0))); \ } #if IMAGE_BYTE_ORDER == LSBFirst #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \ temp=count&3; \ where-=temp; \ workingWhere=(CARD32 *)where; \ workingVal=READ(workingWhere++); \ count=4-temp; \ workingVal>>=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)&0xff; (y)>>=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest>>=8; workingoDest|=(what<<24); ww--; if(!ww) { ww=4; WRITE (wodst++, workingoDest); } #else #warning "I havn't tested fbCompositeTrans_0888xnx0888() on big endian yet!" #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \ temp=count&3; \ where-=temp; \ workingWhere=(CARD32 *)where; \ workingVal=READ(workingWhere++); \ count=4-temp; \ workingVal<<=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)>>24; (y)<<=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest<<=8; workingoDest|=what; ww--; if(!ww) { ww=4; WRITE(wodst++, workingoDest); } #endif /* * Naming convention: * * opSRCxMASKxDST */ void fbCompositeSolidMask_nx8x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0xff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (m) { d = fbIn (src, m); WRITE(dst, fbOver (d, READ(dst)) & dstMask); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8888x8888C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o, p; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (ma) { d = READ(dst); #define FbInOverC(src,srca,msk,dst,i,result) { \ CARD16 __a = FbGet8(msk,i); \ CARD32 __t, __ta; \ CARD32 __i; \ __t = FbIntMult (FbGet8(src,i), __a,__i); \ __ta = (CARD8) ~FbIntMult (srca, __a,__i); \ __t = __t + FbIntMult(FbGet8(dst,i),__ta,__i); \ __t = (CARD32) (CARD8) (__t | (-(__t >> 8))); \ result = __t << (i); \ } FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); FbInOverC (src, srca, ma, d, 24, p); WRITE(dst, m|n|o|p); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } #define srcAlphaCombine24(a,b) genericCombine24(a,b,srca,srcia) void fbCompositeSolidMask_nx8x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca, srcia; CARD8 *dstLine, *dst, *edst; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; CARD32 rs,gs,bs,rd,gd,bd; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; srcia = 255-srca; if (src == 0) return; rs=src&0xff; gs=(src>>8)&0xff; bs=(src>>16)&0xff; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { /* fixme: cleanup unused */ unsigned long wt, wd; CARD32 workingiDest; CARD32 *widst; edst = dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; #ifndef NO_MASKED_PACKED_READ setupPackedReader(wd,wt,edst,widst,workingiDest); #endif while (w--) { #ifndef NO_MASKED_PACKED_READ readPackedDest(rd); readPackedDest(gd); readPackedDest(bd); #else rd = READ(edst++); gd = READ(edst++); bd = READ(edst++); #endif m = READ(mask++); if (m == 0xff) { if (srca == 0xff) { WRITE(dst++, rs); WRITE(dst++, gs); WRITE(dst++, bs); } else { WRITE(dst++, (srcAlphaCombine24(rs, rd)>>8)); WRITE(dst++, (srcAlphaCombine24(gs, gd)>>8)); WRITE(dst++, (srcAlphaCombine24(bs, bd)>>8)); } } else if (m) { int na=(srca*(int)m)>>8; int nia=255-na; WRITE(dst++, (genericCombine24(rs, rd, na, nia)>>8)); WRITE(dst++, (genericCombine24(gs, gd, na, nia)>>8)); WRITE(dst++, (genericCombine24(bs, bd, na, nia)>>8)); } else { dst+=3; } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 t; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w,src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = (src >> 24); srca5 = (srca8 >> 3); src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { d = READ(dst); if (m == 0xff) { t = fbOver24 (src, cvt0565to0888 (d)); } else { t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); } WRITE(dst++, cvt8888to0565 (t)); } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } static void fbCompositeSolidMask_nx8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 *maskLine, *mask; CARD32 t; CARD8 m; FbStride dstStride, maskStride; CARD16 w, src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = src >> 24; srca5 = srca8 >> 3; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++) >> 24; if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { if (m == 0xff) { d = READ(dst); t = fbOver24 (src, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } else { d = READ(dst); t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } } } } } void fbCompositeSolidMask_nx8888x0565C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD16 src16; CARD16 *dstLine, *dst; CARD32 d; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; if (src == 0) return; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) { WRITE(dst, src16); } else { d = READ(dst); d = fbOver24 (src, cvt0565to0888(d)); WRITE(dst, cvt8888to0565(d)); } } else if (ma) { d = READ(dst); d = cvt0565to0888(d); FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); d = m|n|o; WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst, dstMask; CARD32 *srcLine, *src, s; FbStride dstStride, srcStride; CARD8 a; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); dstMask = FbFullMask (pDst->pDrawable->depth); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a == 0xff) WRITE(dst, s & dstMask); else if (a) WRITE(dst, fbOver (s, READ(dst)) & dstMask); dst++; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else d = fbOver24 (s, Fetch24(dst)); Store24(dst,d); } dst += 3; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else { d = READ(dst); d = fbOver24 (s, cvt0565to0888(d)); } WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8000x8000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD8 s, d; CARD16 t; fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xff) { d = READ(dst); t = d + s; s = t | (0 - (t >> 8)); } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst; CARD32 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD32 s, d; CARD16 t; CARD32 m,n,o,p; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xffffffff) { d = READ(dst); if (d) { m = FbAdd(s,d,0,t); n = FbAdd(s,d,8,t); o = FbAdd(s,d,16,t); p = FbAdd(s,d,24,t); s = m|n|o|p; } } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } static void fbCompositeSrcAdd_8888x8x8 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *maskLine, *mask; FbStride dstStride, maskStride; CARD16 w; CARD32 src; CARD8 sa; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); fbComposeGetSolid (pSrc, src, pDst->format); sa = (src >> 24); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { CARD16 tmp; CARD16 a; CARD32 m, d; CARD32 r; a = READ(mask++); d = READ(dst); m = FbInU (sa, 0, a, tmp); r = FbAdd (m, d, 0, tmp); WRITE(dst++, r); } } fbFinishAccess(pDst->pDrawable); fbFinishAccess(pMask->pDrawable); } void fbCompositeSrcAdd_1000x1000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits, *srcBits; FbStride dstStride, srcStride; int dstBpp, srcBpp; int dstXoff, dstYoff; int srcXoff, srcYoff; fbGetDrawable(pSrc->pDrawable, srcBits, srcStride, srcBpp, srcXoff, srcYoff); fbGetDrawable(pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); fbBlt (srcBits + srcStride * (ySrc + srcYoff), srcStride, xSrc + srcXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, xDst + dstXoff, width, height, GXor, FB_ALLONES, srcBpp, FALSE, FALSE); fbFinishAccess(pDst->pDrawable); fbFinishAccess(pSrc->pDrawable); } void fbCompositeSolidMask_nx1xn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits; FbStip *maskBits; FbStride dstStride, maskStride; int dstBpp, maskBpp; int dstXoff, dstYoff; int maskXoff, maskYoff; FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); fbGetStipDrawable (pMask->pDrawable, maskBits, maskStride, maskBpp, maskXoff, maskYoff); fbGetDrawable (pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); switch (dstBpp) { case 32: break; case 24: break; case 16: src = cvt8888to0565(src); break; } src = fbReplicatePixel (src, dstBpp); fbBltOne (maskBits + maskStride * (yMask + maskYoff), maskStride, xMask + maskXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, (xDst + dstXoff) * dstBpp, dstBpp, width * dstBpp, height, 0x0, src, FB_ALLONES, 0x0); fbFinishAccess (pDst->pDrawable); fbFinishAccess (pMask->pDrawable); } # define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b)) /* * Apply a constant alpha value in an over computation */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); static void fbCompositeTrans_0565xnx0565(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD16 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD8 maskAlpha; CARD16 s_16, d_16; CARD32 s_32, d_32; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 27; if (!maskAlpha) return; if (maskAlpha == 0xff) { fbCompositeSrcSrc_nxn (PictOpSrc, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } fbComposeGetStart (pSrc, xSrc, ySrc, CARD16, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { CARD32 *isrc, *idst; dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; if(((long)src&1)==1) { s_16 = READ(src++); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w--; } isrc=(CARD32 *)src; if(((long)dst&1)==0) { idst=(CARD32 *)dst; while (w>1) { s_32 = READ(isrc++); d_32 = READ(idst); inOver2x0565(maskAlpha, s_32, d_32, idst++); w-=2; } dst=(CARD16 *)idst; } else { while (w > 1) { s_32 = READ(isrc++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32&0xffff; #else s_16=s_32>>16; #endif d_16 = READ(dst); inOver0565 (maskAlpha, s_16, d_16, dst++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32>>16; #else s_16=s_32&0xffff; #endif d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w-=2; } } src=(CARD16 *)isrc; if(w!=0) { s_16 = READ(src); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst); } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } /* macros for "i can't believe it's not fast" packed pixel handling */ #define alphamaskCombine24(a,b) genericCombine24(a,b,maskAlpha,maskiAlpha) static void fbCompositeTrans_0888xnx0888(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst,*idst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD16 maskAlpha,maskiAlpha; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 24; maskiAlpha= 255-maskAlpha; if (!maskAlpha) return; /* if (maskAlpha == 0xff) { fbCompositeSrc_0888x0888 (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } */ fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 3); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); { unsigned long ws,wt; CARD32 workingSource; CARD32 *wsrc, *wdst, *widst; CARD32 rs, rd, nd; CARD8 *isrc; /* are xSrc and xDst at the same alignment? if not, we need to be complicated :) */ /* if(0==0) */ if ((((xSrc * 3) & 3) != ((xDst * 3) & 3)) || ((srcStride & 3) != (dstStride & 3))) { while (height--) { dst = dstLine; dstLine += dstStride; isrc = src = srcLine; srcLine += srcStride; w = width*3; setupPackedReader(ws,wt,isrc,wsrc,workingSource); /* get to word aligned */ switch(~(long)dst&3) { case 1: readPackedSource(rs); /* *dst++=alphamaskCombine24(rs, *dst)>>8; */ rd = READ(dst); /* make gcc happy. hope it doens't cost us too much performance*/ WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 3: readPackedSource(rs); rd = READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; } wdst=(CARD32 *)dst; while (w>3) { rs=READ(wsrc++); /* FIXME: write a special readPackedWord macro, which knows how to * halfword combine */ #if IMAGE_BYTE_ORDER == LSBFirst rd=READ(wdst); readPackedSource(nd); readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<24; #else readPackedSource(nd); nd<<=24; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs; #endif inOver0888(maskAlpha, nd, rd, wdst++); w-=4; } src=(CARD8 *)wdst; switch(w) { case 3: readPackedSource(rs); rd=READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd)>>8); case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); case 1: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); } } } else { while (height--) { idst=dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width*3; /* get to word aligned */ switch(~(long)src&3) { case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; } wsrc=(CARD32 *)src; widst=(CARD32 *)dst; while(w>3) { rs = READ(wsrc++); rd = READ(widst); inOver0888 (maskAlpha, rs, rd, widst++); w-=4; } src=(CARD8 *)wsrc; dst=(CARD8 *)widst; switch(w) { case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); } } } } } /* * Simple bitblt */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dst; FbBits *src; FbStride dstStride, srcStride; int srcXoff, srcYoff; int dstXoff, dstYoff; int srcBpp; int dstBpp; Bool reverse = FALSE; Bool upsidedown = FALSE; fbGetDrawable(pSrc->pDrawable,src,srcStride,srcBpp,srcXoff,srcYoff); fbGetDrawable(pDst->pDrawable,dst,dstStride,dstBpp,dstXoff,dstYoff); fbBlt (src + (ySrc + srcYoff) * srcStride, srcStride, (xSrc + srcXoff) * srcBpp, dst + (yDst + dstYoff) * dstStride, dstStride, (xDst + dstXoff) * dstBpp, (width) * dstBpp, (height), GXcopy, FB_ALLONES, dstBpp, reverse, upsidedown); fbFinishAccess(pSrc->pDrawable); fbFinishAccess(pDst->pDrawable); } /* * Solid fill void fbCompositeSolidSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { } */ #define SCANLINE_BUFFER_LENGTH 2048 static void fbCompositeRectWrapper (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH * 3]; CARD32 *scanline_buffer = _scanline_buffer; FbComposeData data; data.op = op; data.src = pSrc; data.mask = pMask; data.dest = pDst; data.xSrc = xSrc; data.ySrc = ySrc; data.xMask = xMask; } void fbWalkCompositeRegion (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height, Bool srcRepeat, Bool maskRepeat, CompositeFunc compositeRect) { RegionRec region; int n; BoxPtr pbox; int w, h, w_this, h_this; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; if (pSrc->pDrawable) { xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; } if (pMask && pMask->pDrawable) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; } if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; y_msk += pMask->pDrawable->y; } if (srcRepeat) { y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; y_src += pSrc->pDrawable->y; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; x_msk += pMask->pDrawable->x; } if (srcRepeat) { x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; x_src += pSrc->pDrawable->x; } (*compositeRect) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); } void fbComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x8888mmx; else CARD16 width, CARD16 height) { Bool srcRepeat = pSrc->pDrawable && pSrc->repeatType == RepeatNormal; Bool maskRepeat = FALSE; Bool srcTransform = pSrc->transform != 0; break; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; CompositeFunc func = NULL; #ifdef USE_MMX static Bool mmx_setup = FALSE; func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif } #endif if (srcRepeat && srcTransform && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) else if (pMask && pMask->pDrawable) { maskRepeat = pMask->repeatType == RepeatNormal; if (pMask->filter == PictFilterConvolution) } else { switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; default: break; } } else { switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: { FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); if ((src & 0xff000000) == 0xff000000) func = fbCompositeSolidMask_nx1xn; break; } default: break; } break; default: break; }
7,933
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.
Code: void AutofillPopupBaseView::AddExtraInitParams( views::Widget::InitParams* params) { params->opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params->shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <rkaplow@chromium.org> Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org> Reviewed-by: Fabio Tirelo <ftirelo@chromium.org> Reviewed-by: Tommy Martino <tmartino@chromium.org> Commit-Queue: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
void AutofillPopupBaseView::AddExtraInitParams(
18,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.
Code: int xstateregs_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { struct fpu *fpu = &target->thread.fpu; struct xregs_state *xsave; int ret; if (!boot_cpu_has(X86_FEATURE_XSAVE)) return -ENODEV; /* * A whole standard-format XSAVE buffer is needed: */ if ((pos != 0) || (count < fpu_user_xstate_size)) return -EFAULT; xsave = &fpu->state.xsave; fpu__activate_fpstate_write(fpu); if (boot_cpu_has(X86_FEATURE_XSAVES)) { if (kbuf) ret = copy_kernel_to_xstate(xsave, kbuf); else ret = copy_user_to_xstate(xsave, ubuf); } else { ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, xsave, 0, -1); } /* * In case of failure, mark all states as init: */ if (ret) fpstate_init(&fpu->state); /* * mxcsr reserved bits must be masked to zero for security reasons. */ xsave->i387.mxcsr &= mxcsr_feature_mask; xsave->header.xfeatures &= xfeatures_mask; /* * These bits must be zero. */ memset(&xsave->header.reserved, 0, 48); return ret; } Commit Message: x86/fpu: Don't let userspace set bogus xcomp_bv On x86, userspace can use the ptrace() or rt_sigreturn() system calls to set a task's extended state (xstate) or "FPU" registers. ptrace() can set them for another task using the PTRACE_SETREGSET request with NT_X86_XSTATE, while rt_sigreturn() can set them for the current task. In either case, registers can be set to any value, but the kernel assumes that the XSAVE area itself remains valid in the sense that the CPU can restore it. However, in the case where the kernel is using the uncompacted xstate format (which it does whenever the XSAVES instruction is unavailable), it was possible for userspace to set the xcomp_bv field in the xstate_header to an arbitrary value. However, all bits in that field are reserved in the uncompacted case, so when switching to a task with nonzero xcomp_bv, the XRSTOR instruction failed with a #GP fault. This caused the WARN_ON_FPU(err) in copy_kernel_to_xregs() to be hit. In addition, since the error is otherwise ignored, the FPU registers from the task previously executing on the CPU were leaked. Fix the bug by checking that the user-supplied value of xcomp_bv is 0 in the uncompacted case, and returning an error otherwise. The reason for validating xcomp_bv rather than simply overwriting it with 0 is that we want userspace to see an error if it (incorrectly) provides an XSAVE area in compacted format rather than in uncompacted format. Note that as before, in case of error we clear the task's FPU state. This is perhaps non-ideal, especially for PTRACE_SETREGSET; it might be better to return an error before changing anything. But it seems the "clear on error" behavior is fine for now, and it's a little tricky to do otherwise because it would mean we couldn't simply copy the full userspace state into kernel memory in one __copy_from_user(). This bug was found by syzkaller, which hit the above-mentioned WARN_ON_FPU(): WARNING: CPU: 1 PID: 0 at ./arch/x86/include/asm/fpu/internal.h:373 __switch_to+0x5b5/0x5d0 CPU: 1 PID: 0 Comm: swapper/1 Not tainted 4.13.0 #453 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 task: ffff9ba2bc8e42c0 task.stack: ffffa78cc036c000 RIP: 0010:__switch_to+0x5b5/0x5d0 RSP: 0000:ffffa78cc08bbb88 EFLAGS: 00010082 RAX: 00000000fffffffe RBX: ffff9ba2b8bf2180 RCX: 00000000c0000100 RDX: 00000000ffffffff RSI: 000000005cb10700 RDI: ffff9ba2b8bf36c0 RBP: ffffa78cc08bbbd0 R08: 00000000929fdf46 R09: 0000000000000001 R10: 0000000000000000 R11: 0000000000000000 R12: ffff9ba2bc8e42c0 R13: 0000000000000000 R14: ffff9ba2b8bf3680 R15: ffff9ba2bf5d7b40 FS: 00007f7e5cb10700(0000) GS:ffff9ba2bf400000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00000000004005cc CR3: 0000000079fd5000 CR4: 00000000001406e0 Call Trace: Code: 84 00 00 00 00 00 e9 11 fd ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 e7 fa ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 c2 fa ff ff <0f> ff 66 0f 1f 84 00 00 00 00 00 e9 d4 fc ff ff 66 66 2e 0f 1f Here is a C reproducer. The expected behavior is that the program spin forever with no output. However, on a buggy kernel running on a processor with the "xsave" feature but without the "xsaves" feature (e.g. Sandy Bridge through Broadwell for Intel), within a second or two the program reports that the xmm registers were corrupted, i.e. were not restored correctly. With CONFIG_X86_DEBUG_FPU=y it also hits the above kernel warning. #define _GNU_SOURCE #include <stdbool.h> #include <inttypes.h> #include <linux/elf.h> #include <stdio.h> #include <sys/ptrace.h> #include <sys/uio.h> #include <sys/wait.h> #include <unistd.h> int main(void) { int pid = fork(); uint64_t xstate[512]; struct iovec iov = { .iov_base = xstate, .iov_len = sizeof(xstate) }; if (pid == 0) { bool tracee = true; for (int i = 0; i < sysconf(_SC_NPROCESSORS_ONLN) && tracee; i++) tracee = (fork() != 0); uint32_t xmm0[4] = { [0 ... 3] = tracee ? 0x00000000 : 0xDEADBEEF }; asm volatile(" movdqu %0, %%xmm0\n" " mov %0, %%rbx\n" "1: movdqu %%xmm0, %0\n" " mov %0, %%rax\n" " cmp %%rax, %%rbx\n" " je 1b\n" : "+m" (xmm0) : : "rax", "rbx", "xmm0"); printf("BUG: xmm registers corrupted! tracee=%d, xmm0=%08X%08X%08X%08X\n", tracee, xmm0[0], xmm0[1], xmm0[2], xmm0[3]); } else { usleep(100000); ptrace(PTRACE_ATTACH, pid, 0, 0); wait(NULL); ptrace(PTRACE_GETREGSET, pid, NT_X86_XSTATE, &iov); xstate[65] = -1; ptrace(PTRACE_SETREGSET, pid, NT_X86_XSTATE, &iov); ptrace(PTRACE_CONT, pid, 0, 0); wait(NULL); } return 1; } Note: the program only tests for the bug using the ptrace() system call. The bug can also be reproduced using the rt_sigreturn() system call, but only when called from a 32-bit program, since for 64-bit programs the kernel restores the FPU state from the signal frame by doing XRSTOR directly from userspace memory (with proper error checking). Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Biggers <ebiggers@google.com> Reviewed-by: Kees Cook <keescook@chromium.org> Reviewed-by: Rik van Riel <riel@redhat.com> Acked-by: Dave Hansen <dave.hansen@linux.intel.com> Cc: <stable@vger.kernel.org> [v3.17+] Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Andy Lutomirski <luto@amacapital.net> Cc: Andy Lutomirski <luto@kernel.org> Cc: Borislav Petkov <bp@alien8.de> Cc: Eric Biggers <ebiggers3@gmail.com> Cc: Fenghua Yu <fenghua.yu@intel.com> Cc: Kevin Hao <haokexin@gmail.com> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Michael Halcrow <mhalcrow@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Wanpeng Li <wanpeng.li@hotmail.com> Cc: Yu-cheng Yu <yu-cheng.yu@intel.com> Cc: kernel-hardening@lists.openwall.com Fixes: 0b29643a5843 ("x86/xsaves: Change compacted format xsave area header") Link: http://lkml.kernel.org/r/20170922174156.16780-2-ebiggers3@gmail.com Link: http://lkml.kernel.org/r/20170923130016.21448-25-mingo@kernel.org Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-200
int xstateregs_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { struct fpu *fpu = &target->thread.fpu; struct xregs_state *xsave; int ret; if (!boot_cpu_has(X86_FEATURE_XSAVE)) return -ENODEV; /* * A whole standard-format XSAVE buffer is needed: */ if ((pos != 0) || (count < fpu_user_xstate_size)) return -EFAULT; xsave = &fpu->state.xsave; fpu__activate_fpstate_write(fpu); if (boot_cpu_has(X86_FEATURE_XSAVES)) { if (kbuf) ret = copy_kernel_to_xstate(xsave, kbuf); else ret = copy_user_to_xstate(xsave, ubuf); } else { ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, xsave, 0, -1); /* xcomp_bv must be 0 when using uncompacted format */ if (!ret && xsave->header.xcomp_bv) ret = -EINVAL; } /* * In case of failure, mark all states as init: */ if (ret) fpstate_init(&fpu->state); /* * mxcsr reserved bits must be masked to zero for security reasons. */ xsave->i387.mxcsr &= mxcsr_feature_mask; xsave->header.xfeatures &= xfeatures_mask; /* * These bits must be zero. */ memset(&xsave->header.reserved, 0, 48); return ret; }
17,979
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.
Code: std::unique_ptr<JSONObject> TransformPaintPropertyNode::ToJSON() const { auto json = JSONObject::Create(); if (Parent()) json->SetString("parent", String::Format("%p", Parent())); if (!state_.matrix.IsIdentity()) json->SetString("matrix", state_.matrix.ToString()); if (!state_.matrix.IsIdentityOrTranslation()) json->SetString("origin", state_.origin.ToString()); if (!state_.flattens_inherited_transform) json->SetBoolean("flattensInheritedTransform", false); if (state_.backface_visibility != BackfaceVisibility::kInherited) { json->SetString("backface", state_.backface_visibility == BackfaceVisibility::kVisible ? "visible" : "hidden"); } if (state_.rendering_context_id) { json->SetString("renderingContextId", String::Format("%x", state_.rendering_context_id)); } if (state_.direct_compositing_reasons != CompositingReason::kNone) { json->SetString( "directCompositingReasons", CompositingReason::ToString(state_.direct_compositing_reasons)); } if (state_.compositor_element_id) { json->SetString("compositorElementId", state_.compositor_element_id.ToString().c_str()); } if (state_.scroll) json->SetString("scroll", String::Format("%p", state_.scroll.get())); return json; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <trchen@chromium.org> > > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > > Cr-Commit-Position: refs/heads/master@{#554626} > > TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > Cr-Commit-Position: refs/heads/master@{#554653} TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
std::unique_ptr<JSONObject> TransformPaintPropertyNode::ToJSON() const { auto json = JSONObject::Create(); if (Parent()) json->SetString("parent", String::Format("%p", Parent())); if (!state_.matrix.IsIdentity()) json->SetString("matrix", state_.matrix.ToString()); if (!state_.matrix.IsIdentityOrTranslation()) json->SetString("origin", state_.origin.ToString()); if (!state_.flattens_inherited_transform) json->SetBoolean("flattensInheritedTransform", false); if (state_.backface_visibility != BackfaceVisibility::kInherited) { json->SetString("backface", state_.backface_visibility == BackfaceVisibility::kVisible ? "visible" : "hidden"); } if (state_.rendering_context_id) { json->SetString("renderingContextId", String::Format("%x", state_.rendering_context_id)); } if (state_.direct_compositing_reasons != CompositingReason::kNone) { json->SetString( "directCompositingReasons", CompositingReason::ToString(state_.direct_compositing_reasons)); } if (state_.compositor_element_id) { json->SetString("compositorElementId", state_.compositor_element_id.ToString().c_str()); } if (state_.scroll) json->SetString("scroll", String::Format("%p", state_.scroll)); return json; }
28,538
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.
Code: void RenderProcessHostImpl::CreateMessageFilters() { DCHECK_CURRENTLY_ON(BrowserThread::UI); AddFilter(new ResourceSchedulerFilter(GetID())); MediaInternals* media_internals = MediaInternals::GetInstance(); scoped_refptr<BrowserPluginMessageFilter> bp_message_filter( new BrowserPluginMessageFilter(GetID())); AddFilter(bp_message_filter.get()); scoped_refptr<net::URLRequestContextGetter> request_context( storage_partition_impl_->GetURLRequestContext()); scoped_refptr<RenderMessageFilter> render_message_filter( new RenderMessageFilter( GetID(), GetBrowserContext(), request_context.get(), widget_helper_.get(), media_internals, storage_partition_impl_->GetDOMStorageContext(), storage_partition_impl_->GetCacheStorageContext())); AddFilter(render_message_filter.get()); render_frame_message_filter_ = new RenderFrameMessageFilter( GetID(), #if BUILDFLAG(ENABLE_PLUGINS) PluginServiceImpl::GetInstance(), #else nullptr, #endif GetBrowserContext(), request_context.get(), widget_helper_.get()); AddFilter(render_frame_message_filter_.get()); BrowserContext* browser_context = GetBrowserContext(); ResourceContext* resource_context = browser_context->GetResourceContext(); scoped_refptr<net::URLRequestContextGetter> media_request_context( GetStoragePartition()->GetMediaURLRequestContext()); ResourceMessageFilter::GetContextsCallback get_contexts_callback( base::Bind(&GetContexts, browser_context->GetResourceContext(), request_context, media_request_context)); scoped_refptr<ChromeBlobStorageContext> blob_storage_context = ChromeBlobStorageContext::GetFor(browser_context); resource_message_filter_ = new ResourceMessageFilter( GetID(), storage_partition_impl_->GetAppCacheService(), blob_storage_context.get(), storage_partition_impl_->GetFileSystemContext(), storage_partition_impl_->GetServiceWorkerContext(), get_contexts_callback); AddFilter(resource_message_filter_.get()); media::AudioManager* audio_manager = BrowserMainLoop::GetInstance()->audio_manager(); MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); audio_input_renderer_host_ = new AudioInputRendererHost( GetID(), base::GetProcId(GetHandle()), audio_manager, media_stream_manager, AudioMirroringManager::GetInstance(), BrowserMainLoop::GetInstance()->user_input_monitor()); AddFilter(audio_input_renderer_host_.get()); audio_renderer_host_ = new AudioRendererHost( GetID(), audio_manager, AudioMirroringManager::GetInstance(), media_stream_manager, browser_context->GetResourceContext()->GetMediaDeviceIDSalt()); AddFilter(audio_renderer_host_.get()); AddFilter( new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_service())); AddFilter(new AppCacheDispatcherHost( storage_partition_impl_->GetAppCacheService(), GetID())); AddFilter(new ClipboardMessageFilter(blob_storage_context)); AddFilter(new DOMStorageMessageFilter( storage_partition_impl_->GetDOMStorageContext())); #if BUILDFLAG(ENABLE_WEBRTC) peer_connection_tracker_host_ = new PeerConnectionTrackerHost( GetID(), webrtc_eventlog_host_.GetWeakPtr()); AddFilter(peer_connection_tracker_host_.get()); AddFilter(new MediaStreamDispatcherHost( GetID(), browser_context->GetResourceContext()->GetMediaDeviceIDSalt(), media_stream_manager)); AddFilter(new MediaStreamTrackMetricsHost()); #endif #if BUILDFLAG(ENABLE_PLUGINS) AddFilter(new PepperRendererConnection(GetID())); #endif AddFilter(new SpeechRecognitionDispatcherHost( GetID(), storage_partition_impl_->GetURLRequestContext())); AddFilter(new FileAPIMessageFilter( GetID(), storage_partition_impl_->GetURLRequestContext(), storage_partition_impl_->GetFileSystemContext(), blob_storage_context.get(), StreamContext::GetFor(browser_context))); AddFilter(new BlobDispatcherHost( GetID(), blob_storage_context, make_scoped_refptr(storage_partition_impl_->GetFileSystemContext()))); AddFilter(new FileUtilitiesMessageFilter(GetID())); AddFilter( new DatabaseMessageFilter(storage_partition_impl_->GetDatabaseTracker())); #if defined(OS_MACOSX) AddFilter(new TextInputClientMessageFilter()); #elif defined(OS_WIN) AddFilter(new DWriteFontProxyMessageFilter()); channel_->AddFilter(new FontCacheDispatcher()); #endif message_port_message_filter_ = new MessagePortMessageFilter( base::Bind(&RenderWidgetHelper::GetNextRoutingID, base::Unretained(widget_helper_.get()))); AddFilter(message_port_message_filter_.get()); scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter = new CacheStorageDispatcherHost(); cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext()); AddFilter(cache_storage_filter.get()); scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter = new ServiceWorkerDispatcherHost( GetID(), message_port_message_filter_.get(), resource_context); service_worker_filter->Init( storage_partition_impl_->GetServiceWorkerContext()); AddFilter(service_worker_filter.get()); AddFilter(new SharedWorkerMessageFilter( GetID(), resource_context, WorkerStoragePartition( storage_partition_impl_->GetURLRequestContext(), storage_partition_impl_->GetMediaURLRequestContext(), storage_partition_impl_->GetAppCacheService(), storage_partition_impl_->GetQuotaManager(), storage_partition_impl_->GetFileSystemContext(), storage_partition_impl_->GetDatabaseTracker(), storage_partition_impl_->GetIndexedDBContext(), storage_partition_impl_->GetServiceWorkerContext()), message_port_message_filter_.get())); #if BUILDFLAG(ENABLE_WEBRTC) p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost( resource_context, request_context.get()); AddFilter(p2p_socket_dispatcher_host_.get()); #endif AddFilter(new TraceMessageFilter(GetID())); AddFilter(new ResolveProxyMsgHelper(request_context.get())); AddFilter(new QuotaDispatcherHost( GetID(), storage_partition_impl_->GetQuotaManager(), GetContentClient()->browser()->CreateQuotaPermissionContext())); scoped_refptr<ServiceWorkerContextWrapper> service_worker_context( static_cast<ServiceWorkerContextWrapper*>( storage_partition_impl_->GetServiceWorkerContext())); notification_message_filter_ = new NotificationMessageFilter( GetID(), storage_partition_impl_->GetPlatformNotificationContext(), resource_context, service_worker_context, browser_context); AddFilter(notification_message_filter_.get()); AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER)); AddFilter(new HistogramMessageFilter()); AddFilter(new MemoryMessageFilter(this)); AddFilter(new PushMessagingMessageFilter( GetID(), storage_partition_impl_->GetServiceWorkerContext())); #if defined(OS_ANDROID) AddFilter(new ScreenOrientationListenerAndroid()); synchronous_compositor_filter_ = new SynchronousCompositorBrowserFilter(GetID()); AddFilter(synchronous_compositor_filter_.get()); #endif } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=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 Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID:
void RenderProcessHostImpl::CreateMessageFilters() { DCHECK_CURRENTLY_ON(BrowserThread::UI); AddFilter(new ResourceSchedulerFilter(GetID())); MediaInternals* media_internals = MediaInternals::GetInstance(); scoped_refptr<BrowserPluginMessageFilter> bp_message_filter( new BrowserPluginMessageFilter(GetID())); AddFilter(bp_message_filter.get()); scoped_refptr<net::URLRequestContextGetter> request_context( storage_partition_impl_->GetURLRequestContext()); scoped_refptr<RenderMessageFilter> render_message_filter( new RenderMessageFilter( GetID(), GetBrowserContext(), request_context.get(), widget_helper_.get(), media_internals, storage_partition_impl_->GetDOMStorageContext(), storage_partition_impl_->GetCacheStorageContext())); AddFilter(render_message_filter.get()); render_frame_message_filter_ = new RenderFrameMessageFilter( GetID(), #if BUILDFLAG(ENABLE_PLUGINS) PluginServiceImpl::GetInstance(), #else nullptr, #endif GetBrowserContext(), request_context.get(), widget_helper_.get()); AddFilter(render_frame_message_filter_.get()); BrowserContext* browser_context = GetBrowserContext(); ResourceContext* resource_context = browser_context->GetResourceContext(); scoped_refptr<net::URLRequestContextGetter> media_request_context( GetStoragePartition()->GetMediaURLRequestContext()); ResourceMessageFilter::GetContextsCallback get_contexts_callback( base::Bind(&GetContexts, browser_context->GetResourceContext(), request_context, media_request_context)); scoped_refptr<ChromeBlobStorageContext> blob_storage_context = ChromeBlobStorageContext::GetFor(browser_context); resource_message_filter_ = new ResourceMessageFilter( GetID(), storage_partition_impl_->GetAppCacheService(), blob_storage_context.get(), storage_partition_impl_->GetFileSystemContext(), storage_partition_impl_->GetServiceWorkerContext(), get_contexts_callback); AddFilter(resource_message_filter_.get()); media::AudioManager* audio_manager = BrowserMainLoop::GetInstance()->audio_manager(); MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); audio_input_renderer_host_ = new AudioInputRendererHost( GetID(), base::GetProcId(GetHandle()), audio_manager, media_stream_manager, AudioMirroringManager::GetInstance(), BrowserMainLoop::GetInstance()->user_input_monitor()); AddFilter(audio_input_renderer_host_.get()); audio_renderer_host_ = new AudioRendererHost( GetID(), audio_manager, BrowserMainLoop::GetInstance()->audio_system(), AudioMirroringManager::GetInstance(), media_stream_manager, browser_context->GetResourceContext()->GetMediaDeviceIDSalt()); AddFilter(audio_renderer_host_.get()); AddFilter( new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_service())); AddFilter(new AppCacheDispatcherHost( storage_partition_impl_->GetAppCacheService(), GetID())); AddFilter(new ClipboardMessageFilter(blob_storage_context)); AddFilter(new DOMStorageMessageFilter( storage_partition_impl_->GetDOMStorageContext())); #if BUILDFLAG(ENABLE_WEBRTC) peer_connection_tracker_host_ = new PeerConnectionTrackerHost( GetID(), webrtc_eventlog_host_.GetWeakPtr()); AddFilter(peer_connection_tracker_host_.get()); AddFilter(new MediaStreamDispatcherHost( GetID(), browser_context->GetResourceContext()->GetMediaDeviceIDSalt(), media_stream_manager)); AddFilter(new MediaStreamTrackMetricsHost()); #endif #if BUILDFLAG(ENABLE_PLUGINS) AddFilter(new PepperRendererConnection(GetID())); #endif AddFilter(new SpeechRecognitionDispatcherHost( GetID(), storage_partition_impl_->GetURLRequestContext())); AddFilter(new FileAPIMessageFilter( GetID(), storage_partition_impl_->GetURLRequestContext(), storage_partition_impl_->GetFileSystemContext(), blob_storage_context.get(), StreamContext::GetFor(browser_context))); AddFilter(new BlobDispatcherHost( GetID(), blob_storage_context, make_scoped_refptr(storage_partition_impl_->GetFileSystemContext()))); AddFilter(new FileUtilitiesMessageFilter(GetID())); AddFilter( new DatabaseMessageFilter(storage_partition_impl_->GetDatabaseTracker())); #if defined(OS_MACOSX) AddFilter(new TextInputClientMessageFilter()); #elif defined(OS_WIN) AddFilter(new DWriteFontProxyMessageFilter()); channel_->AddFilter(new FontCacheDispatcher()); #endif message_port_message_filter_ = new MessagePortMessageFilter( base::Bind(&RenderWidgetHelper::GetNextRoutingID, base::Unretained(widget_helper_.get()))); AddFilter(message_port_message_filter_.get()); scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter = new CacheStorageDispatcherHost(); cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext()); AddFilter(cache_storage_filter.get()); scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter = new ServiceWorkerDispatcherHost( GetID(), message_port_message_filter_.get(), resource_context); service_worker_filter->Init( storage_partition_impl_->GetServiceWorkerContext()); AddFilter(service_worker_filter.get()); AddFilter(new SharedWorkerMessageFilter( GetID(), resource_context, WorkerStoragePartition( storage_partition_impl_->GetURLRequestContext(), storage_partition_impl_->GetMediaURLRequestContext(), storage_partition_impl_->GetAppCacheService(), storage_partition_impl_->GetQuotaManager(), storage_partition_impl_->GetFileSystemContext(), storage_partition_impl_->GetDatabaseTracker(), storage_partition_impl_->GetIndexedDBContext(), storage_partition_impl_->GetServiceWorkerContext()), message_port_message_filter_.get())); #if BUILDFLAG(ENABLE_WEBRTC) p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost( resource_context, request_context.get()); AddFilter(p2p_socket_dispatcher_host_.get()); #endif AddFilter(new TraceMessageFilter(GetID())); AddFilter(new ResolveProxyMsgHelper(request_context.get())); AddFilter(new QuotaDispatcherHost( GetID(), storage_partition_impl_->GetQuotaManager(), GetContentClient()->browser()->CreateQuotaPermissionContext())); scoped_refptr<ServiceWorkerContextWrapper> service_worker_context( static_cast<ServiceWorkerContextWrapper*>( storage_partition_impl_->GetServiceWorkerContext())); notification_message_filter_ = new NotificationMessageFilter( GetID(), storage_partition_impl_->GetPlatformNotificationContext(), resource_context, service_worker_context, browser_context); AddFilter(notification_message_filter_.get()); AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER)); AddFilter(new HistogramMessageFilter()); AddFilter(new MemoryMessageFilter(this)); AddFilter(new PushMessagingMessageFilter( GetID(), storage_partition_impl_->GetServiceWorkerContext())); #if defined(OS_ANDROID) AddFilter(new ScreenOrientationListenerAndroid()); synchronous_compositor_filter_ = new SynchronousCompositorBrowserFilter(GetID()); AddFilter(synchronous_compositor_filter_.get()); #endif }
12,554
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.
Code: void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) { if (U_FAILURE(*status)) return; const icu::UnicodeSet* recommended_set = uspoof_getRecommendedUnicodeSet(status); icu::UnicodeSet allowed_set; allowed_set.addAll(*recommended_set); const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status); allowed_set.addAll(*inclusion_set); allowed_set.remove(0x338u); allowed_set.remove(0x58au); // Armenian Hyphen allowed_set.remove(0x2010u); allowed_set.remove(0x2019u); // Right Single Quotation Mark allowed_set.remove(0x2027u); allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe #if defined(OS_MACOSX) allowed_set.remove(0x0620u); allowed_set.remove(0x0F8Cu); allowed_set.remove(0x0F8Du); allowed_set.remove(0x0F8Eu); allowed_set.remove(0x0F8Fu); #endif allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status); } Commit Message: Block modifier-letter-voicing character from domain names This character (ˬ) is easy to miss between other characters. It's one of the three characters from Spacing-Modifier-Letters block that ICU lists in its recommended set in uspoof.cpp. Two of these characters (modifier-letter-turned-comma and modifier-letter-apostrophe) are already blocked in crbug/678812. Bug: 896717 Change-Id: I24b2b591de8cc7822cd55aa005b15676be91175e Reviewed-on: https://chromium-review.googlesource.com/c/1303037 Commit-Queue: Mustafa Emre Acer <meacer@chromium.org> Reviewed-by: Tommy Li <tommycli@chromium.org> Cr-Commit-Position: refs/heads/master@{#604128} CWE ID: CWE-20
void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) { if (U_FAILURE(*status)) return; const icu::UnicodeSet* recommended_set = uspoof_getRecommendedUnicodeSet(status); icu::UnicodeSet allowed_set; allowed_set.addAll(*recommended_set); const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status); allowed_set.addAll(*inclusion_set); allowed_set.remove(0x338u); allowed_set.remove(0x58au); // Armenian Hyphen allowed_set.remove(0x2010u); allowed_set.remove(0x2019u); // Right Single Quotation Mark allowed_set.remove(0x2027u); allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe // Block modifier letter voicing. allowed_set.remove(0x2ecu); #if defined(OS_MACOSX) allowed_set.remove(0x0620u); allowed_set.remove(0x0F8Cu); allowed_set.remove(0x0F8Du); allowed_set.remove(0x0F8Eu); allowed_set.remove(0x0F8Fu); #endif allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status); }
22,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.
Code: void Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { } Commit Message: Don't report OnFirstSurfaceActivation for ui::Compositor Bug: 893850 Change-Id: Iee754cefbd083d0a21a2b672fb8e837eaab81c43 Reviewed-on: https://chromium-review.googlesource.com/c/1293712 Reviewed-by: Antoine Labour <piman@chromium.org> Commit-Queue: Saman Sami <samans@chromium.org> Cr-Commit-Position: refs/heads/master@{#601629} CWE ID: CWE-20
void Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { NOTREACHED(); }
2,409
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.
Code: static __init int seqgen_init(void) { rekey_seq_generator(NULL); return 0; } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <dan@doxpara.com> Tested-by: Willy Tarreau <w@1wt.eu> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
static __init int seqgen_init(void) get_random_bytes(random_int_secret, sizeof(random_int_secret)); return 0; }
29,294
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.
Code: check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { char path[PATH_MAX]; struct passwd *pwd; { char path[PATH_MAX]; struct passwd *pwd; FILE *fp; int i, save_errno; uid_t fsuid; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); save_errno = errno; setfsuid(fsuid); if (fp != NULL) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } } Commit Message: CWE ID: CWE-399
check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { char path[PATH_MAX]; struct passwd *pwd; { char path[PATH_MAX]; struct passwd *pwd; FILE *fp = NULL; int i, fd = -1, save_errno; uid_t fsuid; struct stat st; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); if (!stat(path, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; else fd = open(path, O_RDONLY | O_NOCTTY); } save_errno = errno; setfsuid(fsuid); if (fd >= 0) { if (!fstat(fd, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; else fp = fdopen(fd, "r"); } if (!fp) { save_errno = errno; close(fd); } } if (fp) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } }
17,423
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.
Code: bool GestureSequence::PinchUpdate(const TouchEvent& event, const GesturePoint& point, Gestures* gestures) { DCHECK(state_ == GS_PINCH); float distance = points_[0].Distance(points_[1]); if (abs(distance - pinch_distance_current_) < kMinimumPinchUpdateDistance) { if (!points_[0].DidScroll(event, kMinimumDistanceForPinchScroll) || !points_[1].DidScroll(event, kMinimumDistanceForPinchScroll)) return false; gfx::Point center = points_[0].last_touch_position().Middle( points_[1].last_touch_position()); AppendScrollGestureUpdate(point, center, gestures); } else { AppendPinchGestureUpdate(points_[0], points_[1], distance / pinch_distance_current_, gestures); pinch_distance_current_ = distance; } return true; } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool GestureSequence::PinchUpdate(const TouchEvent& event, const GesturePoint& point, Gestures* gestures) { DCHECK(state_ == GS_PINCH); float distance = points_[0].Distance(points_[1]); if (abs(distance - pinch_distance_current_) < GestureConfiguration::minimum_pinch_update_distance_in_pixels()) { if (!points_[0].DidScroll(event, GestureConfiguration::minimum_distance_for_pinch_scroll_in_pixels()) || !points_[1].DidScroll(event, GestureConfiguration::minimum_distance_for_pinch_scroll_in_pixels())) return false; gfx::Point center = points_[0].last_touch_position().Middle( points_[1].last_touch_position()); AppendScrollGestureUpdate(point, center, gestures); } else { AppendPinchGestureUpdate(points_[0], points_[1], distance / pinch_distance_current_, gestures); pinch_distance_current_ = distance; } return true; }
18,489
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.
Code: void LocalFileSystem::requestFileSystem(ExecutionContext* context, FileSystemType type, long long size, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::fileSystemAllowedInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::requestFileSystem(ExecutionContext* context, FileSystemType type, long long size, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); CallbackWrapper* wrapper = new CallbackWrapper(callbacks); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::fileSystemAllowedInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); }
21,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.
Code: void XMLHttpRequest::didTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); clearResponse(); clearRequest(); m_error = true; m_exceptionCode = TimeoutError; if (!m_async) { m_state = DONE; m_exceptionCode = TimeoutError; return; } changeState(DONE); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::didTimeout() void XMLHttpRequest::handleDidTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); m_exceptionCode = TimeoutError; handleDidFailGeneric(); if (!m_async) { m_state = DONE; return; } changeState(DONE); dispatchEventAndLoadEnd(eventNames().timeoutEvent); }
13,650
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.
Code: void unix_notinflight(struct file *fp) { struct sock *s = unix_get_socket(fp); if (s) { struct unix_sock *u = unix_sk(s); spin_lock(&unix_gc_lock); BUG_ON(list_empty(&u->link)); if (atomic_long_dec_and_test(&u->inflight)) list_del_init(&u->link); unix_tot_inflight--; spin_unlock(&unix_gc_lock); } } Commit Message: unix: properly account for FDs passed over unix sockets It is possible for a process to allocate and accumulate far more FDs than the process' limit by sending them over a unix socket then closing them to keep the process' fd count low. This change addresses this problem by keeping track of the number of FDs in flight per user and preventing non-privileged processes from having more FDs in flight than their configured FD limit. Reported-by: socketpair@gmail.com Reported-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: Willy Tarreau <w@1wt.eu> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
void unix_notinflight(struct file *fp) { struct sock *s = unix_get_socket(fp); spin_lock(&unix_gc_lock); if (s) { struct unix_sock *u = unix_sk(s); BUG_ON(list_empty(&u->link)); if (atomic_long_dec_and_test(&u->inflight)) list_del_init(&u->link); unix_tot_inflight--; } fp->f_cred->user->unix_inflight--; spin_unlock(&unix_gc_lock); }
24,734
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.
Code: void BufferQueueConsumer::dump(String8& result, const char* prefix) const { const IPCThreadState* ipc = IPCThreadState::self(); const pid_t pid = ipc->getCallingPid(); const uid_t uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(String16( "android.permission.DUMP"), pid, uid)) { result.appendFormat("Permission Denial: can't dump BufferQueueConsumer " "from pid=%d, uid=%d\n", pid, uid); } else { mCore->dump(result, prefix); } } Commit Message: Add SN logging Bug 27046057 Change-Id: Iede7c92e59e60795df1ec7768ebafd6b090f1c27 CWE ID: CWE-264
void BufferQueueConsumer::dump(String8& result, const char* prefix) const { const IPCThreadState* ipc = IPCThreadState::self(); const pid_t pid = ipc->getCallingPid(); const uid_t uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(String16( "android.permission.DUMP"), pid, uid)) { result.appendFormat("Permission Denial: can't dump BufferQueueConsumer " "from pid=%d, uid=%d\n", pid, uid); android_errorWriteWithInfoLog(0x534e4554, "27046057", uid, NULL, 0); } else { mCore->dump(result, prefix); } }
27,228
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.
Code: isofs_export_encode_fh(struct inode *inode, __u32 *fh32, int *max_len, struct inode *parent) { struct iso_inode_info * ei = ISOFS_I(inode); int len = *max_len; int type = 1; __u16 *fh16 = (__u16*)fh32; /* * WARNING: max_len is 5 for NFSv2. Because of this * limitation, we use the lower 16 bits of fh32[1] to hold the * offset of the inode and the upper 16 bits of fh32[1] to * hold the offset of the parent. */ if (parent && (len < 5)) { *max_len = 5; return 255; } else if (len < 3) { *max_len = 3; return 255; } len = 3; fh32[0] = ei->i_iget5_block; fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */ fh32[2] = inode->i_generation; if (parent) { struct iso_inode_info *eparent; eparent = ISOFS_I(parent); fh32[3] = eparent->i_iget5_block; fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */ fh32[4] = parent->i_generation; len = 5; type = 2; } *max_len = len; return type; } Commit Message: isofs: avoid info leak on export For type 1 the parent_offset member in struct isofs_fid gets copied uninitialized to userland. Fix this by initializing it to 0. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-200
isofs_export_encode_fh(struct inode *inode, __u32 *fh32, int *max_len, struct inode *parent) { struct iso_inode_info * ei = ISOFS_I(inode); int len = *max_len; int type = 1; __u16 *fh16 = (__u16*)fh32; /* * WARNING: max_len is 5 for NFSv2. Because of this * limitation, we use the lower 16 bits of fh32[1] to hold the * offset of the inode and the upper 16 bits of fh32[1] to * hold the offset of the parent. */ if (parent && (len < 5)) { *max_len = 5; return 255; } else if (len < 3) { *max_len = 3; return 255; } len = 3; fh32[0] = ei->i_iget5_block; fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */ fh16[3] = 0; /* avoid leaking uninitialized data */ fh32[2] = inode->i_generation; if (parent) { struct iso_inode_info *eparent; eparent = ISOFS_I(parent); fh32[3] = eparent->i_iget5_block; fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */ fh32[4] = parent->i_generation; len = 5; type = 2; } *max_len = len; return type; }
27,123
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.
Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { p=DestroyImage(p); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare("interpolate",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,"", "=","\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,"cache:%s", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1623 CWE ID: CWE-399
WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); image=DestroyImage(image); status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); image=DestroyImage(image); status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); new_images=DestroyImage(new_images); status=MagickFalse; break; } /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); image=DestroyImage(image); status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); magnitude_image=DestroyImage(magnitude_image); status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); magnitude_image=DestroyImage(magnitude_image); phase_image=DestroyImage(phase_image); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { p=DestroyImage(p); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare("interpolate",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,"", "=","\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,"cache:%s", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); }
1,371
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.
Code: void mbedtls_strerror( int ret, char *buf, size_t buflen ) { size_t len; int use_ret; if( buflen == 0 ) return; memset( buf, 0x00, buflen ); if( ret < 0 ) ret = -ret; if( ret & 0xFF80 ) { use_ret = ret & 0xFF80; #if defined(MBEDTLS_CIPHER_C) if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "CIPHER - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "CIPHER - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) ) mbedtls_snprintf( buf, buflen, "CIPHER - Input data contains invalid padding and is rejected" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Decryption of block requires a full block" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) ) mbedtls_snprintf( buf, buflen, "CIPHER - The context is invalid, eg because it was free()ed" ); #endif /* MBEDTLS_CIPHER_C */ #if defined(MBEDTLS_DHM_C) if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "DHM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Making of the DHM parameters failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Reading of the public values failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Making of the public value failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Calculation of the DHM secret failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "DHM - The ASN.1 data is not formatted correctly" ); if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Allocation of memory failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "DHM - Read/write of file failed" ); #endif /* MBEDTLS_DHM_C */ #if defined(MBEDTLS_ECP_C) if( use_ret == -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "ECP - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "ECP - The buffer is too small to write to" ); if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "ECP - Requested curve not available" ); if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - The signature is not valid" ); if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - Generation of random value, such as (ephemeral) key, failed" ); if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) ) mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" ); if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) ) mbedtls_snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" ); #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_MD_C) if( use_ret == -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "MD - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_MD_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "MD - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_MD_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "MD - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "MD - Opening or reading of file failed" ); #endif /* MBEDTLS_MD_C */ #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) if( use_ret == -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) ) mbedtls_snprintf( buf, buflen, "PEM - No PEM header or footer found" ); if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_DATA) ) mbedtls_snprintf( buf, buflen, "PEM - PEM string is not as expected" ); if( use_ret == -(MBEDTLS_ERR_PEM_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "PEM - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_ENC_IV) ) mbedtls_snprintf( buf, buflen, "PEM - RSA IV is not in hex-format" ); if( use_ret == -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG) ) mbedtls_snprintf( buf, buflen, "PEM - Unsupported key encryption algorithm" ); if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) ) mbedtls_snprintf( buf, buflen, "PEM - Private key password can't be empty" ); if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PEM - Given private key password does not allow for correct decryption" ); if( use_ret == -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PEM - Unavailable feature, e.g. hashing/encryption combination" ); if( use_ret == -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PEM - Bad input parameters to function" ); #endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */ #if defined(MBEDTLS_PK_C) if( use_ret == -(MBEDTLS_ERR_PK_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "PK - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_PK_TYPE_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" ); if( use_ret == -(MBEDTLS_ERR_PK_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PK - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PK_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "PK - Read/write of file failed" ); if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION) ) mbedtls_snprintf( buf, buflen, "PK - Unsupported key version" ); if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PK - Invalid key tag or value" ); if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG) ) mbedtls_snprintf( buf, buflen, "PK - Key algorithm is unsupported (only RSA and EC are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED) ) mbedtls_snprintf( buf, buflen, "PK - Private key password can't be empty" ); if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - Given private key password does not allow for correct decryption" ); if( use_ret == -(MBEDTLS_ERR_PK_INVALID_PUBKEY) ) mbedtls_snprintf( buf, buflen, "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_INVALID_ALG) ) mbedtls_snprintf( buf, buflen, "PK - The algorithm tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE) ) mbedtls_snprintf( buf, buflen, "PK - Elliptic curve is unsupported (only NIST curves are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" ); if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" ); #endif /* MBEDTLS_PK_C */ #if defined(MBEDTLS_PKCS12_C) if( use_ret == -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Given private key password does not allow for correct decryption" ); #endif /* MBEDTLS_PKCS12_C */ #if defined(MBEDTLS_PKCS5_C) if( use_ret == -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Unexpected ASN.1 data" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Requested encryption or digest alg not available" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Given private key password does not allow for correct decryption" ); #endif /* MBEDTLS_PKCS5_C */ #if defined(MBEDTLS_RSA_C) if( use_ret == -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "RSA - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_RSA_INVALID_PADDING) ) mbedtls_snprintf( buf, buflen, "RSA - Input data contains invalid padding and is rejected" ); if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - Something failed during generation of a key" ); if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - Key failed to pass the library's validity check" ); if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The public key operation failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The private key operation failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The PKCS#1 verification failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE) ) mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" ); if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" ); #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_SSL_TLS_C) if( use_ret == -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "SSL - The requested feature is not available" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "SSL - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_MAC) ) mbedtls_snprintf( buf, buflen, "SSL - Verification of the message MAC failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_RECORD) ) mbedtls_snprintf( buf, buflen, "SSL - An invalid SSL record was received" ); if( use_ret == -(MBEDTLS_ERR_SSL_CONN_EOF) ) mbedtls_snprintf( buf, buflen, "SSL - The connection indicated an EOF" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) ) mbedtls_snprintf( buf, buflen, "SSL - An unknown cipher was received" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) ) mbedtls_snprintf( buf, buflen, "SSL - The server has no ciphersuites in common with the client" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_RNG) ) mbedtls_snprintf( buf, buflen, "SSL - No RNG was provided to the SSL module" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE) ) mbedtls_snprintf( buf, buflen, "SSL - No client certification received from the client, but required by the authentication mode" ); if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) ) mbedtls_snprintf( buf, buflen, "SSL - Our own certificate(s) is/are too large to send in an SSL message" ); if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - The own certificate is not set, but needed by the server" ); if( use_ret == -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - The own private key or pre-shared key is not set, but needed" ); if( use_ret == -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - No CA Chain is set, but required to operate" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) ) mbedtls_snprintf( buf, buflen, "SSL - An unexpected message was received from our peer" ); if( use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) ) { mbedtls_snprintf( buf, buflen, "SSL - A fatal alert message was received from our peer" ); return; } if( use_ret == -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Verification of our peer failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) ) mbedtls_snprintf( buf, buflen, "SSL - The peer notified us that the connection is going to be closed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientHello handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHello handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the Certificate handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateRequest handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerKeyExchange handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHelloDone handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateVerify handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ChangeCipherSpec handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the Finished handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function returned with error" ); if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH) ) mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function skipped / left alone data" ); if( use_ret == -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the compression / decompression failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) ) mbedtls_snprintf( buf, buflen, "SSL - Handshake protocol not within min/max boundaries" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the NewSessionTicket handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) ) mbedtls_snprintf( buf, buflen, "SSL - Session ticket has expired" ); if( use_ret == -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH) ) mbedtls_snprintf( buf, buflen, "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) ) mbedtls_snprintf( buf, buflen, "SSL - Unknown identity received (eg, PSK identity)" ); if( use_ret == -(MBEDTLS_ERR_SSL_INTERNAL_ERROR) ) mbedtls_snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" ); if( use_ret == -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING) ) mbedtls_snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" ); if( use_ret == -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) ) mbedtls_snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" ); if( use_ret == -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - DTLS client must retry for hello verification" ); if( use_ret == -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "SSL - A buffer is too small to receive or write a message" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) ) mbedtls_snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" ); if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) ) mbedtls_snprintf( buf, buflen, "SSL - Connection requires a read call" ); if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) ) mbedtls_snprintf( buf, buflen, "SSL - Connection requires a write call" ); if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) ) mbedtls_snprintf( buf, buflen, "SSL - The operation timed out" ); if( use_ret == -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT) ) mbedtls_snprintf( buf, buflen, "SSL - The client initiated a reconnect from the same port" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) ) mbedtls_snprintf( buf, buflen, "SSL - Record header looks valid but is not expected" ); if( use_ret == -(MBEDTLS_ERR_SSL_NON_FATAL) ) mbedtls_snprintf( buf, buflen, "SSL - The alert message received indicates a non-fatal error" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) ) mbedtls_snprintf( buf, buflen, "SSL - Couldn't set the hash for verifying CertificateVerify" ); #endif /* MBEDTLS_SSL_TLS_C */ #if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) if( use_ret == -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_OID) ) mbedtls_snprintf( buf, buflen, "X509 - Requested OID is unknown" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_VERSION) ) mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR version element is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SERIAL) ) mbedtls_snprintf( buf, buflen, "X509 - The serial tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_ALG) ) mbedtls_snprintf( buf, buflen, "X509 - The algorithm tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_NAME) ) mbedtls_snprintf( buf, buflen, "X509 - The name tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_DATE) ) mbedtls_snprintf( buf, buflen, "X509 - The date tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SIGNATURE) ) mbedtls_snprintf( buf, buflen, "X509 - The signature tag or value invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS) ) mbedtls_snprintf( buf, buflen, "X509 - The extension tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_VERSION) ) mbedtls_snprintf( buf, buflen, "X509 - CRT/CRL/CSR has an unsupported version number" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG) ) mbedtls_snprintf( buf, buflen, "X509 - Signature algorithm (oid) is unsupported" ); if( use_ret == -(MBEDTLS_ERR_X509_SIG_MISMATCH) ) mbedtls_snprintf( buf, buflen, "X509 - Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid)" ); if( use_ret == -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" ); if( use_ret == -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT) ) mbedtls_snprintf( buf, buflen, "X509 - Format not recognized as DER or PEM" ); if( use_ret == -(MBEDTLS_ERR_X509_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "X509 - Input invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "X509 - Allocation of memory failed" ); if( use_ret == -(MBEDTLS_ERR_X509_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "X509 - Read/write of file failed" ); if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "X509 - Destination buffer is too small" ); #endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */ if( strlen( buf ) == 0 ) mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret ); } use_ret = ret & ~0xFF80; if( use_ret == 0 ) return; len = strlen( buf ); if( len > 0 ) { if( buflen - len < 5 ) return; mbedtls_snprintf( buf + len, buflen - len, " : " ); buf += len + 3; buflen -= len + 3; } #if defined(MBEDTLS_AES_C) if( use_ret == -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "AES - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" ); #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_ASN1_PARSE_C) if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) ) mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" ); if( use_ret == -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) ) mbedtls_snprintf( buf, buflen, "ASN1 - ASN1 tag was of an unexpected value" ); if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_LENGTH) ) mbedtls_snprintf( buf, buflen, "ASN1 - Error when trying to determine the length or invalid length" ); if( use_ret == -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH) ) mbedtls_snprintf( buf, buflen, "ASN1 - Actual length differs from expected length" ); if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_DATA) ) mbedtls_snprintf( buf, buflen, "ASN1 - Data is invalid. (not used)" ); if( use_ret == -(MBEDTLS_ERR_ASN1_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "ASN1 - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "ASN1 - Buffer too small when writing ASN.1 data structure" ); #endif /* MBEDTLS_ASN1_PARSE_C */ #if defined(MBEDTLS_BASE64_C) if( use_ret == -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "BASE64 - Output buffer too small" ); if( use_ret == -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER) ) mbedtls_snprintf( buf, buflen, "BASE64 - Invalid character in input" ); #endif /* MBEDTLS_BASE64_C */ #if defined(MBEDTLS_BIGNUM_C) if( use_ret == -(MBEDTLS_ERR_MPI_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "BIGNUM - An error occurred while reading from or writing to a file" ); if( use_ret == -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "BIGNUM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_MPI_INVALID_CHARACTER) ) mbedtls_snprintf( buf, buflen, "BIGNUM - There is an invalid character in the digit string" ); if( use_ret == -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The buffer is too small to write to" ); if( use_ret == -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are negative or result in illegal output" ); if( use_ret == -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input argument for division is zero, which is not allowed" ); if( use_ret == -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are not acceptable" ); if( use_ret == -(MBEDTLS_ERR_MPI_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "BIGNUM - Memory allocation failed" ); #endif /* MBEDTLS_BIGNUM_C */ #if defined(MBEDTLS_BLOWFISH_C) if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" ); #endif /* MBEDTLS_BLOWFISH_C */ #if defined(MBEDTLS_CAMELLIA_C) if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" ); #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_CCM_C) if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) ) mbedtls_snprintf( buf, buflen, "CCM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "CCM - Authenticated decryption failed" ); #endif /* MBEDTLS_CCM_C */ #if defined(MBEDTLS_CTR_DRBG_C) if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Too many random requested in single call" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Input too large (Entropy + additional)" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Read/write error in file" ); #endif /* MBEDTLS_CTR_DRBG_C */ #if defined(MBEDTLS_DES_C) if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "DES - The data input has an invalid length" ); #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ENTROPY_C) if( use_ret == -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "ENTROPY - Critical entropy source failure" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No more sources can be added" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No sources have been added to poll" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No strong sources have been added to poll" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "ENTROPY - Read/write error in file" ); #endif /* MBEDTLS_ENTROPY_C */ #if defined(MBEDTLS_GCM_C) if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "GCM - Authenticated decryption failed" ); if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) ) mbedtls_snprintf( buf, buflen, "GCM - Bad input parameters to function" ); #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_HMAC_DRBG_C) if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Too many random requested in single call" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Input too large (Entropy + additional)" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Read/write error in file" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" ); #endif /* MBEDTLS_HMAC_DRBG_C */ #if defined(MBEDTLS_NET_C) if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Failed to open a socket" ); if( use_ret == -(MBEDTLS_ERR_NET_CONNECT_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - The connection to the given server / port failed" ); if( use_ret == -(MBEDTLS_ERR_NET_BIND_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Binding of the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_LISTEN_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Could not listen on the socket" ); if( use_ret == -(MBEDTLS_ERR_NET_ACCEPT_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Could not accept the incoming connection" ); if( use_ret == -(MBEDTLS_ERR_NET_RECV_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Reading information from the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_SEND_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Sending information through the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_CONN_RESET) ) mbedtls_snprintf( buf, buflen, "NET - Connection was reset by peer" ); if( use_ret == -(MBEDTLS_ERR_NET_UNKNOWN_HOST) ) mbedtls_snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" ); if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "NET - Buffer is too small to hold the data" ); if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) ) mbedtls_snprintf( buf, buflen, "NET - The context is invalid, eg because it was free()ed" ); #endif /* MBEDTLS_NET_C */ #if defined(MBEDTLS_OID_C) if( use_ret == -(MBEDTLS_ERR_OID_NOT_FOUND) ) mbedtls_snprintf( buf, buflen, "OID - OID is not found" ); if( use_ret == -(MBEDTLS_ERR_OID_BUF_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "OID - output buffer is too small" ); #endif /* MBEDTLS_OID_C */ #if defined(MBEDTLS_PADLOCK_C) if( use_ret == -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED) ) mbedtls_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" ); #endif /* MBEDTLS_PADLOCK_C */ #if defined(MBEDTLS_THREADING_C) if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "THREADING - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "THREADING - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_THREADING_MUTEX_ERROR) ) mbedtls_snprintf( buf, buflen, "THREADING - Locking / unlocking / free failed with error code" ); #endif /* MBEDTLS_THREADING_C */ #if defined(MBEDTLS_XTEA_C) if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "XTEA - The data input has an invalid length" ); #endif /* MBEDTLS_XTEA_C */ if( strlen( buf ) != 0 ) return; mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret ); } Commit Message: Only return VERIFY_FAILED from a single point Everything else is a fatal error. Also improve documentation about that for the vrfy callback. CWE ID: CWE-287
void mbedtls_strerror( int ret, char *buf, size_t buflen ) { size_t len; int use_ret; if( buflen == 0 ) return; memset( buf, 0x00, buflen ); if( ret < 0 ) ret = -ret; if( ret & 0xFF80 ) { use_ret = ret & 0xFF80; #if defined(MBEDTLS_CIPHER_C) if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "CIPHER - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "CIPHER - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) ) mbedtls_snprintf( buf, buflen, "CIPHER - Input data contains invalid padding and is rejected" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Decryption of block requires a full block" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" ); if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) ) mbedtls_snprintf( buf, buflen, "CIPHER - The context is invalid, eg because it was free()ed" ); #endif /* MBEDTLS_CIPHER_C */ #if defined(MBEDTLS_DHM_C) if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "DHM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Making of the DHM parameters failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Reading of the public values failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Making of the public value failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Calculation of the DHM secret failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "DHM - The ASN.1 data is not formatted correctly" ); if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "DHM - Allocation of memory failed" ); if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "DHM - Read/write of file failed" ); #endif /* MBEDTLS_DHM_C */ #if defined(MBEDTLS_ECP_C) if( use_ret == -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "ECP - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "ECP - The buffer is too small to write to" ); if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "ECP - Requested curve not available" ); if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - The signature is not valid" ); if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - Generation of random value, such as (ephemeral) key, failed" ); if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) ) mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" ); if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) ) mbedtls_snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" ); #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_MD_C) if( use_ret == -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "MD - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_MD_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "MD - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_MD_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "MD - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "MD - Opening or reading of file failed" ); #endif /* MBEDTLS_MD_C */ #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) if( use_ret == -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) ) mbedtls_snprintf( buf, buflen, "PEM - No PEM header or footer found" ); if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_DATA) ) mbedtls_snprintf( buf, buflen, "PEM - PEM string is not as expected" ); if( use_ret == -(MBEDTLS_ERR_PEM_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "PEM - Failed to allocate memory" ); if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_ENC_IV) ) mbedtls_snprintf( buf, buflen, "PEM - RSA IV is not in hex-format" ); if( use_ret == -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG) ) mbedtls_snprintf( buf, buflen, "PEM - Unsupported key encryption algorithm" ); if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) ) mbedtls_snprintf( buf, buflen, "PEM - Private key password can't be empty" ); if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PEM - Given private key password does not allow for correct decryption" ); if( use_ret == -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PEM - Unavailable feature, e.g. hashing/encryption combination" ); if( use_ret == -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PEM - Bad input parameters to function" ); #endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */ #if defined(MBEDTLS_PK_C) if( use_ret == -(MBEDTLS_ERR_PK_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "PK - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_PK_TYPE_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" ); if( use_ret == -(MBEDTLS_ERR_PK_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PK - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PK_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "PK - Read/write of file failed" ); if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION) ) mbedtls_snprintf( buf, buflen, "PK - Unsupported key version" ); if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PK - Invalid key tag or value" ); if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG) ) mbedtls_snprintf( buf, buflen, "PK - Key algorithm is unsupported (only RSA and EC are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED) ) mbedtls_snprintf( buf, buflen, "PK - Private key password can't be empty" ); if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - Given private key password does not allow for correct decryption" ); if( use_ret == -(MBEDTLS_ERR_PK_INVALID_PUBKEY) ) mbedtls_snprintf( buf, buflen, "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_INVALID_ALG) ) mbedtls_snprintf( buf, buflen, "PK - The algorithm tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE) ) mbedtls_snprintf( buf, buflen, "PK - Elliptic curve is unsupported (only NIST curves are supported)" ); if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" ); if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" ); #endif /* MBEDTLS_PK_C */ #if defined(MBEDTLS_PKCS12_C) if( use_ret == -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" ); if( use_ret == -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PKCS12 - Given private key password does not allow for correct decryption" ); #endif /* MBEDTLS_PKCS12_C */ #if defined(MBEDTLS_PKCS5_C) if( use_ret == -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Unexpected ASN.1 data" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Requested encryption or digest alg not available" ); if( use_ret == -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) ) mbedtls_snprintf( buf, buflen, "PKCS5 - Given private key password does not allow for correct decryption" ); #endif /* MBEDTLS_PKCS5_C */ #if defined(MBEDTLS_RSA_C) if( use_ret == -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "RSA - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_RSA_INVALID_PADDING) ) mbedtls_snprintf( buf, buflen, "RSA - Input data contains invalid padding and is rejected" ); if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - Something failed during generation of a key" ); if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - Key failed to pass the library's validity check" ); if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The public key operation failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The private key operation failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The PKCS#1 verification failed" ); if( use_ret == -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE) ) mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" ); if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) ) mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" ); #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_SSL_TLS_C) if( use_ret == -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "SSL - The requested feature is not available" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "SSL - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_MAC) ) mbedtls_snprintf( buf, buflen, "SSL - Verification of the message MAC failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_RECORD) ) mbedtls_snprintf( buf, buflen, "SSL - An invalid SSL record was received" ); if( use_ret == -(MBEDTLS_ERR_SSL_CONN_EOF) ) mbedtls_snprintf( buf, buflen, "SSL - The connection indicated an EOF" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) ) mbedtls_snprintf( buf, buflen, "SSL - An unknown cipher was received" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) ) mbedtls_snprintf( buf, buflen, "SSL - The server has no ciphersuites in common with the client" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_RNG) ) mbedtls_snprintf( buf, buflen, "SSL - No RNG was provided to the SSL module" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE) ) mbedtls_snprintf( buf, buflen, "SSL - No client certification received from the client, but required by the authentication mode" ); if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) ) mbedtls_snprintf( buf, buflen, "SSL - Our own certificate(s) is/are too large to send in an SSL message" ); if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - The own certificate is not set, but needed by the server" ); if( use_ret == -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - The own private key or pre-shared key is not set, but needed" ); if( use_ret == -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - No CA Chain is set, but required to operate" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) ) mbedtls_snprintf( buf, buflen, "SSL - An unexpected message was received from our peer" ); if( use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) ) { mbedtls_snprintf( buf, buflen, "SSL - A fatal alert message was received from our peer" ); return; } if( use_ret == -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Verification of our peer failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) ) mbedtls_snprintf( buf, buflen, "SSL - The peer notified us that the connection is going to be closed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientHello handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHello handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the Certificate handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateRequest handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerKeyExchange handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHelloDone handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateVerify handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the ChangeCipherSpec handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the Finished handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function returned with error" ); if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH) ) mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function skipped / left alone data" ); if( use_ret == -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the compression / decompression failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) ) mbedtls_snprintf( buf, buflen, "SSL - Handshake protocol not within min/max boundaries" ); if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) ) mbedtls_snprintf( buf, buflen, "SSL - Processing of the NewSessionTicket handshake message failed" ); if( use_ret == -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) ) mbedtls_snprintf( buf, buflen, "SSL - Session ticket has expired" ); if( use_ret == -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH) ) mbedtls_snprintf( buf, buflen, "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) ) mbedtls_snprintf( buf, buflen, "SSL - Unknown identity received (eg, PSK identity)" ); if( use_ret == -(MBEDTLS_ERR_SSL_INTERNAL_ERROR) ) mbedtls_snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" ); if( use_ret == -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING) ) mbedtls_snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" ); if( use_ret == -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) ) mbedtls_snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" ); if( use_ret == -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) ) mbedtls_snprintf( buf, buflen, "SSL - DTLS client must retry for hello verification" ); if( use_ret == -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "SSL - A buffer is too small to receive or write a message" ); if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) ) mbedtls_snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" ); if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) ) mbedtls_snprintf( buf, buflen, "SSL - Connection requires a read call" ); if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) ) mbedtls_snprintf( buf, buflen, "SSL - Connection requires a write call" ); if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) ) mbedtls_snprintf( buf, buflen, "SSL - The operation timed out" ); if( use_ret == -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT) ) mbedtls_snprintf( buf, buflen, "SSL - The client initiated a reconnect from the same port" ); if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) ) mbedtls_snprintf( buf, buflen, "SSL - Record header looks valid but is not expected" ); if( use_ret == -(MBEDTLS_ERR_SSL_NON_FATAL) ) mbedtls_snprintf( buf, buflen, "SSL - The alert message received indicates a non-fatal error" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) ) mbedtls_snprintf( buf, buflen, "SSL - Couldn't set the hash for verifying CertificateVerify" ); #endif /* MBEDTLS_SSL_TLS_C */ #if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) if( use_ret == -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_OID) ) mbedtls_snprintf( buf, buflen, "X509 - Requested OID is unknown" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_FORMAT) ) mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_VERSION) ) mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR version element is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SERIAL) ) mbedtls_snprintf( buf, buflen, "X509 - The serial tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_ALG) ) mbedtls_snprintf( buf, buflen, "X509 - The algorithm tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_NAME) ) mbedtls_snprintf( buf, buflen, "X509 - The name tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_DATE) ) mbedtls_snprintf( buf, buflen, "X509 - The date tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SIGNATURE) ) mbedtls_snprintf( buf, buflen, "X509 - The signature tag or value invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS) ) mbedtls_snprintf( buf, buflen, "X509 - The extension tag or value is invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_VERSION) ) mbedtls_snprintf( buf, buflen, "X509 - CRT/CRL/CSR has an unsupported version number" ); if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG) ) mbedtls_snprintf( buf, buflen, "X509 - Signature algorithm (oid) is unsupported" ); if( use_ret == -(MBEDTLS_ERR_X509_SIG_MISMATCH) ) mbedtls_snprintf( buf, buflen, "X509 - Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid)" ); if( use_ret == -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" ); if( use_ret == -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT) ) mbedtls_snprintf( buf, buflen, "X509 - Format not recognized as DER or PEM" ); if( use_ret == -(MBEDTLS_ERR_X509_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "X509 - Input invalid" ); if( use_ret == -(MBEDTLS_ERR_X509_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "X509 - Allocation of memory failed" ); if( use_ret == -(MBEDTLS_ERR_X509_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "X509 - Read/write of file failed" ); if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "X509 - Destination buffer is too small" ); if( use_ret == -(MBEDTLS_ERR_X509_FATAL_ERROR) ) mbedtls_snprintf( buf, buflen, "X509 - A fatal error occured, eg the chain is too long or the vrfy callback failed" ); #endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */ if( strlen( buf ) == 0 ) mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret ); } use_ret = ret & ~0xFF80; if( use_ret == 0 ) return; len = strlen( buf ); if( len > 0 ) { if( buflen - len < 5 ) return; mbedtls_snprintf( buf + len, buflen - len, " : " ); buf += len + 3; buflen -= len + 3; } #if defined(MBEDTLS_AES_C) if( use_ret == -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "AES - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" ); #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_ASN1_PARSE_C) if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) ) mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" ); if( use_ret == -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) ) mbedtls_snprintf( buf, buflen, "ASN1 - ASN1 tag was of an unexpected value" ); if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_LENGTH) ) mbedtls_snprintf( buf, buflen, "ASN1 - Error when trying to determine the length or invalid length" ); if( use_ret == -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH) ) mbedtls_snprintf( buf, buflen, "ASN1 - Actual length differs from expected length" ); if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_DATA) ) mbedtls_snprintf( buf, buflen, "ASN1 - Data is invalid. (not used)" ); if( use_ret == -(MBEDTLS_ERR_ASN1_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "ASN1 - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "ASN1 - Buffer too small when writing ASN.1 data structure" ); #endif /* MBEDTLS_ASN1_PARSE_C */ #if defined(MBEDTLS_BASE64_C) if( use_ret == -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "BASE64 - Output buffer too small" ); if( use_ret == -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER) ) mbedtls_snprintf( buf, buflen, "BASE64 - Invalid character in input" ); #endif /* MBEDTLS_BASE64_C */ #if defined(MBEDTLS_BIGNUM_C) if( use_ret == -(MBEDTLS_ERR_MPI_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "BIGNUM - An error occurred while reading from or writing to a file" ); if( use_ret == -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "BIGNUM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_MPI_INVALID_CHARACTER) ) mbedtls_snprintf( buf, buflen, "BIGNUM - There is an invalid character in the digit string" ); if( use_ret == -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The buffer is too small to write to" ); if( use_ret == -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are negative or result in illegal output" ); if( use_ret == -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input argument for division is zero, which is not allowed" ); if( use_ret == -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) ) mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are not acceptable" ); if( use_ret == -(MBEDTLS_ERR_MPI_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "BIGNUM - Memory allocation failed" ); #endif /* MBEDTLS_BIGNUM_C */ #if defined(MBEDTLS_BLOWFISH_C) if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" ); #endif /* MBEDTLS_BLOWFISH_C */ #if defined(MBEDTLS_CAMELLIA_C) if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH) ) mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" ); #endif /* MBEDTLS_CAMELLIA_C */ #if defined(MBEDTLS_CCM_C) if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) ) mbedtls_snprintf( buf, buflen, "CCM - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "CCM - Authenticated decryption failed" ); #endif /* MBEDTLS_CCM_C */ #if defined(MBEDTLS_CTR_DRBG_C) if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Too many random requested in single call" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Input too large (Entropy + additional)" ); if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "CTR_DRBG - Read/write error in file" ); #endif /* MBEDTLS_CTR_DRBG_C */ #if defined(MBEDTLS_DES_C) if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "DES - The data input has an invalid length" ); #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ENTROPY_C) if( use_ret == -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "ENTROPY - Critical entropy source failure" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No more sources can be added" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No sources have been added to poll" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE) ) mbedtls_snprintf( buf, buflen, "ENTROPY - No strong sources have been added to poll" ); if( use_ret == -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "ENTROPY - Read/write error in file" ); #endif /* MBEDTLS_ENTROPY_C */ #if defined(MBEDTLS_GCM_C) if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) ) mbedtls_snprintf( buf, buflen, "GCM - Authenticated decryption failed" ); if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) ) mbedtls_snprintf( buf, buflen, "GCM - Bad input parameters to function" ); #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_HMAC_DRBG_C) if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Too many random requested in single call" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Input too large (Entropy + additional)" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Read/write error in file" ); if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) ) mbedtls_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" ); #endif /* MBEDTLS_HMAC_DRBG_C */ #if defined(MBEDTLS_NET_C) if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Failed to open a socket" ); if( use_ret == -(MBEDTLS_ERR_NET_CONNECT_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - The connection to the given server / port failed" ); if( use_ret == -(MBEDTLS_ERR_NET_BIND_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Binding of the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_LISTEN_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Could not listen on the socket" ); if( use_ret == -(MBEDTLS_ERR_NET_ACCEPT_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Could not accept the incoming connection" ); if( use_ret == -(MBEDTLS_ERR_NET_RECV_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Reading information from the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_SEND_FAILED) ) mbedtls_snprintf( buf, buflen, "NET - Sending information through the socket failed" ); if( use_ret == -(MBEDTLS_ERR_NET_CONN_RESET) ) mbedtls_snprintf( buf, buflen, "NET - Connection was reset by peer" ); if( use_ret == -(MBEDTLS_ERR_NET_UNKNOWN_HOST) ) mbedtls_snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" ); if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "NET - Buffer is too small to hold the data" ); if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) ) mbedtls_snprintf( buf, buflen, "NET - The context is invalid, eg because it was free()ed" ); #endif /* MBEDTLS_NET_C */ #if defined(MBEDTLS_OID_C) if( use_ret == -(MBEDTLS_ERR_OID_NOT_FOUND) ) mbedtls_snprintf( buf, buflen, "OID - OID is not found" ); if( use_ret == -(MBEDTLS_ERR_OID_BUF_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "OID - output buffer is too small" ); #endif /* MBEDTLS_OID_C */ #if defined(MBEDTLS_PADLOCK_C) if( use_ret == -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED) ) mbedtls_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" ); #endif /* MBEDTLS_PADLOCK_C */ #if defined(MBEDTLS_THREADING_C) if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "THREADING - The selected feature is not available" ); if( use_ret == -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "THREADING - Bad input parameters to function" ); if( use_ret == -(MBEDTLS_ERR_THREADING_MUTEX_ERROR) ) mbedtls_snprintf( buf, buflen, "THREADING - Locking / unlocking / free failed with error code" ); #endif /* MBEDTLS_THREADING_C */ #if defined(MBEDTLS_XTEA_C) if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "XTEA - The data input has an invalid length" ); #endif /* MBEDTLS_XTEA_C */ if( strlen( buf ) != 0 ) return; mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret ); }
6,261
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.
Code: Page* ChromeClientImpl::CreateWindow(LocalFrame* frame, const FrameLoadRequest& r, const WebWindowFeatures& features, NavigationPolicy navigation_policy, SandboxFlags sandbox_flags) { if (!web_view_->Client()) return nullptr; if (!frame->GetPage() || frame->GetPage()->Paused()) return nullptr; DCHECK(frame->GetDocument()); Fullscreen::FullyExitFullscreen(*frame->GetDocument()); const AtomicString& frame_name = !EqualIgnoringASCIICase(r.FrameName(), "_blank") ? r.FrameName() : g_empty_atom; WebViewImpl* new_view = static_cast<WebViewImpl*>(web_view_->Client()->CreateView( WebLocalFrameImpl::FromFrame(frame), WrappedResourceRequest(r.GetResourceRequest()), features, frame_name, static_cast<WebNavigationPolicy>(navigation_policy), r.GetShouldSetOpener() == kNeverSetOpener, static_cast<WebSandboxFlags>(sandbox_flags))); if (!new_view) return nullptr; return new_view->GetPage(); } Commit Message: If a page shows a popup, end fullscreen. This was implemented in Blink r159834, but it is susceptible to a popup/fullscreen race. This CL reverts that implementation and re-implements it in WebContents. BUG=752003 TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f Reviewed-on: https://chromium-review.googlesource.com/606987 Commit-Queue: Avi Drissman <avi@chromium.org> Reviewed-by: Charlie Reis <creis@chromium.org> Reviewed-by: Philip Jägenstedt <foolip@chromium.org> Cr-Commit-Position: refs/heads/master@{#498171} CWE ID: CWE-20
Page* ChromeClientImpl::CreateWindow(LocalFrame* frame, const FrameLoadRequest& r, const WebWindowFeatures& features, NavigationPolicy navigation_policy, SandboxFlags sandbox_flags) { if (!web_view_->Client()) return nullptr; if (!frame->GetPage() || frame->GetPage()->Paused()) return nullptr; const AtomicString& frame_name = !EqualIgnoringASCIICase(r.FrameName(), "_blank") ? r.FrameName() : g_empty_atom; WebViewImpl* new_view = static_cast<WebViewImpl*>(web_view_->Client()->CreateView( WebLocalFrameImpl::FromFrame(frame), WrappedResourceRequest(r.GetResourceRequest()), features, frame_name, static_cast<WebNavigationPolicy>(navigation_policy), r.GetShouldSetOpener() == kNeverSetOpener, static_cast<WebSandboxFlags>(sandbox_flags))); if (!new_view) return nullptr; return new_view->GetPage(); }
16,043
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.
Code: pkinit_server_verify_padata(krb5_context context, krb5_data *req_pkt, krb5_kdc_req * request, krb5_enc_tkt_part * enc_tkt_reply, krb5_pa_data * data, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_verify_respond_fn respond, void *arg) { krb5_error_code retval = 0; krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL}; krb5_pa_pk_as_req *reqp = NULL; krb5_pa_pk_as_req_draft9 *reqp9 = NULL; krb5_auth_pack *auth_pack = NULL; krb5_auth_pack_draft9 *auth_pack9 = NULL; pkinit_kdc_context plgctx = NULL; pkinit_kdc_req_context reqctx = NULL; krb5_checksum cksum = {0, 0, 0, NULL}; krb5_data *der_req = NULL; int valid_eku = 0, valid_san = 0; krb5_data k5data; int is_signed = 1; krb5_pa_data **e_data = NULL; krb5_kdcpreauth_modreq modreq = NULL; pkiDebug("pkinit_verify_padata: entered!\n"); if (data == NULL || data->length <= 0 || data->contents == NULL) { (*respond)(arg, 0, NULL, NULL, NULL); return; } if (moddata == NULL) { (*respond)(arg, EINVAL, NULL, NULL, NULL); return; } plgctx = pkinit_find_realm_context(context, moddata, request->server); if (plgctx == NULL) { (*respond)(arg, 0, NULL, NULL, NULL); return; } #ifdef DEBUG_ASN1 print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req"); #endif /* create a per-request context */ retval = pkinit_init_kdc_req_context(context, &reqctx); if (retval) goto cleanup; reqctx->pa_type = data->pa_type; PADATA_TO_KRB5DATA(data, &k5data); switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: pkiDebug("processing KRB5_PADATA_PK_AS_REQ\n"); retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp); if (retval) { pkiDebug("decode_krb5_pa_pk_as_req failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin(reqp->signedAuthPack.data, reqp->signedAuthPack.length, "/tmp/kdc_signed_data"); #endif retval = cms_signeddata_verify(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT, plgctx->opts->require_crl_checking, (unsigned char *) reqp->signedAuthPack.data, reqp->signedAuthPack.length, (unsigned char **)&authp_data.data, &authp_data.length, (unsigned char **)&krb5_authz.data, &krb5_authz.length, &is_signed); break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: pkiDebug("processing KRB5_PADATA_PK_AS_REQ_OLD\n"); retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9); if (retval) { pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin(reqp9->signedAuthPack.data, reqp9->signedAuthPack.length, "/tmp/kdc_signed_data_draft9"); #endif retval = cms_signeddata_verify(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9, plgctx->opts->require_crl_checking, (unsigned char *) reqp9->signedAuthPack.data, reqp9->signedAuthPack.length, (unsigned char **)&authp_data.data, &authp_data.length, (unsigned char **)&krb5_authz.data, &krb5_authz.length, NULL); break; default: pkiDebug("unrecognized pa_type = %d\n", data->pa_type); retval = EINVAL; goto cleanup; } if (retval) { pkiDebug("pkcs7_signeddata_verify failed\n"); goto cleanup; } if (is_signed) { retval = verify_client_san(context, plgctx, reqctx, request->client, &valid_san); if (retval) goto cleanup; if (!valid_san) { pkiDebug("%s: did not find an acceptable SAN in user " "certificate\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto cleanup; } retval = verify_client_eku(context, plgctx, reqctx, &valid_eku); if (retval) goto cleanup; if (!valid_eku) { pkiDebug("%s: did not find an acceptable EKU in user " "certificate\n", __FUNCTION__); retval = KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE; goto cleanup; } } else { /* !is_signed */ if (!krb5_principal_compare(context, request->client, krb5_anonymous_principal())) { retval = KRB5KDC_ERR_PREAUTH_FAILED; krb5_set_error_message(context, retval, _("Pkinit request not signed, but client " "not anonymous.")); goto cleanup; } } #ifdef DEBUG_ASN1 print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack"); #endif OCTETDATA_TO_KRB5DATA(&authp_data, &k5data); switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack); if (retval) { pkiDebug("failed to decode krb5_auth_pack\n"); goto cleanup; } retval = krb5_check_clockskew(context, auth_pack->pkAuthenticator.ctime); if (retval) goto cleanup; /* check dh parameters */ if (auth_pack->clientPublicValue != NULL) { retval = server_check_dh(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &auth_pack->clientPublicValue->algorithm.parameters, plgctx->opts->dh_min_bits); if (retval) { pkiDebug("bad dh parameters\n"); goto cleanup; } } else if (!is_signed) { /*Anonymous pkinit requires DH*/ retval = KRB5KDC_ERR_PREAUTH_FAILED; krb5_set_error_message(context, retval, _("Anonymous pkinit without DH public " "value not supported.")); goto cleanup; } der_req = cb->request_body(context, rock); retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL, 0, der_req, &cksum); if (retval) { pkiDebug("unable to calculate AS REQ checksum\n"); goto cleanup; } if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length || k5_bcmp(cksum.contents, auth_pack->pkAuthenticator.paChecksum.contents, cksum.length) != 0) { pkiDebug("failed to match the checksum\n"); #ifdef DEBUG_CKSUM pkiDebug("calculating checksum on buf size (%d)\n", req_pkt->length); print_buffer(req_pkt->data, req_pkt->length); pkiDebug("received checksum type=%d size=%d ", auth_pack->pkAuthenticator.paChecksum.checksum_type, auth_pack->pkAuthenticator.paChecksum.length); print_buffer(auth_pack->pkAuthenticator.paChecksum.contents, auth_pack->pkAuthenticator.paChecksum.length); pkiDebug("expected checksum type=%d size=%d ", cksum.checksum_type, cksum.length); print_buffer(cksum.contents, cksum.length); #endif retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED; goto cleanup; } /* check if kdcPkId present and match KDC's subjectIdentifier */ if (reqp->kdcPkId.data != NULL) { int valid_kdcPkId = 0; retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, (unsigned char *)reqp->kdcPkId.data, reqp->kdcPkId.length, &valid_kdcPkId); if (retval) goto cleanup; if (!valid_kdcPkId) pkiDebug("kdcPkId in AS_REQ does not match KDC's cert" "RFC says to ignore and proceed\n"); } /* remember the decoded auth_pack for verify_padata routine */ reqctx->rcv_auth_pack = auth_pack; auth_pack = NULL; break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9); if (retval) { pkiDebug("failed to decode krb5_auth_pack_draft9\n"); goto cleanup; } if (auth_pack9->clientPublicValue != NULL) { retval = server_check_dh(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &auth_pack9->clientPublicValue->algorithm.parameters, plgctx->opts->dh_min_bits); if (retval) { pkiDebug("bad dh parameters\n"); goto cleanup; } } /* remember the decoded auth_pack for verify_padata routine */ reqctx->rcv_auth_pack9 = auth_pack9; auth_pack9 = NULL; break; } /* remember to set the PREAUTH flag in the reply */ enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH; modreq = (krb5_kdcpreauth_modreq)reqctx; reqctx = NULL; cleanup: if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) { pkiDebug("pkinit_verify_padata failed: creating e-data\n"); if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, plgctx->opts, retval, &e_data)) pkiDebug("pkinit_create_edata failed\n"); } switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: free_krb5_pa_pk_as_req(&reqp); free(cksum.contents); break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: free_krb5_pa_pk_as_req_draft9(&reqp9); } free(authp_data.data); free(krb5_authz.data); if (reqctx != NULL) pkinit_fini_kdc_req_context(context, reqctx); free_krb5_auth_pack(&auth_pack); free_krb5_auth_pack_draft9(context, &auth_pack9); (*respond)(arg, retval, modreq, e_data, NULL); } Commit Message: Prevent requires_preauth bypass [CVE-2015-2694] In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until the request is successfully verified. In the PKINIT kdcpreauth module, don't respond with code 0 on empty input or an unconfigured realm. Together these bugs could cause the KDC preauth framework to erroneously treat a request as pre-authenticated. CVE-2015-2694: In MIT krb5 1.12 and later, when the KDC is configured with PKINIT support, an unauthenticated remote attacker can bypass the requires_preauth flag on a client principal and obtain a ciphertext encrypted in the principal's long-term key. This ciphertext could be used to conduct an off-line dictionary attack against the user's password. CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C ticket: 8160 (new) target_version: 1.13.2 tags: pullup subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694] CWE ID: CWE-264
pkinit_server_verify_padata(krb5_context context, krb5_data *req_pkt, krb5_kdc_req * request, krb5_enc_tkt_part * enc_tkt_reply, krb5_pa_data * data, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_verify_respond_fn respond, void *arg) { krb5_error_code retval = 0; krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL}; krb5_pa_pk_as_req *reqp = NULL; krb5_pa_pk_as_req_draft9 *reqp9 = NULL; krb5_auth_pack *auth_pack = NULL; krb5_auth_pack_draft9 *auth_pack9 = NULL; pkinit_kdc_context plgctx = NULL; pkinit_kdc_req_context reqctx = NULL; krb5_checksum cksum = {0, 0, 0, NULL}; krb5_data *der_req = NULL; int valid_eku = 0, valid_san = 0; krb5_data k5data; int is_signed = 1; krb5_pa_data **e_data = NULL; krb5_kdcpreauth_modreq modreq = NULL; pkiDebug("pkinit_verify_padata: entered!\n"); if (data == NULL || data->length <= 0 || data->contents == NULL) { (*respond)(arg, EINVAL, NULL, NULL, NULL); return; } if (moddata == NULL) { (*respond)(arg, EINVAL, NULL, NULL, NULL); return; } plgctx = pkinit_find_realm_context(context, moddata, request->server); if (plgctx == NULL) { (*respond)(arg, EINVAL, NULL, NULL, NULL); return; } #ifdef DEBUG_ASN1 print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req"); #endif /* create a per-request context */ retval = pkinit_init_kdc_req_context(context, &reqctx); if (retval) goto cleanup; reqctx->pa_type = data->pa_type; PADATA_TO_KRB5DATA(data, &k5data); switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: pkiDebug("processing KRB5_PADATA_PK_AS_REQ\n"); retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp); if (retval) { pkiDebug("decode_krb5_pa_pk_as_req failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin(reqp->signedAuthPack.data, reqp->signedAuthPack.length, "/tmp/kdc_signed_data"); #endif retval = cms_signeddata_verify(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT, plgctx->opts->require_crl_checking, (unsigned char *) reqp->signedAuthPack.data, reqp->signedAuthPack.length, (unsigned char **)&authp_data.data, &authp_data.length, (unsigned char **)&krb5_authz.data, &krb5_authz.length, &is_signed); break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: pkiDebug("processing KRB5_PADATA_PK_AS_REQ_OLD\n"); retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9); if (retval) { pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin(reqp9->signedAuthPack.data, reqp9->signedAuthPack.length, "/tmp/kdc_signed_data_draft9"); #endif retval = cms_signeddata_verify(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9, plgctx->opts->require_crl_checking, (unsigned char *) reqp9->signedAuthPack.data, reqp9->signedAuthPack.length, (unsigned char **)&authp_data.data, &authp_data.length, (unsigned char **)&krb5_authz.data, &krb5_authz.length, NULL); break; default: pkiDebug("unrecognized pa_type = %d\n", data->pa_type); retval = EINVAL; goto cleanup; } if (retval) { pkiDebug("pkcs7_signeddata_verify failed\n"); goto cleanup; } if (is_signed) { retval = verify_client_san(context, plgctx, reqctx, request->client, &valid_san); if (retval) goto cleanup; if (!valid_san) { pkiDebug("%s: did not find an acceptable SAN in user " "certificate\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto cleanup; } retval = verify_client_eku(context, plgctx, reqctx, &valid_eku); if (retval) goto cleanup; if (!valid_eku) { pkiDebug("%s: did not find an acceptable EKU in user " "certificate\n", __FUNCTION__); retval = KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE; goto cleanup; } } else { /* !is_signed */ if (!krb5_principal_compare(context, request->client, krb5_anonymous_principal())) { retval = KRB5KDC_ERR_PREAUTH_FAILED; krb5_set_error_message(context, retval, _("Pkinit request not signed, but client " "not anonymous.")); goto cleanup; } } #ifdef DEBUG_ASN1 print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack"); #endif OCTETDATA_TO_KRB5DATA(&authp_data, &k5data); switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack); if (retval) { pkiDebug("failed to decode krb5_auth_pack\n"); goto cleanup; } retval = krb5_check_clockskew(context, auth_pack->pkAuthenticator.ctime); if (retval) goto cleanup; /* check dh parameters */ if (auth_pack->clientPublicValue != NULL) { retval = server_check_dh(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &auth_pack->clientPublicValue->algorithm.parameters, plgctx->opts->dh_min_bits); if (retval) { pkiDebug("bad dh parameters\n"); goto cleanup; } } else if (!is_signed) { /*Anonymous pkinit requires DH*/ retval = KRB5KDC_ERR_PREAUTH_FAILED; krb5_set_error_message(context, retval, _("Anonymous pkinit without DH public " "value not supported.")); goto cleanup; } der_req = cb->request_body(context, rock); retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL, 0, der_req, &cksum); if (retval) { pkiDebug("unable to calculate AS REQ checksum\n"); goto cleanup; } if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length || k5_bcmp(cksum.contents, auth_pack->pkAuthenticator.paChecksum.contents, cksum.length) != 0) { pkiDebug("failed to match the checksum\n"); #ifdef DEBUG_CKSUM pkiDebug("calculating checksum on buf size (%d)\n", req_pkt->length); print_buffer(req_pkt->data, req_pkt->length); pkiDebug("received checksum type=%d size=%d ", auth_pack->pkAuthenticator.paChecksum.checksum_type, auth_pack->pkAuthenticator.paChecksum.length); print_buffer(auth_pack->pkAuthenticator.paChecksum.contents, auth_pack->pkAuthenticator.paChecksum.length); pkiDebug("expected checksum type=%d size=%d ", cksum.checksum_type, cksum.length); print_buffer(cksum.contents, cksum.length); #endif retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED; goto cleanup; } /* check if kdcPkId present and match KDC's subjectIdentifier */ if (reqp->kdcPkId.data != NULL) { int valid_kdcPkId = 0; retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, (unsigned char *)reqp->kdcPkId.data, reqp->kdcPkId.length, &valid_kdcPkId); if (retval) goto cleanup; if (!valid_kdcPkId) pkiDebug("kdcPkId in AS_REQ does not match KDC's cert" "RFC says to ignore and proceed\n"); } /* remember the decoded auth_pack for verify_padata routine */ reqctx->rcv_auth_pack = auth_pack; auth_pack = NULL; break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9); if (retval) { pkiDebug("failed to decode krb5_auth_pack_draft9\n"); goto cleanup; } if (auth_pack9->clientPublicValue != NULL) { retval = server_check_dh(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &auth_pack9->clientPublicValue->algorithm.parameters, plgctx->opts->dh_min_bits); if (retval) { pkiDebug("bad dh parameters\n"); goto cleanup; } } /* remember the decoded auth_pack for verify_padata routine */ reqctx->rcv_auth_pack9 = auth_pack9; auth_pack9 = NULL; break; } /* remember to set the PREAUTH flag in the reply */ enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH; modreq = (krb5_kdcpreauth_modreq)reqctx; reqctx = NULL; cleanup: if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) { pkiDebug("pkinit_verify_padata failed: creating e-data\n"); if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, plgctx->opts, retval, &e_data)) pkiDebug("pkinit_create_edata failed\n"); } switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: free_krb5_pa_pk_as_req(&reqp); free(cksum.contents); break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: free_krb5_pa_pk_as_req_draft9(&reqp9); } free(authp_data.data); free(krb5_authz.data); if (reqctx != NULL) pkinit_fini_kdc_req_context(context, reqctx); free_krb5_auth_pack(&auth_pack); free_krb5_auth_pack_draft9(context, &auth_pack9); (*respond)(arg, retval, modreq, e_data, NULL); }
5,747
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.
Code: png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; png_structp png_ptr=*ptr_ptr; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_read_init() and should be" " recompiled."); break; #endif } } while (png_libpng_ver[i++]); png_debug(1, "in png_read_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); png_ptr = *ptr_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zstream.zalloc = png_zalloc; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_ptr->zstream.zalloc = png_zalloc; png_ptr->zstream.zfree = png_zfree; png_ptr->zstream.opaque = (voidpf)png_ptr; switch (inflateInit(&png_ptr->zstream)) { case Z_OK: /* Do nothing */ break; case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break; case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break; default: png_error(png_ptr, "Unknown zlib error"); } png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; png_structp png_ptr=*ptr_ptr; if (png_ptr == NULL) return; do { if (user_png_ver == NULL || user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_read_init() and should be" " recompiled."); break; #endif } } while (png_libpng_ver[i++]); png_debug(1, "in png_read_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); png_ptr = *ptr_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zstream.zalloc = png_zalloc; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_ptr->zstream.zalloc = png_zalloc; png_ptr->zstream.zfree = png_zfree; png_ptr->zstream.opaque = (voidpf)png_ptr; switch (inflateInit(&png_ptr->zstream)) { case Z_OK: /* Do nothing */ break; case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break; case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break; default: png_error(png_ptr, "Unknown zlib error"); } png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL); }
17,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.
Code: AccessibilityOrientation AXNodeObject::orientation() const { const AtomicString& ariaOrientation = getAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation); AccessibilityOrientation orientation = AccessibilityOrientationUndefined; if (equalIgnoringCase(ariaOrientation, "horizontal")) orientation = AccessibilityOrientationHorizontal; else if (equalIgnoringCase(ariaOrientation, "vertical")) orientation = AccessibilityOrientationVertical; switch (roleValue()) { case ComboBoxRole: case ListBoxRole: case MenuRole: case ScrollBarRole: case TreeRole: if (orientation == AccessibilityOrientationUndefined) orientation = AccessibilityOrientationVertical; return orientation; case MenuBarRole: case SliderRole: case SplitterRole: case TabListRole: case ToolbarRole: if (orientation == AccessibilityOrientationUndefined) orientation = AccessibilityOrientationHorizontal; return orientation; case RadioGroupRole: case TreeGridRole: case TableRole: return orientation; default: return AXObject::orientation(); } } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
AccessibilityOrientation AXNodeObject::orientation() const { const AtomicString& ariaOrientation = getAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation); AccessibilityOrientation orientation = AccessibilityOrientationUndefined; if (equalIgnoringASCIICase(ariaOrientation, "horizontal")) orientation = AccessibilityOrientationHorizontal; else if (equalIgnoringASCIICase(ariaOrientation, "vertical")) orientation = AccessibilityOrientationVertical; switch (roleValue()) { case ComboBoxRole: case ListBoxRole: case MenuRole: case ScrollBarRole: case TreeRole: if (orientation == AccessibilityOrientationUndefined) orientation = AccessibilityOrientationVertical; return orientation; case MenuBarRole: case SliderRole: case SplitterRole: case TabListRole: case ToolbarRole: if (orientation == AccessibilityOrientationUndefined) orientation = AccessibilityOrientationHorizontal; return orientation; case RadioGroupRole: case TreeGridRole: case TableRole: return orientation; default: return AXObject::orientation(); } }
17,546
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.
Code: static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], colorspace[MagickPathExtent], tuple[MagickPathExtent]; MagickBooleanType status; MagickOffsetType scene; PixelInfo pixel; register const Quantum *p; register ssize_t x; ssize_t y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { ComplianceType compliance; const char *value; (void) CopyMagickString(colorspace,CommandOptionToMnemonic( MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent); LocaleLower(colorspace); image->depth=GetImageQuantumDepth(image,MagickTrue); if (image->alpha_trait != UndefinedPixelTrait) (void) ConcatenateMagickString(colorspace,"a",MagickPathExtent); compliance=NoCompliance; value=GetImageOption(image_info,"txt:compliance"); if (value != (char *) NULL) compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions, MagickFalse,value); if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0) { size_t depth; depth=compliance == SVGCompliance ? image->depth : MAGICKCORE_QUANTUM_DEPTH; (void) FormatLocaleString(buffer,MagickPathExtent, "# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double) image->columns,(double) image->rows,(double) ((MagickOffsetType) GetQuantumRange(depth)),colorspace); (void) WriteBlobString(image,buffer); } GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,p,&pixel); if (pixel.colorspace == LabColorspace) { pixel.green-=(QuantumRange+1)/2.0; pixel.blue-=(QuantumRange+1)/2.0; } if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0) { /* Sparse-color format. */ if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha) { GetColorTuple(&pixel,MagickFalse,tuple); (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g,%.20g,",(double) x,(double) y); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image," "); } p+=GetPixelChannels(image); continue; } (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ", (double) x,(double) y); (void) WriteBlobString(image,buffer); (void) CopyMagickString(tuple,"(",MagickPathExtent); if (pixel.colorspace == GRAYColorspace) ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance, tuple); else { ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple); (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance, tuple); (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple); } if (pixel.colorspace == CMYKColorspace) { (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance, tuple); } if (pixel.alpha_trait != UndefinedPixelTrait) { (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance, tuple); } (void) ConcatenateMagickString(tuple,")",MagickPathExtent); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image," "); GetColorTuple(&pixel,MagickTrue,tuple); (void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," "); (void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image,"\n"); p+=GetPixelChannels(image); } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/298 CWE ID: CWE-476
static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], colorspace[MagickPathExtent], tuple[MagickPathExtent]; MagickBooleanType status; MagickOffsetType scene; PixelInfo pixel; register const Quantum *p; register ssize_t x; ssize_t y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { ComplianceType compliance; const char *value; (void) CopyMagickString(colorspace,CommandOptionToMnemonic( MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent); LocaleLower(colorspace); image->depth=GetImageQuantumDepth(image,MagickTrue); if (image->alpha_trait != UndefinedPixelTrait) (void) ConcatenateMagickString(colorspace,"a",MagickPathExtent); compliance=NoCompliance; value=GetImageOption(image_info,"txt:compliance"); if (value != (char *) NULL) compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions, MagickFalse,value); if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0) { size_t depth; depth=compliance == SVGCompliance ? image->depth : MAGICKCORE_QUANTUM_DEPTH; (void) FormatLocaleString(buffer,MagickPathExtent, "# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double) image->columns,(double) image->rows,(double) ((MagickOffsetType) GetQuantumRange(depth)),colorspace); (void) WriteBlobString(image,buffer); } GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,p,&pixel); if (pixel.colorspace == LabColorspace) { pixel.green-=(QuantumRange+1)/2.0; pixel.blue-=(QuantumRange+1)/2.0; } if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0) { /* Sparse-color format. */ if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha) { GetColorTuple(&pixel,MagickFalse,tuple); (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g,%.20g,",(double) x,(double) y); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image," "); } p+=GetPixelChannels(image); continue; } (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ", (double) x,(double) y); (void) WriteBlobString(image,buffer); (void) CopyMagickString(tuple,"(",MagickPathExtent); if (pixel.colorspace == GRAYColorspace) ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple); else { ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple); (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance, tuple); (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple); } if (pixel.colorspace == CMYKColorspace) { (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance, tuple); } if (pixel.alpha_trait != UndefinedPixelTrait) { (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance, tuple); } (void) ConcatenateMagickString(tuple,")",MagickPathExtent); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image," "); GetColorTuple(&pixel,MagickTrue,tuple); (void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," "); (void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image,"\n"); p+=GetPixelChannels(image); } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
17,500
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.
Code: void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) { if (!is_hidden_) return; TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown"); is_hidden_ = false; if (new_content_rendering_timeout_ && new_content_rendering_timeout_->IsRunning()) { new_content_rendering_timeout_->Stop(); ClearDisplayedGraphics(); } SendScreenRects(); RestartHangMonitorTimeoutIfNecessary(); bool needs_repainting = true; needs_repainting_on_restore_ = false; Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info)); process_->WidgetRestored(); bool is_visible = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderWidgetHost>(this), Details<bool>(&is_visible)); WasResized(); } Commit Message: Force a flush of drawing to the widget when a dialog is shown. BUG=823353 TEST=as in bug Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260 Reviewed-on: https://chromium-review.googlesource.com/971661 Reviewed-by: Ken Buchanan <kenrb@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#544518} CWE ID:
void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) { if (!is_hidden_) return; TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown"); is_hidden_ = false; ForceFirstFrameAfterNavigationTimeout(); SendScreenRects(); RestartHangMonitorTimeoutIfNecessary(); bool needs_repainting = true; needs_repainting_on_restore_ = false; Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info)); process_->WidgetRestored(); bool is_visible = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderWidgetHost>(this), Details<bool>(&is_visible)); WasResized(); }
19,779
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.
Code: int dtls1_get_record(SSL *s) { int ssl_major,ssl_minor; int i,n; SSL3_RECORD *rr; unsigned char *p = NULL; unsigned short version; DTLS1_BITMAP *bitmap; unsigned int is_next_epoch; rr= &(s->s3->rrec); /* The epoch may have changed. If so, process all the * pending records. This is a non-blocking operation. */ dtls1_process_buffered_records(s); /* if we're renegotiating, then there may be buffered records */ if (dtls1_get_processed_record(s)) return 1; /* get something from the wire */ again: /* check if we have the header */ if ( (s->rstate != SSL_ST_READ_BODY) || (s->packet_length < DTLS1_RT_HEADER_LENGTH)) { n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); /* read timeout is handled by dtls1_read_bytes */ if (n <= 0) return(n); /* error or non-blocking */ /* this packet contained a partial record, dump it */ if (s->packet_length != DTLS1_RT_HEADER_LENGTH) { s->packet_length = 0; goto again; } s->rstate=SSL_ST_READ_BODY; p=s->packet; if (s->msg_callback) s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg); /* Pull apart the header into the DTLS1_RECORD */ rr->type= *(p++); ssl_major= *(p++); ssl_minor= *(p++); version=(ssl_major<<8)|ssl_minor; /* sequence number is 64 bits, with top 2 bytes = epoch */ n2s(p,rr->epoch); memcpy(&(s->s3->read_sequence[2]), p, 6); p+=6; n2s(p,rr->length); /* Lets check version */ if (!s->first_packet) { if (version != s->version) { /* unexpected version, silently discard */ rr->length = 0; s->packet_length = 0; goto again; } } if ((version & 0xff00) != (s->version & 0xff00)) { /* wrong version, silently discard record */ rr->length = 0; s->packet_length = 0; goto again; } if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { /* record too long, silently discard it */ rr->length = 0; s->packet_length = 0; goto again; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH) { /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */ i=rr->length; n=ssl3_read_n(s,i,i,1); /* this packet contained a partial record, dump it */ if ( n != i) { rr->length = 0; s->packet_length = 0; goto again; } /* now n == rr->length, * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */ } s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ /* match epochs. NULL means the packet is dropped on the floor */ bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); if ( bitmap == NULL) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP /* Only do replay check if no SCTP bio */ if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) { #endif /* Check whether this is a repeat, or aged record. * Don't check if we're listening and this message is * a ClientHello. They can look as if they're replayed, * since they arrive from different connections and * would be dropped unnecessarily. */ if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE && *p == SSL3_MT_CLIENT_HELLO) && !dtls1_record_replay_check(s, bitmap)) { rr->length = 0; s->packet_length=0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP } #endif /* just read a 0 length packet */ if (rr->length == 0) goto again; /* If this record is from the next epoch (either HM or ALERT), * and a handshake is currently in progress, buffer it since it * cannot be processed at this time. However, do not buffer * anything while listening. */ if (is_next_epoch) { if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) { dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num); } rr->length = 0; s->packet_length = 0; goto again; } if (!dtls1_process_record(s)) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } return(1); } Commit Message: Follow on from CVE-2014-3571. This fixes the code that was the original source of the crash due to p being NULL. Steve's fix prevents this situation from occuring - however this is by no means obvious by looking at the code for dtls1_get_record. This fix just makes things look a bit more sane. Reviewed-by: Dr Stephen Henson <steve@openssl.org> CWE ID:
int dtls1_get_record(SSL *s) { int ssl_major,ssl_minor; int i,n; SSL3_RECORD *rr; unsigned char *p = NULL; unsigned short version; DTLS1_BITMAP *bitmap; unsigned int is_next_epoch; rr= &(s->s3->rrec); /* The epoch may have changed. If so, process all the * pending records. This is a non-blocking operation. */ dtls1_process_buffered_records(s); /* if we're renegotiating, then there may be buffered records */ if (dtls1_get_processed_record(s)) return 1; /* get something from the wire */ again: /* check if we have the header */ if ( (s->rstate != SSL_ST_READ_BODY) || (s->packet_length < DTLS1_RT_HEADER_LENGTH)) { n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); /* read timeout is handled by dtls1_read_bytes */ if (n <= 0) return(n); /* error or non-blocking */ /* this packet contained a partial record, dump it */ if (s->packet_length != DTLS1_RT_HEADER_LENGTH) { s->packet_length = 0; goto again; } s->rstate=SSL_ST_READ_BODY; p=s->packet; if (s->msg_callback) s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg); /* Pull apart the header into the DTLS1_RECORD */ rr->type= *(p++); ssl_major= *(p++); ssl_minor= *(p++); version=(ssl_major<<8)|ssl_minor; /* sequence number is 64 bits, with top 2 bytes = epoch */ n2s(p,rr->epoch); memcpy(&(s->s3->read_sequence[2]), p, 6); p+=6; n2s(p,rr->length); /* Lets check version */ if (!s->first_packet) { if (version != s->version) { /* unexpected version, silently discard */ rr->length = 0; s->packet_length = 0; goto again; } } if ((version & 0xff00) != (s->version & 0xff00)) { /* wrong version, silently discard record */ rr->length = 0; s->packet_length = 0; goto again; } if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { /* record too long, silently discard it */ rr->length = 0; s->packet_length = 0; goto again; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH) { /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */ i=rr->length; n=ssl3_read_n(s,i,i,1); /* this packet contained a partial record, dump it */ if ( n != i) { rr->length = 0; s->packet_length = 0; goto again; } /* now n == rr->length, * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */ } s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ /* match epochs. NULL means the packet is dropped on the floor */ bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); if ( bitmap == NULL) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP /* Only do replay check if no SCTP bio */ if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) { #endif /* Check whether this is a repeat, or aged record. * Don't check if we're listening and this message is * a ClientHello. They can look as if they're replayed, * since they arrive from different connections and * would be dropped unnecessarily. */ if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE && s->packet_length > DTLS1_RT_HEADER_LENGTH && s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) && !dtls1_record_replay_check(s, bitmap)) { rr->length = 0; s->packet_length=0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP } #endif /* just read a 0 length packet */ if (rr->length == 0) goto again; /* If this record is from the next epoch (either HM or ALERT), * and a handshake is currently in progress, buffer it since it * cannot be processed at this time. However, do not buffer * anything while listening. */ if (is_next_epoch) { if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) { dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num); } rr->length = 0; s->packet_length = 0; goto again; } if (!dtls1_process_record(s)) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } return(1); }
1,041
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.
Code: static int __net_init sit_init_net(struct net *net) { struct sit_net *sitn = net_generic(net, sit_net_id); struct ip_tunnel *t; int err; sitn->tunnels[0] = sitn->tunnels_wc; sitn->tunnels[1] = sitn->tunnels_l; sitn->tunnels[2] = sitn->tunnels_r; sitn->tunnels[3] = sitn->tunnels_r_l; if (!net_has_fallback_tunnels(net)) return 0; sitn->fb_tunnel_dev = alloc_netdev(sizeof(struct ip_tunnel), "sit0", NET_NAME_UNKNOWN, ipip6_tunnel_setup); if (!sitn->fb_tunnel_dev) { err = -ENOMEM; goto err_alloc_dev; } dev_net_set(sitn->fb_tunnel_dev, net); sitn->fb_tunnel_dev->rtnl_link_ops = &sit_link_ops; /* FB netdevice is special: we have one, and only one per netns. * Allowing to move it to another netns is clearly unsafe. */ sitn->fb_tunnel_dev->features |= NETIF_F_NETNS_LOCAL; err = register_netdev(sitn->fb_tunnel_dev); if (err) goto err_reg_dev; ipip6_tunnel_clone_6rd(sitn->fb_tunnel_dev, sitn); ipip6_fb_tunnel_init(sitn->fb_tunnel_dev); t = netdev_priv(sitn->fb_tunnel_dev); strcpy(t->parms.name, sitn->fb_tunnel_dev->name); return 0; err_reg_dev: ipip6_dev_free(sitn->fb_tunnel_dev); err_alloc_dev: return err; } Commit Message: net: sit: fix memory leak in sit_init_net() If register_netdev() is failed to register sitn->fb_tunnel_dev, it will go to err_reg_dev and forget to free netdev(sitn->fb_tunnel_dev). BUG: memory leak unreferenced object 0xffff888378daad00 (size 512): comm "syz-executor.1", pid 4006, jiffies 4295121142 (age 16.115s) hex dump (first 32 bytes): 00 e6 ed c0 83 88 ff ff 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ backtrace: [<00000000d6dcb63e>] kvmalloc include/linux/mm.h:577 [inline] [<00000000d6dcb63e>] kvzalloc include/linux/mm.h:585 [inline] [<00000000d6dcb63e>] netif_alloc_netdev_queues net/core/dev.c:8380 [inline] [<00000000d6dcb63e>] alloc_netdev_mqs+0x600/0xcc0 net/core/dev.c:8970 [<00000000867e172f>] sit_init_net+0x295/0xa40 net/ipv6/sit.c:1848 [<00000000871019fa>] ops_init+0xad/0x3e0 net/core/net_namespace.c:129 [<00000000319507f6>] setup_net+0x2ba/0x690 net/core/net_namespace.c:314 [<0000000087db4f96>] copy_net_ns+0x1dc/0x330 net/core/net_namespace.c:437 [<0000000057efc651>] create_new_namespaces+0x382/0x730 kernel/nsproxy.c:107 [<00000000676f83de>] copy_namespaces+0x2ed/0x3d0 kernel/nsproxy.c:165 [<0000000030b74bac>] copy_process.part.27+0x231e/0x6db0 kernel/fork.c:1919 [<00000000fff78746>] copy_process kernel/fork.c:1713 [inline] [<00000000fff78746>] _do_fork+0x1bc/0xe90 kernel/fork.c:2224 [<000000001c2e0d1c>] do_syscall_64+0xc8/0x580 arch/x86/entry/common.c:290 [<00000000ec48bd44>] entry_SYSCALL_64_after_hwframe+0x49/0xbe [<0000000039acff8a>] 0xffffffffffffffff Signed-off-by: Mao Wenan <maowenan@huawei.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-772
static int __net_init sit_init_net(struct net *net) { struct sit_net *sitn = net_generic(net, sit_net_id); struct ip_tunnel *t; int err; sitn->tunnels[0] = sitn->tunnels_wc; sitn->tunnels[1] = sitn->tunnels_l; sitn->tunnels[2] = sitn->tunnels_r; sitn->tunnels[3] = sitn->tunnels_r_l; if (!net_has_fallback_tunnels(net)) return 0; sitn->fb_tunnel_dev = alloc_netdev(sizeof(struct ip_tunnel), "sit0", NET_NAME_UNKNOWN, ipip6_tunnel_setup); if (!sitn->fb_tunnel_dev) { err = -ENOMEM; goto err_alloc_dev; } dev_net_set(sitn->fb_tunnel_dev, net); sitn->fb_tunnel_dev->rtnl_link_ops = &sit_link_ops; /* FB netdevice is special: we have one, and only one per netns. * Allowing to move it to another netns is clearly unsafe. */ sitn->fb_tunnel_dev->features |= NETIF_F_NETNS_LOCAL; err = register_netdev(sitn->fb_tunnel_dev); if (err) goto err_reg_dev; ipip6_tunnel_clone_6rd(sitn->fb_tunnel_dev, sitn); ipip6_fb_tunnel_init(sitn->fb_tunnel_dev); t = netdev_priv(sitn->fb_tunnel_dev); strcpy(t->parms.name, sitn->fb_tunnel_dev->name); return 0; err_reg_dev: ipip6_dev_free(sitn->fb_tunnel_dev); free_netdev(sitn->fb_tunnel_dev); err_alloc_dev: return err; }
25,957
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.
Code: static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1602 CWE ID: CWE-190
static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if (((offset > 0) && (profile->offset > (SSIZE_MAX-offset))) || ((offset < 0) && (profile->offset < (-SSIZE_MAX-offset)))) { errno=EOVERFLOW; return(-1); } if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); }
2,853
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.
Code: PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; size_t localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; size_t localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL); }
8,867
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.
Code: krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data, krb5_kvno mkvno) { struct berval **ret = NULL; int currkvno; int num_versions = 1; int i, j, last; krb5_error_code err = 0; krb5_key_data *key_data; if (n_key_data <= 0) return NULL; /* Make a shallow copy of the key data so we can alter it. */ key_data = k5calloc(n_key_data, sizeof(*key_data), &err); if (key_data_in == NULL) goto cleanup; memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data)); /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt * field. For compatibility, always encode a salt field. */ for (i = 0; i < n_key_data; i++) { if (key_data[i].key_data_ver == 1) { key_data[i].key_data_ver = 2; key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } } /* Find the number of key versions */ for (i = 0; i < n_key_data - 1; i++) if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno) num_versions++; ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *)); if (ret == NULL) { err = ENOMEM; goto cleanup; } for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) { krb5_data *code; if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) { ret[j] = k5alloc(sizeof(struct berval), &err); if (ret[j] == NULL) goto cleanup; err = asn1_encode_sequence_of_keys(key_data + last, (krb5_int16)i - last + 1, mkvno, &code); if (err) goto cleanup; /*CHECK_NULL(ret[j]); */ ret[j]->bv_len = code->length; ret[j]->bv_val = code->data; free(code); j++; last = i + 1; currkvno = key_data[i].key_data_kvno; } } ret[num_versions] = NULL; cleanup: free(key_data); if (err != 0) { if (ret != NULL) { for (i = 0; i <= num_versions; i++) if (ret[i] != NULL) free (ret[i]); free (ret); ret = NULL; } } return ret; } Commit Message: Fix LDAP key data segmentation [CVE-2014-4345] For principal entries having keys with multiple kvnos (due to use of -keepold), the LDAP KDB module makes an attempt to store all the keys having the same kvno into a single krbPrincipalKey attribute value. There is a fencepost error in the loop, causing currkvno to be set to the just-processed value instead of the next kvno. As a result, the second and all following groups of multiple keys by kvno are each stored in two krbPrincipalKey attribute values. Fix the loop to use the correct kvno value. CVE-2014-4345: In MIT krb5, when kadmind is configured to use LDAP for the KDC database, an authenticated remote attacker can cause it to perform an out-of-bounds write (buffer overrun) by performing multiple cpw -keepold operations. An off-by-one error while copying key information to the new database entry results in keys sharing a common kvno being written to different array buckets, in an array whose size is determined by the number of kvnos present. After sufficient iterations, the extra writes extend past the end of the (NULL-terminated) array. The NULL terminator is always written after the end of the loop, so no out-of-bounds data is read, it is only written. Historically, it has been possible to convert an out-of-bounds write into remote code execution in some cases, though the necessary exploits must be tailored to the individual application and are usually quite complicated. Depending on the allocated length of the array, an out-of-bounds write may also cause a segmentation fault and/or application crash. CVSSv2 Vector: AV:N/AC:M/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C [ghudson@mit.edu: clarified commit message] [kaduk@mit.edu: CVE summary, CVSSv2 vector] (cherry picked from commit 81c332e29f10887c6b9deb065f81ba259f4c7e03) ticket: 7980 version_fixed: 1.12.2 status: resolved CWE ID: CWE-189
krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data, krb5_kvno mkvno) { struct berval **ret = NULL; int currkvno; int num_versions = 1; int i, j, last; krb5_error_code err = 0; krb5_key_data *key_data; if (n_key_data <= 0) return NULL; /* Make a shallow copy of the key data so we can alter it. */ key_data = k5calloc(n_key_data, sizeof(*key_data), &err); if (key_data_in == NULL) goto cleanup; memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data)); /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt * field. For compatibility, always encode a salt field. */ for (i = 0; i < n_key_data; i++) { if (key_data[i].key_data_ver == 1) { key_data[i].key_data_ver = 2; key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } } /* Find the number of key versions */ for (i = 0; i < n_key_data - 1; i++) if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno) num_versions++; ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *)); if (ret == NULL) { err = ENOMEM; goto cleanup; } for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) { krb5_data *code; if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) { ret[j] = k5alloc(sizeof(struct berval), &err); if (ret[j] == NULL) goto cleanup; err = asn1_encode_sequence_of_keys(key_data + last, (krb5_int16)i - last + 1, mkvno, &code); if (err) goto cleanup; /*CHECK_NULL(ret[j]); */ ret[j]->bv_len = code->length; ret[j]->bv_val = code->data; free(code); j++; last = i + 1; if (i < n_key_data - 1) currkvno = key_data[i + 1].key_data_kvno; } } ret[num_versions] = NULL; cleanup: free(key_data); if (err != 0) { if (ret != NULL) { for (i = 0; i <= num_versions; i++) if (ret[i] != NULL) free (ret[i]); free (ret); ret = NULL; } } return ret; }
12,830
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.
Code: void LauncherView::SetAlignment(ShelfAlignment alignment) { if (alignment_ == alignment) return; alignment_ = alignment; UpdateFirstButtonPadding(); LayoutToIdealBounds(); tooltip_->SetArrowLocation(alignment_); } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void LauncherView::SetAlignment(ShelfAlignment alignment) { if (alignment_ == alignment) return; alignment_ = alignment; UpdateFirstButtonPadding(); LayoutToIdealBounds(); tooltip_->SetArrowLocation(alignment_); if (overflow_bubble_.get()) overflow_bubble_->Hide(); }
7,505
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.
Code: long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) { assert(pReader); long long total, available; long status = pReader->Length(&total, &available); if (status < 0) // error return status; pos = 0; long long end = (available >= 1024) ? 1024 : available; for (;;) { unsigned char b = 0; while (pos < end) { status = pReader->Read(pos, 1, &b); if (status < 0) // error return status; if (b == 0x1A) break; ++pos; } if (b != 0x1A) { if (pos >= 1024) return E_FILE_FORMAT_INVALID; // don't bother looking anymore if ((total >= 0) && ((total - available) < 5)) return E_FILE_FORMAT_INVALID; return available + 5; // 5 = 4-byte ID + 1st byte of size } if ((total >= 0) && ((total - pos) < 5)) return E_FILE_FORMAT_INVALID; if ((available - pos) < 5) return pos + 5; // try again later long len; const long long result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; if (result == 0x0A45DFA3) { // EBML Header ID pos += len; // consume ID break; } ++pos; // throw away just the 0x1A byte, and try again } long len; long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return result; if (result > 0) // need more data return result; assert(len > 0); assert(len <= 8); if ((total >= 0) && ((total - pos) < len)) return E_FILE_FORMAT_INVALID; if ((available - pos) < len) return pos + len; // try again later result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; pos += len; // consume size field if ((total >= 0) && ((total - pos) < result)) return E_FILE_FORMAT_INVALID; if ((available - pos) < result) return pos + result; end = pos + result; Init(); while (pos < end) { long long id, size; status = ParseElementHeader(pReader, pos, end, id, size); if (status < 0) // error return status; if (size == 0) // weird return E_FILE_FORMAT_INVALID; if (id == 0x0286) { // version m_version = UnserializeUInt(pReader, pos, size); if (m_version <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F7) { // read version m_readVersion = UnserializeUInt(pReader, pos, size); if (m_readVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F2) { // max id length m_maxIdLength = UnserializeUInt(pReader, pos, size); if (m_maxIdLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F3) { // max size length m_maxSizeLength = UnserializeUInt(pReader, pos, size); if (m_maxSizeLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0282) { // doctype if (m_docType) return E_FILE_FORMAT_INVALID; status = UnserializeString(pReader, pos, size, m_docType); if (status) // error return status; } else if (id == 0x0287) { // doctype version m_docTypeVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0285) { // doctype read version m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeReadVersion <= 0) return E_FILE_FORMAT_INVALID; } pos += size; } assert(pos == end); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) { if (!pReader) return E_FILE_FORMAT_INVALID; long long total, available; long status = pReader->Length(&total, &available); if (status < 0) // error return status; pos = 0; long long end = (available >= 1024) ? 1024 : available; for (;;) { unsigned char b = 0; while (pos < end) { status = pReader->Read(pos, 1, &b); if (status < 0) // error return status; if (b == 0x1A) break; ++pos; } if (b != 0x1A) { if (pos >= 1024) return E_FILE_FORMAT_INVALID; // don't bother looking anymore if ((total >= 0) && ((total - available) < 5)) return E_FILE_FORMAT_INVALID; return available + 5; // 5 = 4-byte ID + 1st byte of size } if ((total >= 0) && ((total - pos) < 5)) return E_FILE_FORMAT_INVALID; if ((available - pos) < 5) return pos + 5; // try again later long len; const long long result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; if (result == 0x0A45DFA3) { // EBML Header ID pos += len; // consume ID break; } ++pos; // throw away just the 0x1A byte, and try again } long len; long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return result; if (result > 0) // need more data return result; if (len < 1 || len > 8) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((total - pos) < len)) return E_FILE_FORMAT_INVALID; if ((available - pos) < len) return pos + len; // try again later result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; pos += len; // consume size field if ((total >= 0) && ((total - pos) < result)) return E_FILE_FORMAT_INVALID; if ((available - pos) < result) return pos + result; end = pos + result; Init(); while (pos < end) { long long id, size; status = ParseElementHeader(pReader, pos, end, id, size); if (status < 0) // error return status; if (size == 0) // weird return E_FILE_FORMAT_INVALID; if (id == 0x0286) { // version m_version = UnserializeUInt(pReader, pos, size); if (m_version <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F7) { // read version m_readVersion = UnserializeUInt(pReader, pos, size); if (m_readVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F2) { // max id length m_maxIdLength = UnserializeUInt(pReader, pos, size); if (m_maxIdLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F3) { // max size length m_maxSizeLength = UnserializeUInt(pReader, pos, size); if (m_maxSizeLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0282) { // doctype if (m_docType) return E_FILE_FORMAT_INVALID; status = UnserializeString(pReader, pos, size, m_docType); if (status) // error return status; } else if (id == 0x0287) { // doctype version m_docTypeVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0285) { // doctype read version m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeReadVersion <= 0) return E_FILE_FORMAT_INVALID; } pos += size; } if (pos != end) return E_FILE_FORMAT_INVALID; return 0; }
14,390
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.
Code: int _mkp_stage_30(struct plugin *p, struct client_session *cs, struct session_request *sr) { mk_ptr_t referer; (void) p; (void) cs; PLUGIN_TRACE("[FD %i] Mandril validating URL", cs->socket); if (mk_security_check_url(sr->uri) < 0) { PLUGIN_TRACE("[FD %i] Close connection, blocked URL", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } PLUGIN_TRACE("[FD %d] Mandril validating hotlinking", cs->socket); referer = mk_api->header_get(&sr->headers_toc, "Referer", strlen("Referer")); if (mk_security_check_hotlink(sr->uri_processed, sr->host, referer) < 0) { PLUGIN_TRACE("[FD %i] Close connection, deny hotlinking.", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } return MK_PLUGIN_RET_NOT_ME; } Commit Message: Mandril: check decoded URI (fix #92) Signed-off-by: Eduardo Silva <eduardo@monkey.io> CWE ID: CWE-264
int _mkp_stage_30(struct plugin *p, struct client_session *cs, struct session_request *sr) { mk_ptr_t referer; (void) p; (void) cs; PLUGIN_TRACE("[FD %i] Mandril validating URL", cs->socket); if (mk_security_check_url(sr->uri_processed) < 0) { PLUGIN_TRACE("[FD %i] Close connection, blocked URL", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } PLUGIN_TRACE("[FD %d] Mandril validating hotlinking", cs->socket); referer = mk_api->header_get(&sr->headers_toc, "Referer", strlen("Referer")); if (mk_security_check_hotlink(sr->uri_processed, sr->host, referer) < 0) { PLUGIN_TRACE("[FD %i] Close connection, deny hotlinking.", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } return MK_PLUGIN_RET_NOT_ME; }
29,234
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.
Code: void get_checksum2(char *buf, int32 len, char *sum) { md_context m; switch (xfersum_type) { case CSUM_MD5: { uchar seedbuf[4]; md5_begin(&m); if (proper_seed_order) { if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } md5_update(&m, (uchar *)buf, len); } else { md5_update(&m, (uchar *)buf, len); if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } } md5_result(&m, (uchar *)sum); break; } case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: { int32 i; static char *buf1; static int32 len1; mdfour_begin(&m); if (len > len1) { if (buf1) free(buf1); buf1 = new_array(char, len+4); len1 = len; if (!buf1) out_of_memory("get_checksum2"); } memcpy(buf1, buf, len); if (checksum_seed) { SIVAL(buf1,len,checksum_seed); len += 4; } for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) mdfour_update(&m, (uchar *)(buf1+i), CSUM_CHUNK); /* * Prior to version 27 an incorrect MD4 checksum was computed * by failing to call mdfour_tail() for block sizes that * are multiples of 64. This is fixed by calling mdfour_update() * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ if (len - i > 0 || xfersum_type != CSUM_MD4_BUSTED) mdfour_update(&m, (uchar *)(buf1+i), len-i); mdfour_result(&m, (uchar *)sum); } } } Commit Message: CWE ID: CWE-354
void get_checksum2(char *buf, int32 len, char *sum) { md_context m; switch (xfersum_type) { case CSUM_MD5: { uchar seedbuf[4]; md5_begin(&m); if (proper_seed_order) { if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } md5_update(&m, (uchar *)buf, len); } else { md5_update(&m, (uchar *)buf, len); if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } } md5_result(&m, (uchar *)sum); break; } case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: case CSUM_MD4_ARCHAIC: { int32 i; static char *buf1; static int32 len1; mdfour_begin(&m); if (len > len1) { if (buf1) free(buf1); buf1 = new_array(char, len+4); len1 = len; if (!buf1) out_of_memory("get_checksum2"); } memcpy(buf1, buf, len); if (checksum_seed) { SIVAL(buf1,len,checksum_seed); len += 4; } for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) mdfour_update(&m, (uchar *)(buf1+i), CSUM_CHUNK); /* * Prior to version 27 an incorrect MD4 checksum was computed * by failing to call mdfour_tail() for block sizes that * are multiples of 64. This is fixed by calling mdfour_update() * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ if (len - i > 0 || xfersum_type > CSUM_MD4_BUSTED) mdfour_update(&m, (uchar *)(buf1+i), len-i); mdfour_result(&m, (uchar *)sum); } } }
22,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.
Code: void HandleCompleteLogin(const base::ListValue* args) { #if defined(OS_CHROMEOS) oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui())); oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher( oauth2_delegate_.get(), profile_->GetRequestContext())); oauth2_token_fetcher_->StartExchangeFromCookies(); #elif !defined(OS_ANDROID) const base::DictionaryValue* dict = NULL; string16 email; string16 password; if (!args->GetDictionary(0, &dict) || !dict || !dict->GetString("email", &email) || !dict->GetString("password", &password)) { NOTREACHED(); return; } new OneClickSigninSyncStarter( profile_, NULL, "0" /* session_index 0 for the default user */, UTF16ToASCII(email), UTF16ToASCII(password), OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS, true /* force_same_tab_navigation */, OneClickSigninSyncStarter::NO_CONFIRMATION); web_ui()->CallJavascriptFunction("inline.login.closeDialog"); #endif } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void HandleCompleteLogin(const base::ListValue* args) { #if defined(OS_CHROMEOS) oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui())); oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher( oauth2_delegate_.get(), profile_->GetRequestContext())); oauth2_token_fetcher_->StartExchangeFromCookies(); #elif !defined(OS_ANDROID) const base::DictionaryValue* dict = NULL; string16 email; string16 password; if (!args->GetDictionary(0, &dict) || !dict || !dict->GetString("email", &email) || !dict->GetString("password", &password)) { NOTREACHED(); return; } new OneClickSigninSyncStarter( profile_, NULL, "0" /* session_index 0 for the default user */, UTF16ToASCII(email), UTF16ToASCII(password), OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS, true /* force_same_tab_navigation */, OneClickSigninSyncStarter::NO_CONFIRMATION, SyncPromoUI::SOURCE_UNKNOWN); web_ui()->CallJavascriptFunction("inline.login.closeDialog"); #endif }
14,886
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.
Code: static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) { int rowsize; int pad; unsigned int z; int nz; int c; int x; int y; int v; jas_matrix_t *data[3]; int i; for (i = 0; i < numcmpts; ++i) { data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image)); assert(data[i]); } rowsize = RAS_ROWSIZE(hdr); pad = rowsize - (hdr->width * hdr->depth + 7) / 8; hdr->length = hdr->height * rowsize; for (y = 0; y < hdr->height; y++) { for (i = 0; i < numcmpts; ++i) { if (jas_image_readcmpt(image, cmpts[i], 0, y, jas_image_width(image), 1, data[i])) { return -1; } } z = 0; nz = 0; for (x = 0; x < hdr->width; x++) { z <<= hdr->depth; if (RAS_ISRGB(hdr)) { v = RAS_RED((jas_matrix_getv(data[0], x))) | RAS_GREEN((jas_matrix_getv(data[1], x))) | RAS_BLUE((jas_matrix_getv(data[2], x))); } else { v = (jas_matrix_getv(data[0], x)); } z |= v & RAS_ONES(hdr->depth); nz += hdr->depth; while (nz >= 8) { c = (z >> (nz - 8)) & 0xff; if (jas_stream_putc(out, c) == EOF) { return -1; } nz -= 8; z &= RAS_ONES(nz); } } if (nz > 0) { c = (z >> (8 - nz)) & RAS_ONES(nz); if (jas_stream_putc(out, c) == EOF) { return -1; } } if (pad % 2) { if (jas_stream_putc(out, 0) == EOF) { return -1; } } } for (i = 0; i < numcmpts; ++i) { jas_matrix_destroy(data[i]); } return 0; } Commit Message: Fixed a few bugs in the RAS encoder and decoder where errors were tested with assertions instead of being gracefully handled. CWE ID:
static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) { int rowsize; int pad; unsigned int z; int nz; int c; int x; int y; int v; jas_matrix_t *data[3]; int i; assert(numcmpts <= 3); for (i = 0; i < 3; ++i) { data[i] = 0; } for (i = 0; i < numcmpts; ++i) { if (!(data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image)))) { goto error; } } rowsize = RAS_ROWSIZE(hdr); pad = rowsize - (hdr->width * hdr->depth + 7) / 8; hdr->length = hdr->height * rowsize; for (y = 0; y < hdr->height; y++) { for (i = 0; i < numcmpts; ++i) { if (jas_image_readcmpt(image, cmpts[i], 0, y, jas_image_width(image), 1, data[i])) { goto error; } } z = 0; nz = 0; for (x = 0; x < hdr->width; x++) { z <<= hdr->depth; if (RAS_ISRGB(hdr)) { v = RAS_RED((jas_matrix_getv(data[0], x))) | RAS_GREEN((jas_matrix_getv(data[1], x))) | RAS_BLUE((jas_matrix_getv(data[2], x))); } else { v = (jas_matrix_getv(data[0], x)); } z |= v & RAS_ONES(hdr->depth); nz += hdr->depth; while (nz >= 8) { c = (z >> (nz - 8)) & 0xff; if (jas_stream_putc(out, c) == EOF) { goto error; } nz -= 8; z &= RAS_ONES(nz); } } if (nz > 0) { c = (z >> (8 - nz)) & RAS_ONES(nz); if (jas_stream_putc(out, c) == EOF) { goto error; } } if (pad % 2) { if (jas_stream_putc(out, 0) == EOF) { goto error; } } } for (i = 0; i < numcmpts; ++i) { jas_matrix_destroy(data[i]); data[i] = 0; } return 0; error: for (i = 0; i < numcmpts; ++i) { if (data[i]) { jas_matrix_destroy(data[i]); } } return -1; }
25,578
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.
Code: int GetAvailableDraftPageCount() { int page_data_map_size = page_data_map_.size(); if (page_data_map_.find(printing::COMPLETE_PREVIEW_DOCUMENT_INDEX) != page_data_map_.end()) { page_data_map_size--; } return page_data_map_size; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
int GetAvailableDraftPageCount() { int page_data_map_size = page_data_map_.size(); if (ContainsKey(page_data_map_, printing::COMPLETE_PREVIEW_DOCUMENT_INDEX)) page_data_map_size--; return page_data_map_size; }
10,789
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.
Code: static void copyStereo16( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i]; *dst++ = src[1][i]; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyStereo16( short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i]; *dst++ = src[1][i]; } }
8,631
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.
Code: DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host, DevToolsAgentHostClient* client) : binding_(this), agent_host_(agent_host), client_(client), process_host_id_(ChildProcessHost::kInvalidUniqueID), host_(nullptr), dispatcher_(new protocol::UberDispatcher(this)), weak_factory_(this) { dispatcher_->setFallThroughForNotFound(true); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. TBR=alexclarke@chromium.org Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Nasko Oskov <nasko@chromium.org> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host, DevToolsAgentHostClient* client, bool restricted) : binding_(this), agent_host_(agent_host), client_(client), restricted_(restricted), process_host_id_(ChildProcessHost::kInvalidUniqueID), host_(nullptr), dispatcher_(new protocol::UberDispatcher(this)), weak_factory_(this) { dispatcher_->setFallThroughForNotFound(true); }
14,826
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.
Code: store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize, size_t pos, PNG_CONST char *msg) { if (pp != NULL && pp == ps->pread) { /* Reading a file */ pos = safecat(buffer, bufsize, pos, "read: "); if (ps->current != NULL) { pos = safecat(buffer, bufsize, pos, ps->current->name); pos = safecat(buffer, bufsize, pos, sep); } } else if (pp != NULL && pp == ps->pwrite) { /* Writing a file */ pos = safecat(buffer, bufsize, pos, "write: "); pos = safecat(buffer, bufsize, pos, ps->wname); pos = safecat(buffer, bufsize, pos, sep); } else { /* Neither reading nor writing (or a memory error in struct delete) */ pos = safecat(buffer, bufsize, pos, "pngvalid: "); } if (ps->test[0] != 0) { pos = safecat(buffer, bufsize, pos, ps->test); pos = safecat(buffer, bufsize, pos, sep); } pos = safecat(buffer, bufsize, pos, msg); return pos; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize, size_t pos, const char *msg) { if (pp != NULL && pp == ps->pread) { /* Reading a file */ pos = safecat(buffer, bufsize, pos, "read: "); if (ps->current != NULL) { pos = safecat(buffer, bufsize, pos, ps->current->name); pos = safecat(buffer, bufsize, pos, sep); } } else if (pp != NULL && pp == ps->pwrite) { /* Writing a file */ pos = safecat(buffer, bufsize, pos, "write: "); pos = safecat(buffer, bufsize, pos, ps->wname); pos = safecat(buffer, bufsize, pos, sep); } else { /* Neither reading nor writing (or a memory error in struct delete) */ pos = safecat(buffer, bufsize, pos, "pngvalid: "); } if (ps->test[0] != 0) { pos = safecat(buffer, bufsize, pos, ps->test); pos = safecat(buffer, bufsize, pos, sep); } pos = safecat(buffer, bufsize, pos, msg); return pos; }
27,259
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.
Code: ProxyChannelDelegate::ProxyChannelDelegate() : shutdown_event_(true, false) { } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
ProxyChannelDelegate::ProxyChannelDelegate()
6,622
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.
Code: PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion() Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion()
12,515
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.
Code: void RenderFrameHostImpl::RegisterMojoInterfaces() { #if !defined(OS_ANDROID) registry_->AddInterface(base::Bind(&InstalledAppProviderImplDefault::Create)); #endif // !defined(OS_ANDROID) PermissionControllerImpl* permission_controller = PermissionControllerImpl::FromBrowserContext( GetProcess()->GetBrowserContext()); if (delegate_) { auto* geolocation_context = delegate_->GetGeolocationContext(); if (geolocation_context) { geolocation_service_.reset(new GeolocationServiceImpl( geolocation_context, permission_controller, this)); registry_->AddInterface( base::Bind(&GeolocationServiceImpl::Bind, base::Unretained(geolocation_service_.get()))); } } registry_->AddInterface<device::mojom::WakeLock>(base::Bind( &RenderFrameHostImpl::BindWakeLockRequest, base::Unretained(this))); #if defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebNfc)) { registry_->AddInterface<device::mojom::NFC>(base::Bind( &RenderFrameHostImpl::BindNFCRequest, base::Unretained(this))); } #endif if (!permission_service_context_) permission_service_context_.reset(new PermissionServiceContext(this)); registry_->AddInterface( base::Bind(&PermissionServiceContext::CreateService, base::Unretained(permission_service_context_.get()))); registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindPresentationServiceRequest, base::Unretained(this))); registry_->AddInterface( base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this))); registry_->AddInterface(base::Bind( base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService), base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebUsbService, base::Unretained(this))); registry_->AddInterface<media::mojom::InterfaceFactory>( base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebSocket, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateDedicatedWorkerHostFactory, base::Unretained(this))); registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create, process_->GetID(), routing_id_)); registry_->AddInterface(base::BindRepeating(&device::GamepadMonitor::Create)); registry_->AddInterface<device::mojom::VRService>(base::Bind( &WebvrServiceProvider::BindWebvrService, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioInputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioOutputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::Bind(&CreateFrameResourceCoordinator, base::Unretained(this))); if (BrowserMainLoop::GetInstance()) { MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); registry_->AddInterface( base::Bind(&MediaDevicesDispatcherHost::Create, GetProcess()->GetID(), GetRoutingID(), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); registry_->AddInterface( base::BindRepeating( &RenderFrameHostImpl::CreateMediaStreamDispatcherHost, base::Unretained(this), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } #if BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::Bind(&RemoterFactoryImpl::Bind, GetProcess()->GetID(), GetRoutingID())); #endif // BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::BindRepeating( &KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this))); registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create)); #if !defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebAuth)) { registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest, base::Unretained(this))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableWebAuthTestingAPI)) { auto* environment_singleton = ScopedVirtualAuthenticatorEnvironment::GetInstance(); registry_->AddInterface(base::BindRepeating( &ScopedVirtualAuthenticatorEnvironment::AddBinding, base::Unretained(environment_singleton))); } } #endif // !defined(OS_ANDROID) sensor_provider_proxy_.reset( new SensorProviderProxyImpl(permission_controller, this)); registry_->AddInterface( base::Bind(&SensorProviderProxyImpl::Bind, base::Unretained(sensor_provider_proxy_.get()))); media::VideoDecodePerfHistory::SaveCallback save_stats_cb; if (GetSiteInstance()->GetBrowserContext()->GetVideoDecodePerfHistory()) { save_stats_cb = GetSiteInstance() ->GetBrowserContext() ->GetVideoDecodePerfHistory() ->GetSaveCallback(); } registry_->AddInterface(base::BindRepeating( &media::MediaMetricsProvider::Create, frame_tree_node_->IsMainFrame(), base::BindRepeating( &RenderFrameHostDelegate::GetUkmSourceIdForLastCommittedSource, base::Unretained(delegate_)), std::move(save_stats_cb))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( cc::switches::kEnableGpuBenchmarking)) { registry_->AddInterface( base::Bind(&InputInjectorImpl::Create, weak_ptr_factory_.GetWeakPtr())); } registry_->AddInterface(base::BindRepeating( &QuotaDispatcherHost::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface( base::BindRepeating(SpeechRecognitionDispatcherHost::Create, GetProcess()->GetID(), routing_id_), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); file_system_manager_.reset(new FileSystemManagerImpl( GetProcess()->GetID(), routing_id_, GetProcess()->GetStoragePartition()->GetFileSystemContext(), ChromeBlobStorageContext::GetFor(GetProcess()->GetBrowserContext()))); registry_->AddInterface( base::BindRepeating(&FileSystemManagerImpl::BindRequest, base::Unretained(file_system_manager_.get())), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); if (Portal::IsEnabled()) { registry_->AddInterface(base::BindRepeating(IgnoreResult(&Portal::Create), base::Unretained(this))); } registry_->AddInterface(base::BindRepeating( &BackgroundFetchServiceImpl::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface(base::BindRepeating(&ContactsManagerImpl::Create)); registry_->AddInterface( base::BindRepeating(&FileChooserImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&AudioContextManagerImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&WakeLockServiceImpl::Create, base::Unretained(this))); } 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 <emircan@chromium.org> Reviewed-by: Ken Buchanan <kenrb@chromium.org> Reviewed-by: Olga Sharonova <olka@chromium.org> Commit-Queue: Guido Urdaneta <guidou@chromium.org> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void RenderFrameHostImpl::RegisterMojoInterfaces() { #if !defined(OS_ANDROID) registry_->AddInterface(base::Bind(&InstalledAppProviderImplDefault::Create)); #endif // !defined(OS_ANDROID) PermissionControllerImpl* permission_controller = PermissionControllerImpl::FromBrowserContext( GetProcess()->GetBrowserContext()); if (delegate_) { auto* geolocation_context = delegate_->GetGeolocationContext(); if (geolocation_context) { geolocation_service_.reset(new GeolocationServiceImpl( geolocation_context, permission_controller, this)); registry_->AddInterface( base::Bind(&GeolocationServiceImpl::Bind, base::Unretained(geolocation_service_.get()))); } } registry_->AddInterface<device::mojom::WakeLock>(base::Bind( &RenderFrameHostImpl::BindWakeLockRequest, base::Unretained(this))); #if defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebNfc)) { registry_->AddInterface<device::mojom::NFC>(base::Bind( &RenderFrameHostImpl::BindNFCRequest, base::Unretained(this))); } #endif if (!permission_service_context_) permission_service_context_.reset(new PermissionServiceContext(this)); registry_->AddInterface( base::Bind(&PermissionServiceContext::CreateService, base::Unretained(permission_service_context_.get()))); registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindPresentationServiceRequest, base::Unretained(this))); registry_->AddInterface( base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this))); registry_->AddInterface(base::Bind( base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService), base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebUsbService, base::Unretained(this))); registry_->AddInterface<media::mojom::InterfaceFactory>( base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebSocket, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateDedicatedWorkerHostFactory, base::Unretained(this))); registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create, process_->GetID(), routing_id_)); registry_->AddInterface(base::BindRepeating(&device::GamepadMonitor::Create)); registry_->AddInterface<device::mojom::VRService>(base::Bind( &WebvrServiceProvider::BindWebvrService, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioInputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioOutputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::Bind(&CreateFrameResourceCoordinator, base::Unretained(this))); if (BrowserMainLoop::GetInstance()) { MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); registry_->AddInterface( base::Bind(&MediaDevicesDispatcherHost::Create, GetProcess()->GetID(), GetRoutingID(), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); registry_->AddInterface( base::BindRepeating(&MediaStreamDispatcherHost::Create, GetProcess()->GetID(), GetRoutingID(), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } #if BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::Bind(&RemoterFactoryImpl::Bind, GetProcess()->GetID(), GetRoutingID())); #endif // BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::BindRepeating( &KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this))); registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create)); #if !defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebAuth)) { registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest, base::Unretained(this))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableWebAuthTestingAPI)) { auto* environment_singleton = ScopedVirtualAuthenticatorEnvironment::GetInstance(); registry_->AddInterface(base::BindRepeating( &ScopedVirtualAuthenticatorEnvironment::AddBinding, base::Unretained(environment_singleton))); } } #endif // !defined(OS_ANDROID) sensor_provider_proxy_.reset( new SensorProviderProxyImpl(permission_controller, this)); registry_->AddInterface( base::Bind(&SensorProviderProxyImpl::Bind, base::Unretained(sensor_provider_proxy_.get()))); media::VideoDecodePerfHistory::SaveCallback save_stats_cb; if (GetSiteInstance()->GetBrowserContext()->GetVideoDecodePerfHistory()) { save_stats_cb = GetSiteInstance() ->GetBrowserContext() ->GetVideoDecodePerfHistory() ->GetSaveCallback(); } registry_->AddInterface(base::BindRepeating( &media::MediaMetricsProvider::Create, frame_tree_node_->IsMainFrame(), base::BindRepeating( &RenderFrameHostDelegate::GetUkmSourceIdForLastCommittedSource, base::Unretained(delegate_)), std::move(save_stats_cb))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( cc::switches::kEnableGpuBenchmarking)) { registry_->AddInterface( base::Bind(&InputInjectorImpl::Create, weak_ptr_factory_.GetWeakPtr())); } registry_->AddInterface(base::BindRepeating( &QuotaDispatcherHost::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface( base::BindRepeating(SpeechRecognitionDispatcherHost::Create, GetProcess()->GetID(), routing_id_), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); file_system_manager_.reset(new FileSystemManagerImpl( GetProcess()->GetID(), routing_id_, GetProcess()->GetStoragePartition()->GetFileSystemContext(), ChromeBlobStorageContext::GetFor(GetProcess()->GetBrowserContext()))); registry_->AddInterface( base::BindRepeating(&FileSystemManagerImpl::BindRequest, base::Unretained(file_system_manager_.get())), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); if (Portal::IsEnabled()) { registry_->AddInterface(base::BindRepeating(IgnoreResult(&Portal::Create), base::Unretained(this))); } registry_->AddInterface(base::BindRepeating( &BackgroundFetchServiceImpl::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface(base::BindRepeating(&ContactsManagerImpl::Create)); registry_->AddInterface( base::BindRepeating(&FileChooserImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&AudioContextManagerImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&WakeLockServiceImpl::Create, base::Unretained(this))); }
11,316
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.
Code: bool ResourceTracker::UnrefResource(PP_Resource res) { DLOG_IF(ERROR, !CheckIdType(res, PP_ID_TYPE_RESOURCE)) << res << " is not a PP_Resource."; ResourceMap::iterator i = live_resources_.find(res); if (i != live_resources_.end()) { if (!--i->second.second) { Resource* to_release = i->second.first; PP_Instance instance = to_release->instance()->pp_instance(); to_release->LastPluginRefWasDeleted(false); instance_map_[instance]->resources.erase(res); live_resources_.erase(i); } return true; } else { return false; } } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ResourceTracker::UnrefResource(PP_Resource res) { DLOG_IF(ERROR, !CheckIdType(res, PP_ID_TYPE_RESOURCE)) << res << " is not a PP_Resource."; ResourceMap::iterator i = live_resources_.find(res); if (i != live_resources_.end()) { if (!--i->second.second) { Resource* to_release = i->second.first; PP_Instance instance = to_release->instance()->pp_instance(); to_release->LastPluginRefWasDeleted(); instance_map_[instance]->ref_resources.erase(res); live_resources_.erase(i); } return true; } else { return false; } }
19,946
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.
Code: static Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: { if (header.bits_per_pixel != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case StaticColor: case PseudoColor: { if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) || (header.ncolors == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case TrueColor: case DirectColor: { if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) && (header.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: { if (header.pixmap_depth != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case XYPixmap: case ZPixmap: { if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.bitmap_pad) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_unit) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.byte_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_bit_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (header.ncolors > 65535) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); length=(size_t) (header.header_size-sz_XWDheader); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; colors=(XColor *) AcquireQuantumMemory((size_t) header.ncolors, sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask,exception); SetPixelRed(image,ScaleShortToQuantum( colors[(ssize_t) index].red),q); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask,exception); SetPixelGreen(image,ScaleShortToQuantum( colors[(ssize_t) index].green),q); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask,exception); SetPixelBlue(image,ScaleShortToQuantum( colors[(ssize_t) index].blue),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(image,ScaleShortToQuantum((unsigned short) color),q); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(image,ScaleShortToQuantum((unsigned short) color), q); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(image,ScaleShortToQuantum((unsigned short) color),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleShortToQuantum( colors[i].red); image->colormap[i].green=(MagickRealType) ScaleShortToQuantum( colors[i].green); image->colormap[i].blue=(MagickRealType) ScaleShortToQuantum( colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=(Quantum) ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y),exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1553 CWE ID: CWE-125
static Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((MagickSizeType) header.xoffset >= GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: { if (header.bits_per_pixel != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case StaticColor: case PseudoColor: { if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) || (header.colormap_entries == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case TrueColor: case DirectColor: { if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) && (header.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: { if (header.pixmap_depth != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case XYPixmap: case ZPixmap: { if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.bitmap_pad) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_unit) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.byte_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_bit_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); length=(size_t) (header.header_size-sz_XWDheader); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; length=(size_t) header.ncolors; if (length > ((~0UL)/sizeof(*colors))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask,exception); SetPixelRed(image,ScaleShortToQuantum( colors[(ssize_t) index].red),q); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask,exception); SetPixelGreen(image,ScaleShortToQuantum( colors[(ssize_t) index].green),q); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask,exception); SetPixelBlue(image,ScaleShortToQuantum( colors[(ssize_t) index].blue),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(image,ScaleShortToQuantum((unsigned short) color),q); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(image,ScaleShortToQuantum((unsigned short) color), q); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(image,ScaleShortToQuantum((unsigned short) color),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleShortToQuantum( colors[i].red); image->colormap[i].green=(MagickRealType) ScaleShortToQuantum( colors[i].green); image->colormap[i].blue=(MagickRealType) ScaleShortToQuantum( colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=(Quantum) ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y),exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
8,623
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.
Code: smb_flush_file(struct smb_request *sr, struct smb_ofile *ofile) { sr->user_cr = smb_ofile_getcred(ofile); if ((ofile->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0) (void) smb_fsop_commit(sr, sr->user_cr, ofile->f_node); } Commit Message: 7483 SMB flush on pipe triggers NULL pointer dereference in module smbsrv Reviewed by: Gordon Ross <gwr@nexenta.com> Reviewed by: Matt Barden <matt.barden@nexenta.com> Reviewed by: Evan Layton <evan.layton@nexenta.com> Reviewed by: Dan McDonald <danmcd@omniti.com> Approved by: Gordon Ross <gwr@nexenta.com> CWE ID: CWE-476
smb_flush_file(struct smb_request *sr, struct smb_ofile *ofile)
19,455
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.
Code: bool WebGLRenderingContextBase::ValidateHTMLImageElement( const SecurityOrigin* security_origin, const char* function_name, HTMLImageElement* image, ExceptionState& exception_state) { if (!image || !image->CachedImage()) { SynthesizeGLError(GL_INVALID_VALUE, function_name, "no image"); return false; } const KURL& url = image->CachedImage()->GetResponse().Url(); if (url.IsNull() || url.IsEmpty() || !url.IsValid()) { SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid image"); return false; } if (WouldTaintOrigin(image, security_origin)) { exception_state.ThrowSecurityError("The cross-origin image at " + url.ElidedString() + " may not be loaded."); return false; } return true; } Commit Message: Simplify WebGL error message The WebGL exception message text contains the full URL of a blocked cross-origin resource. It should instead contain only a generic notice. Bug: 799847 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: I3a7f00462a4643c41882f2ee7e7767e6d631557e Reviewed-on: https://chromium-review.googlesource.com/854986 Reviewed-by: Brandon Jones <bajones@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Eric Lawrence <elawrence@chromium.org> Cr-Commit-Position: refs/heads/master@{#528458} CWE ID: CWE-20
bool WebGLRenderingContextBase::ValidateHTMLImageElement( const SecurityOrigin* security_origin, const char* function_name, HTMLImageElement* image, ExceptionState& exception_state) { if (!image || !image->CachedImage()) { SynthesizeGLError(GL_INVALID_VALUE, function_name, "no image"); return false; } const KURL& url = image->CachedImage()->GetResponse().Url(); if (url.IsNull() || url.IsEmpty() || !url.IsValid()) { SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid image"); return false; } if (WouldTaintOrigin(image, security_origin)) { exception_state.ThrowSecurityError( "The image element contains cross-origin data, and may not be loaded."); return false; } return true; }
5,860
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.
Code: void smp_process_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = (uint8_t*)p_data; uint8_t reason = SMP_INVALID_PARAMETERS; SMP_TRACE_DEBUG("%s", __func__); p_cb->status = *(uint8_t*)p_data; if (smp_command_has_invalid_parameters(p_cb)) { smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); return; } if (p != NULL) { STREAM_TO_UINT8(p_cb->peer_keypress_notification, p); } else { p_cb->peer_keypress_notification = BTM_SP_KEY_OUT_OF_RANGE; } p_cb->cb_evt = SMP_PEER_KEYPR_NOT_EVT; } Commit Message: DO NOT MERGE Fix OOB read before buffer length check Bug: 111936834 Test: manual Change-Id: Ib98528fb62db0d724ebd9112d071e367f78e369d (cherry picked from commit 4548f34c90803c6544f6bed03399f2eabeab2a8e) CWE ID: CWE-125
void smp_process_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = (uint8_t*)p_data; uint8_t reason = SMP_INVALID_PARAMETERS; SMP_TRACE_DEBUG("%s", __func__); if (smp_command_has_invalid_parameters(p_cb)) { if (p_cb->rcvd_cmd_len < 2) { // 1 (opcode) + 1 (Notif Type) bytes android_errorWriteLog(0x534e4554, "111936834"); } smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); return; } p_cb->status = *(uint8_t*)p_data; if (p != NULL) { STREAM_TO_UINT8(p_cb->peer_keypress_notification, p); } else { p_cb->peer_keypress_notification = BTM_SP_KEY_OUT_OF_RANGE; } p_cb->cb_evt = SMP_PEER_KEYPR_NOT_EVT; }
14,719
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.
Code: static int em_syscall(struct x86_emulate_ctxt *ctxt) { struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; /* syscall is not available in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_ud(ctxt); ops->get_msr(ctxt, MSR_EFER, &efer); setup_syscalls_segments(ctxt, &cs, &ss); ops->get_msr(ctxt, MSR_STAR, &msr_data); msr_data >>= 32; cs_sel = (u16)(msr_data & 0xfffc); ss_sel = (u16)(msr_data + 8); if (efer & EFER_LMA) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ctxt->regs[VCPU_REGS_RCX] = ctxt->_eip; if (efer & EFER_LMA) { #ifdef CONFIG_X86_64 ctxt->regs[VCPU_REGS_R11] = ctxt->eflags & ~EFLG_RF; ops->get_msr(ctxt, ctxt->mode == X86EMUL_MODE_PROT64 ? MSR_LSTAR : MSR_CSTAR, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data); ctxt->eflags &= ~(msr_data | EFLG_RF); #endif } else { /* legacy mode */ ops->get_msr(ctxt, MSR_STAR, &msr_data); ctxt->_eip = (u32)msr_data; ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF); } return X86EMUL_CONTINUE; } Commit Message: KVM: x86: fix missing checks in syscall emulation On hosts without this patch, 32bit guests will crash (and 64bit guests may behave in a wrong way) for example by simply executing following nasm-demo-application: [bits 32] global _start SECTION .text _start: syscall (I tested it with winxp and linux - both always crashed) Disassembly of section .text: 00000000 <_start>: 0: 0f 05 syscall The reason seems a missing "invalid opcode"-trap (int6) for the syscall opcode "0f05", which is not available on Intel CPUs within non-longmodes, as also on some AMD CPUs within legacy-mode. (depending on CPU vendor, MSR_EFER and cpuid) Because previous mentioned OSs may not engage corresponding syscall target-registers (STAR, LSTAR, CSTAR), they remain NULL and (non trapping) syscalls are leading to multiple faults and finally crashs. Depending on the architecture (AMD or Intel) pretended by guests, various checks according to vendor's documentation are implemented to overcome the current issue and behave like the CPUs physical counterparts. [mtosatti: cleanup/beautify code] Signed-off-by: Stephan Baerwolf <stephan.baerwolf@tu-ilmenau.de> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> CWE ID:
static int em_syscall(struct x86_emulate_ctxt *ctxt) { struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; /* syscall is not available in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_ud(ctxt); if (!(em_syscall_is_enabled(ctxt))) return emulate_ud(ctxt); ops->get_msr(ctxt, MSR_EFER, &efer); setup_syscalls_segments(ctxt, &cs, &ss); if (!(efer & EFER_SCE)) return emulate_ud(ctxt); ops->get_msr(ctxt, MSR_STAR, &msr_data); msr_data >>= 32; cs_sel = (u16)(msr_data & 0xfffc); ss_sel = (u16)(msr_data + 8); if (efer & EFER_LMA) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ctxt->regs[VCPU_REGS_RCX] = ctxt->_eip; if (efer & EFER_LMA) { #ifdef CONFIG_X86_64 ctxt->regs[VCPU_REGS_R11] = ctxt->eflags & ~EFLG_RF; ops->get_msr(ctxt, ctxt->mode == X86EMUL_MODE_PROT64 ? MSR_LSTAR : MSR_CSTAR, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data); ctxt->eflags &= ~(msr_data | EFLG_RF); #endif } else { /* legacy mode */ ops->get_msr(ctxt, MSR_STAR, &msr_data); ctxt->_eip = (u32)msr_data; ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF); } return X86EMUL_CONTINUE; }
4,672
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.
Code: static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmGlobalEntry *ptr = NULL; int buflen = bin->buf->length; if (sec->payload_data + 32 > buflen) { return NULL; } if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) { return ret; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) { goto beach; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) { goto beach; } if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } r_list_append (ret, ptr); r++; } return ret; beach: free (ptr); return ret; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125
static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmGlobalEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; int buflen = bin->buf->length - (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) { return ret; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) { goto beach; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) { goto beach; } if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } r_list_append (ret, ptr); r++; } return ret; beach: free (ptr); return ret; }
143
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.
Code: int use_conf(char *test_path) { int ret; size_t flags = 0; char filename[1024], errstr[1024]; char *buffer; FILE *infile, *conffile; json_t *json; json_error_t error; sprintf(filename, "%s%cinput", test_path, dir_sep); if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, "Could not open \"%s\"\n", filename); return 2; } sprintf(filename, "%s%cenv", test_path, dir_sep); conffile = fopen(filename, "rb"); if (conffile) { read_conf(conffile); fclose(conffile); } if (conf.indent < 0 || conf.indent > 255) { fprintf(stderr, "invalid value for JSON_INDENT: %d\n", conf.indent); return 2; } if (conf.indent) flags |= JSON_INDENT(conf.indent); if (conf.compact) flags |= JSON_COMPACT; if (conf.ensure_ascii) flags |= JSON_ENSURE_ASCII; if (conf.preserve_order) flags |= JSON_PRESERVE_ORDER; if (conf.sort_keys) flags |= JSON_SORT_KEYS; if (conf.strip) { /* Load to memory, strip leading and trailing whitespace */ buffer = loadfile(infile); json = json_loads(strip(buffer), 0, &error); free(buffer); } else json = json_loadf(infile, 0, &error); fclose(infile); if (!json) { sprintf(errstr, "%d %d %d\n%s\n", error.line, error.column, error.position, error.text); ret = cmpfile(errstr, test_path, "error"); return ret; } buffer = json_dumps(json, flags); ret = cmpfile(buffer, test_path, "output"); free(buffer); json_decref(json); return ret; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
int use_conf(char *test_path) { int ret; size_t flags = 0; char filename[1024], errstr[1024]; char *buffer; FILE *infile, *conffile; json_t *json; json_error_t error; sprintf(filename, "%s%cinput", test_path, dir_sep); if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, "Could not open \"%s\"\n", filename); return 2; } sprintf(filename, "%s%cenv", test_path, dir_sep); conffile = fopen(filename, "rb"); if (conffile) { read_conf(conffile); fclose(conffile); } if (conf.indent < 0 || conf.indent > 255) { fprintf(stderr, "invalid value for JSON_INDENT: %d\n", conf.indent); return 2; } if (conf.indent) flags |= JSON_INDENT(conf.indent); if (conf.compact) flags |= JSON_COMPACT; if (conf.ensure_ascii) flags |= JSON_ENSURE_ASCII; if (conf.preserve_order) flags |= JSON_PRESERVE_ORDER; if (conf.sort_keys) flags |= JSON_SORT_KEYS; if (conf.have_hashseed) json_object_seed(conf.hashseed); if (conf.strip) { /* Load to memory, strip leading and trailing whitespace */ buffer = loadfile(infile); json = json_loads(strip(buffer), 0, &error); free(buffer); } else json = json_loadf(infile, 0, &error); fclose(infile); if (!json) { sprintf(errstr, "%d %d %d\n%s\n", error.line, error.column, error.position, error.text); ret = cmpfile(errstr, test_path, "error"); return ret; } buffer = json_dumps(json, flags); ret = cmpfile(buffer, test_path, "output"); free(buffer); json_decref(json); return ret; }
28,947
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.
Code: static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; const struct bpf_map_ops *ops; struct bpf_insn_aux_data *aux; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || insn->code == (BPF_ALU | BPF_MOD | BPF_X) || insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; struct bpf_insn mask_and_div[] = { BPF_MOV32_REG(insn->src_reg, insn->src_reg), /* Rx div 0 -> 0 */ BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2), BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), BPF_JMP_IMM(BPF_JA, 0, 0, 1), *insn, }; struct bpf_insn mask_and_mod[] = { BPF_MOV32_REG(insn->src_reg, insn->src_reg), /* Rx mod 0 -> Rx */ BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1), *insn, }; struct bpf_insn *patchlet; if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { patchlet = mask_and_div + (is64 ? 1 : 0); cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0); } else { patchlet = mask_and_mod + (is64 ? 1 : 0); cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0); } new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (BPF_CLASS(insn->code) == BPF_LD && (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND)) { cnt = env->ops->gen_ld_abs(insn, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->src_reg == BPF_PSEUDO_CALL) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_override_return) prog->kprobe_override = 1; if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; env->prog->aux->max_pkt_offset = MAX_PACKET_OFF; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; aux = &env->insn_aux_data[i + delta]; if (!bpf_map_ptr_unpriv(aux)) continue; /* instead of changing every JIT dealing with tail_call * emit two extra insns: * if (index >= max_entries) goto out; * index &= array->index_mask; * to avoid out-of-bounds cpu speculation */ if (bpf_map_ptr_poisoned(aux)) { verbose(env, "tail_call abusing map_ptr\n"); return -EINVAL; } map_ptr = BPF_MAP_PTR(aux->map_state); insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, map_ptr->max_entries, 2); insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, container_of(map_ptr, struct bpf_array, map)->index_mask); insn_buf[2] = *insn; cnt = 3; new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * and other inlining handlers are currently limited to 64 bit * only. */ if (prog->jit_requested && BITS_PER_LONG == 64 && (insn->imm == BPF_FUNC_map_lookup_elem || insn->imm == BPF_FUNC_map_update_elem || insn->imm == BPF_FUNC_map_delete_elem || insn->imm == BPF_FUNC_map_push_elem || insn->imm == BPF_FUNC_map_pop_elem || insn->imm == BPF_FUNC_map_peek_elem)) { aux = &env->insn_aux_data[i + delta]; if (bpf_map_ptr_poisoned(aux)) goto patch_call_imm; map_ptr = BPF_MAP_PTR(aux->map_state); ops = map_ptr->ops; if (insn->imm == BPF_FUNC_map_lookup_elem && ops->map_gen_lookup) { cnt = ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, (void *(*)(struct bpf_map *map, void *key))NULL)); BUILD_BUG_ON(!__same_type(ops->map_delete_elem, (int (*)(struct bpf_map *map, void *key))NULL)); BUILD_BUG_ON(!__same_type(ops->map_update_elem, (int (*)(struct bpf_map *map, void *key, void *value, u64 flags))NULL)); BUILD_BUG_ON(!__same_type(ops->map_push_elem, (int (*)(struct bpf_map *map, void *value, u64 flags))NULL)); BUILD_BUG_ON(!__same_type(ops->map_pop_elem, (int (*)(struct bpf_map *map, void *value))NULL)); BUILD_BUG_ON(!__same_type(ops->map_peek_elem, (int (*)(struct bpf_map *map, void *value))NULL)); switch (insn->imm) { case BPF_FUNC_map_lookup_elem: insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - __bpf_call_base; continue; case BPF_FUNC_map_update_elem: insn->imm = BPF_CAST_CALL(ops->map_update_elem) - __bpf_call_base; continue; case BPF_FUNC_map_delete_elem: insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - __bpf_call_base; continue; case BPF_FUNC_map_push_elem: insn->imm = BPF_CAST_CALL(ops->map_push_elem) - __bpf_call_base; continue; case BPF_FUNC_map_pop_elem: insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - __bpf_call_base; continue; case BPF_FUNC_map_peek_elem: insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - __bpf_call_base; continue; } goto patch_call_imm; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm, env->prog); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } Commit Message: bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Acked-by: Alexei Starovoitov <ast@kernel.org> Signed-off-by: Alexei Starovoitov <ast@kernel.org> CWE ID: CWE-189
static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; const struct bpf_map_ops *ops; struct bpf_insn_aux_data *aux; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || insn->code == (BPF_ALU | BPF_MOD | BPF_X) || insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; struct bpf_insn mask_and_div[] = { BPF_MOV32_REG(insn->src_reg, insn->src_reg), /* Rx div 0 -> 0 */ BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2), BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), BPF_JMP_IMM(BPF_JA, 0, 0, 1), *insn, }; struct bpf_insn mask_and_mod[] = { BPF_MOV32_REG(insn->src_reg, insn->src_reg), /* Rx mod 0 -> Rx */ BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1), *insn, }; struct bpf_insn *patchlet; if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { patchlet = mask_and_div + (is64 ? 1 : 0); cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0); } else { patchlet = mask_and_mod + (is64 ? 1 : 0); cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0); } new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (BPF_CLASS(insn->code) == BPF_LD && (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND)) { cnt = env->ops->gen_ld_abs(insn, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; struct bpf_insn insn_buf[16]; struct bpf_insn *patch = &insn_buf[0]; bool issrc, isneg; u32 off_reg; aux = &env->insn_aux_data[i + delta]; if (!aux->alu_state) continue; isneg = aux->alu_state & BPF_ALU_NEG_VALUE; issrc = (aux->alu_state & BPF_ALU_SANITIZE) == BPF_ALU_SANITIZE_SRC; off_reg = issrc ? insn->src_reg : insn->dst_reg; if (isneg) *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1); *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); if (issrc) { *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); insn->src_reg = BPF_REG_AX; } else { *patch++ = BPF_ALU64_REG(BPF_AND, off_reg, BPF_REG_AX); } if (isneg) insn->code = insn->code == code_add ? code_sub : code_add; *patch++ = *insn; if (issrc && isneg) *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); cnt = patch - insn_buf; new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->src_reg == BPF_PSEUDO_CALL) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_override_return) prog->kprobe_override = 1; if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; env->prog->aux->max_pkt_offset = MAX_PACKET_OFF; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; aux = &env->insn_aux_data[i + delta]; if (!bpf_map_ptr_unpriv(aux)) continue; /* instead of changing every JIT dealing with tail_call * emit two extra insns: * if (index >= max_entries) goto out; * index &= array->index_mask; * to avoid out-of-bounds cpu speculation */ if (bpf_map_ptr_poisoned(aux)) { verbose(env, "tail_call abusing map_ptr\n"); return -EINVAL; } map_ptr = BPF_MAP_PTR(aux->map_state); insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, map_ptr->max_entries, 2); insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, container_of(map_ptr, struct bpf_array, map)->index_mask); insn_buf[2] = *insn; cnt = 3; new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * and other inlining handlers are currently limited to 64 bit * only. */ if (prog->jit_requested && BITS_PER_LONG == 64 && (insn->imm == BPF_FUNC_map_lookup_elem || insn->imm == BPF_FUNC_map_update_elem || insn->imm == BPF_FUNC_map_delete_elem || insn->imm == BPF_FUNC_map_push_elem || insn->imm == BPF_FUNC_map_pop_elem || insn->imm == BPF_FUNC_map_peek_elem)) { aux = &env->insn_aux_data[i + delta]; if (bpf_map_ptr_poisoned(aux)) goto patch_call_imm; map_ptr = BPF_MAP_PTR(aux->map_state); ops = map_ptr->ops; if (insn->imm == BPF_FUNC_map_lookup_elem && ops->map_gen_lookup) { cnt = ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, (void *(*)(struct bpf_map *map, void *key))NULL)); BUILD_BUG_ON(!__same_type(ops->map_delete_elem, (int (*)(struct bpf_map *map, void *key))NULL)); BUILD_BUG_ON(!__same_type(ops->map_update_elem, (int (*)(struct bpf_map *map, void *key, void *value, u64 flags))NULL)); BUILD_BUG_ON(!__same_type(ops->map_push_elem, (int (*)(struct bpf_map *map, void *value, u64 flags))NULL)); BUILD_BUG_ON(!__same_type(ops->map_pop_elem, (int (*)(struct bpf_map *map, void *value))NULL)); BUILD_BUG_ON(!__same_type(ops->map_peek_elem, (int (*)(struct bpf_map *map, void *value))NULL)); switch (insn->imm) { case BPF_FUNC_map_lookup_elem: insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - __bpf_call_base; continue; case BPF_FUNC_map_update_elem: insn->imm = BPF_CAST_CALL(ops->map_update_elem) - __bpf_call_base; continue; case BPF_FUNC_map_delete_elem: insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - __bpf_call_base; continue; case BPF_FUNC_map_push_elem: insn->imm = BPF_CAST_CALL(ops->map_push_elem) - __bpf_call_base; continue; case BPF_FUNC_map_pop_elem: insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - __bpf_call_base; continue; case BPF_FUNC_map_peek_elem: insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - __bpf_call_base; continue; } goto patch_call_imm; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm, env->prog); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; }
1,905
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.
Code: static void usb_ehci_pci_exit(PCIDevice *dev) { EHCIPCIState *i = PCI_EHCI(dev); static void usb_ehci_pci_reset(DeviceState *dev) { PCIDevice *pci_dev = PCI_DEVICE(dev); EHCIPCIState *i = PCI_EHCI(pci_dev); EHCIState *s = &i->ehci; ehci_reset(s); } static void usb_ehci_pci_write_config(PCIDevice *dev, uint32_t addr, uint32_t val, int l) { EHCIPCIState *i = PCI_EHCI(dev); bool busmaster; pci_default_write_config(dev, addr, val, l); if (!range_covers_byte(addr, l, PCI_COMMAND)) { return; } busmaster = pci_get_word(dev->config + PCI_COMMAND) & PCI_COMMAND_MASTER; i->ehci.as = busmaster ? pci_get_address_space(dev) : &address_space_memory; } static Property ehci_pci_properties[] = { DEFINE_PROP_UINT32("maxframes", EHCIPCIState, ehci.maxframes, 128), DEFINE_PROP_END_OF_LIST(), }; static const VMStateDescription vmstate_ehci_pci = { .name = "ehci", .version_id = 2, .minimum_version_id = 1, .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(pcidev, EHCIPCIState), VMSTATE_STRUCT(ehci, EHCIPCIState, 2, vmstate_ehci, EHCIState), VMSTATE_END_OF_LIST() } }; static void ehci_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->realize = usb_ehci_pci_realize; k->exit = usb_ehci_pci_exit; k->class_id = PCI_CLASS_SERIAL_USB; k->config_write = usb_ehci_pci_write_config; dc->vmsd = &vmstate_ehci_pci; dc->props = ehci_pci_properties; dc->reset = usb_ehci_pci_reset; } static const TypeInfo ehci_pci_type_info = { .name = TYPE_PCI_EHCI, .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(EHCIPCIState), .instance_init = usb_ehci_pci_init, .abstract = true, .class_init = ehci_class_init, }; static void ehci_data_class_init(ObjectClass *klass, void *data) .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(EHCIPCIState), .instance_init = usb_ehci_pci_init, .abstract = true, .class_init = ehci_class_init, }; Commit Message: CWE ID: CWE-772
static void usb_ehci_pci_exit(PCIDevice *dev) { EHCIPCIState *i = PCI_EHCI(dev); static void usb_ehci_pci_reset(DeviceState *dev) { PCIDevice *pci_dev = PCI_DEVICE(dev); EHCIPCIState *i = PCI_EHCI(pci_dev); EHCIState *s = &i->ehci; ehci_reset(s); } static void usb_ehci_pci_write_config(PCIDevice *dev, uint32_t addr, uint32_t val, int l) { EHCIPCIState *i = PCI_EHCI(dev); bool busmaster; pci_default_write_config(dev, addr, val, l); if (!range_covers_byte(addr, l, PCI_COMMAND)) { return; } busmaster = pci_get_word(dev->config + PCI_COMMAND) & PCI_COMMAND_MASTER; i->ehci.as = busmaster ? pci_get_address_space(dev) : &address_space_memory; } static Property ehci_pci_properties[] = { DEFINE_PROP_UINT32("maxframes", EHCIPCIState, ehci.maxframes, 128), DEFINE_PROP_END_OF_LIST(), }; static const VMStateDescription vmstate_ehci_pci = { .name = "ehci", .version_id = 2, .minimum_version_id = 1, .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(pcidev, EHCIPCIState), VMSTATE_STRUCT(ehci, EHCIPCIState, 2, vmstate_ehci, EHCIState), VMSTATE_END_OF_LIST() } }; static void ehci_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->realize = usb_ehci_pci_realize; k->exit = usb_ehci_pci_exit; k->class_id = PCI_CLASS_SERIAL_USB; k->config_write = usb_ehci_pci_write_config; dc->vmsd = &vmstate_ehci_pci; dc->props = ehci_pci_properties; dc->reset = usb_ehci_pci_reset; } static const TypeInfo ehci_pci_type_info = { .name = TYPE_PCI_EHCI, .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(EHCIPCIState), .instance_init = usb_ehci_pci_init, .abstract = true, .class_init = ehci_class_init, }; static void ehci_data_class_init(ObjectClass *klass, void *data) .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(EHCIPCIState), .instance_init = usb_ehci_pci_init, .instance_finalize = usb_ehci_pci_finalize, .abstract = true, .class_init = ehci_class_init, };
9,415
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.
Code: status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { ALOGV("entering parseChunk %lld/%d", (long long)*offset, depth); if (*offset < 0) { ALOGE("b/23540914"); return ERROR_MALFORMED; } if (depth > 100) { ALOGE("b/27456299"); return ERROR_MALFORMED; } uint32_t hdr[2]; if (mDataSource->readAt(*offset, hdr, 8) < 8) { return ERROR_IO; } uint64_t chunk_size = ntohl(hdr[0]); int32_t chunk_type = ntohl(hdr[1]); off64_t data_offset = *offset + 8; if (chunk_size == 1) { if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { return ERROR_IO; } chunk_size = ntoh64(chunk_size); data_offset += 8; if (chunk_size < 16) { return ERROR_MALFORMED; } } else if (chunk_size == 0) { if (depth == 0) { off64_t sourceSize; if (mDataSource->getSize(&sourceSize) == OK) { chunk_size = (sourceSize - *offset); } else { ALOGE("atom size is 0, and data source has no size"); return ERROR_MALFORMED; } } else { *offset += 4; return OK; } } else if (chunk_size < 8) { ALOGE("invalid chunk size: %" PRIu64, chunk_size); return ERROR_MALFORMED; } char chunk[5]; MakeFourCCString(chunk_type, chunk); ALOGV("chunk: %s @ %lld, %d", chunk, (long long)*offset, depth); if (kUseHexDump) { static const char kWhitespace[] = " "; const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size); char buffer[256]; size_t n = chunk_size; if (n > sizeof(buffer)) { n = sizeof(buffer); } if (mDataSource->readAt(*offset, buffer, n) < (ssize_t)n) { return ERROR_IO; } hexdump(buffer, n); } PathAdder autoAdder(&mPath, chunk_type); off64_t chunk_data_size = chunk_size - (data_offset - *offset); if (chunk_data_size < 0) { ALOGE("b/23540914"); return ERROR_MALFORMED; } if (chunk_type != FOURCC('m', 'd', 'a', 't') && chunk_data_size > kMaxAtomSize) { char errMsg[100]; sprintf(errMsg, "%s atom has size %" PRId64, chunk, chunk_data_size); ALOGE("%s (b/28615448)", errMsg); android_errorWriteWithInfoLog(0x534e4554, "28615448", -1, errMsg, strlen(errMsg)); return ERROR_MALFORMED; } if (chunk_type != FOURCC('c', 'p', 'r', 't') && chunk_type != FOURCC('c', 'o', 'v', 'r') && mPath.size() == 5 && underMetaDataPath(mPath)) { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } return OK; } switch(chunk_type) { case FOURCC('m', 'o', 'o', 'v'): case FOURCC('t', 'r', 'a', 'k'): case FOURCC('m', 'd', 'i', 'a'): case FOURCC('m', 'i', 'n', 'f'): case FOURCC('d', 'i', 'n', 'f'): case FOURCC('s', 't', 'b', 'l'): case FOURCC('m', 'v', 'e', 'x'): case FOURCC('m', 'o', 'o', 'f'): case FOURCC('t', 'r', 'a', 'f'): case FOURCC('m', 'f', 'r', 'a'): case FOURCC('u', 'd', 't', 'a'): case FOURCC('i', 'l', 's', 't'): case FOURCC('s', 'i', 'n', 'f'): case FOURCC('s', 'c', 'h', 'i'): case FOURCC('e', 'd', 't', 's'): case FOURCC('w', 'a', 'v', 'e'): { if (chunk_type == FOURCC('m', 'o', 'o', 'v') && depth != 0) { ALOGE("moov: depth %d", depth); return ERROR_MALFORMED; } if (chunk_type == FOURCC('m', 'o', 'o', 'f') && !mMoofFound) { mMoofFound = true; mMoofOffset = *offset; } if (chunk_type == FOURCC('s', 't', 'b', 'l')) { ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size); if (mDataSource->flags() & (DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) { sp<MPEG4DataSource> cachedSource = new MPEG4DataSource(mDataSource); if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { mDataSource = cachedSource; } } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->sampleTable = new SampleTable(mDataSource); } bool isTrack = false; if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { if (depth != 1) { ALOGE("trak: depth %d", depth); return ERROR_MALFORMED; } isTrack = true; Track *track = new Track; track->next = NULL; if (mLastTrack) { mLastTrack->next = track; } else { mFirstTrack = track; } mLastTrack = track; track->meta = new MetaData; track->includes_expensive_metadata = false; track->skipTrack = false; track->timescale = 0; track->meta->setCString(kKeyMIMEType, "application/octet-stream"); } off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { if (isTrack) { mLastTrack->skipTrack = true; break; } return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } if (isTrack) { int32_t trackId; if (!mLastTrack->meta->findInt32(kKeyTrackID, &trackId)) { mLastTrack->skipTrack = true; } if (mLastTrack->skipTrack) { Track *cur = mFirstTrack; if (cur == mLastTrack) { delete cur; mFirstTrack = mLastTrack = NULL; } else { while (cur && cur->next != mLastTrack) { cur = cur->next; } if (cur) { cur->next = NULL; } delete mLastTrack; mLastTrack = cur; } return OK; } status_t err = verifyTrack(mLastTrack); if (err != OK) { return err; } } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { mInitCheck = OK; if (!mIsDrm) { return UNKNOWN_ERROR; // Return a dummy error. } else { return OK; } } break; } case FOURCC('e', 'l', 's', 't'): { *offset += chunk_size; uint8_t version; if (mDataSource->readAt(data_offset, &version, 1) < 1) { return ERROR_IO; } uint32_t entry_count; if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { return ERROR_IO; } if (entry_count != 1) { ALOGW("ignoring edit list with %d entries", entry_count); } else if (mHeaderTimescale == 0) { ALOGW("ignoring edit list because timescale is 0"); } else { off64_t entriesoffset = data_offset + 8; uint64_t segment_duration; int64_t media_time; if (version == 1) { if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { return ERROR_IO; } } else if (version == 0) { uint32_t sd; int32_t mt; if (!mDataSource->getUInt32(entriesoffset, &sd) || !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { return ERROR_IO; } segment_duration = sd; media_time = mt; } else { return ERROR_IO; } uint64_t halfscale = mHeaderTimescale / 2; segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; int64_t duration; int32_t samplerate; if (!mLastTrack) { return ERROR_MALFORMED; } if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { int64_t delay = (media_time * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); int64_t paddingus = duration - (int64_t)(segment_duration + media_time); if (paddingus < 0) { paddingus = 0; } int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); } } break; } case FOURCC('f', 'r', 'm', 'a'): { *offset += chunk_size; uint32_t original_fourcc; if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { return ERROR_IO; } original_fourcc = ntohl(original_fourcc); ALOGV("read original format: %d", original_fourcc); if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); uint32_t num_channels = 0; uint32_t sample_rate = 0; if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); } break; } case FOURCC('t', 'e', 'n', 'c'): { *offset += chunk_size; if (chunk_size < 32) { return ERROR_MALFORMED; } char buf[4]; memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { return ERROR_IO; } uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); if (defaultAlgorithmId > 1) { return ERROR_MALFORMED; } memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { return ERROR_IO; } uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || (defaultAlgorithmId != 0 && defaultIVSize == 0)) { return ERROR_MALFORMED; } else if (defaultIVSize != 0 && defaultIVSize != 8 && defaultIVSize != 16) { return ERROR_MALFORMED; } uint8_t defaultKeyId[16]; if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); break; } case FOURCC('t', 'k', 'h', 'd'): { *offset += chunk_size; status_t err; if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { return err; } break; } case FOURCC('p', 's', 's', 'h'): { *offset += chunk_size; PsshInfo pssh; if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { return ERROR_IO; } uint32_t psshdatalen = 0; if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { return ERROR_IO; } pssh.datalen = ntohl(psshdatalen); ALOGV("pssh data size: %d", pssh.datalen); if (chunk_size < 20 || pssh.datalen > chunk_size - 20) { return ERROR_MALFORMED; } pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; if (pssh.data == NULL) { return ERROR_MALFORMED; } ALOGV("allocated pssh @ %p", pssh.data); ssize_t requested = (ssize_t) pssh.datalen; if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { delete[] pssh.data; return ERROR_IO; } mPssh.push_back(pssh); break; } case FOURCC('m', 'd', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 4 || mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t version; if (mDataSource->readAt( data_offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } off64_t timescale_offset; if (version == 1) { timescale_offset = data_offset + 4 + 16; } else if (version == 0) { timescale_offset = data_offset + 4 + 8; } else { return ERROR_IO; } uint32_t timescale; if (mDataSource->readAt( timescale_offset, &timescale, sizeof(timescale)) < (ssize_t)sizeof(timescale)) { return ERROR_IO; } if (!timescale) { ALOGE("timescale should not be ZERO."); return ERROR_MALFORMED; } mLastTrack->timescale = ntohl(timescale); int64_t duration = 0; if (version == 1) { if (mDataSource->readAt( timescale_offset + 4, &duration, sizeof(duration)) < (ssize_t)sizeof(duration)) { return ERROR_IO; } if (duration != -1) { duration = ntoh64(duration); } } else { uint32_t duration32; if (mDataSource->readAt( timescale_offset + 4, &duration32, sizeof(duration32)) < (ssize_t)sizeof(duration32)) { return ERROR_IO; } if (duration32 != 0xffffffff) { duration = ntohl(duration32); } } if (duration != 0 && mLastTrack->timescale != 0) { mLastTrack->meta->setInt64( kKeyDuration, (duration * 1000000) / mLastTrack->timescale); } uint8_t lang[2]; off64_t lang_offset; if (version == 1) { lang_offset = timescale_offset + 4 + 8; } else if (version == 0) { lang_offset = timescale_offset + 4 + 4; } else { return ERROR_IO; } if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) < (ssize_t)sizeof(lang)) { return ERROR_IO; } char lang_code[4]; lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; lang_code[2] = (lang[1] & 0x1f) + 0x60; lang_code[3] = '\0'; mLastTrack->meta->setCString( kKeyMediaLanguage, lang_code); break; } case FOURCC('s', 't', 's', 'd'): { uint8_t buffer[8]; if (chunk_data_size < (off64_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 8) < 8) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } uint32_t entry_count = U32_AT(&buffer[4]); if (entry_count > 1) { const char *mime; if (mLastTrack == NULL) return ERROR_MALFORMED; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && strcasecmp(mime, "application/octet-stream")) { mLastTrack->skipTrack = true; *offset += chunk_size; break; } } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + 8; for (uint32_t i = 0; i < entry_count; ++i) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 't', 't'): { *offset += chunk_size; if (mLastTrack == NULL) return ERROR_MALFORMED; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } String8 mimeFormat((const char *)(buffer->data()), chunk_data_size); mLastTrack->meta->setCString(kKeyMIMEType, mimeFormat.string()); break; } case FOURCC('m', 'p', '4', 'a'): case FOURCC('e', 'n', 'c', 'a'): case FOURCC('s', 'a', 'm', 'r'): case FOURCC('s', 'a', 'w', 'b'): { if (mIsQT && chunk_type == FOURCC('m', 'p', '4', 'a') && depth >= 1 && mPath[depth - 1] == FOURCC('w', 'a', 'v', 'e')) { *offset += chunk_size; break; } uint8_t buffer[8 + 20]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index __unused = U16_AT(&buffer[6]); uint16_t version = U16_AT(&buffer[8]); uint32_t num_channels = U16_AT(&buffer[16]); uint16_t sample_size = U16_AT(&buffer[18]); uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; if (mLastTrack == NULL) return ERROR_MALFORMED; off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); if (mIsQT && chunk_type == FOURCC('m', 'p', '4', 'a')) { if (version == 1) { if (mDataSource->readAt(*offset, buffer, 16) < 16) { return ERROR_IO; } #if 0 U32_AT(buffer); // samples per packet U32_AT(&buffer[4]); // bytes per packet U32_AT(&buffer[8]); // bytes per frame U32_AT(&buffer[12]); // bytes per sample #endif *offset += 16; } else if (version == 2) { uint8_t v2buffer[36]; if (mDataSource->readAt(*offset, v2buffer, 36) < 36) { return ERROR_IO; } #if 0 U32_AT(v2buffer); // size of struct only sample_rate = (uint32_t)U64_AT(&v2buffer[4]); // audio sample rate num_channels = U32_AT(&v2buffer[12]); // num audio channels U32_AT(&v2buffer[16]); // always 0x7f000000 sample_size = (uint16_t)U32_AT(&v2buffer[20]); // const bits per channel U32_AT(&v2buffer[24]); // format specifc flags U32_AT(&v2buffer[28]); // const bytes per audio packet U32_AT(&v2buffer[32]); // const LPCM frames per audio packet #endif *offset += 36; } } if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); } ALOGV("*** coding='%s' %d channels, size %d, rate %d\n", chunk, num_channels, sample_size, sample_rate); mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'v'): case FOURCC('e', 'n', 'c', 'v'): case FOURCC('s', '2', '6', '3'): case FOURCC('H', '2', '6', '3'): case FOURCC('h', '2', '6', '3'): case FOURCC('a', 'v', 'c', '1'): case FOURCC('h', 'v', 'c', '1'): case FOURCC('h', 'e', 'v', '1'): { uint8_t buffer[78]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index __unused = U16_AT(&buffer[6]); uint16_t width = U16_AT(&buffer[6 + 18]); uint16_t height = U16_AT(&buffer[6 + 20]); if (width == 0) width = 352; if (height == 0) height = 288; if (mLastTrack == NULL) return ERROR_MALFORMED; if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); } mLastTrack->meta->setInt32(kKeyWidth, width); mLastTrack->meta->setInt32(kKeyHeight, height); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('s', 't', 'c', 'o'): case FOURCC('c', 'o', '6', '4'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setChunkOffsetParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'c'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setSampleToChunkParams( data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'z'): case FOURCC('s', 't', 'z', '2'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setSampleSizeParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } size_t max_size; err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); if (err != OK) { return err; } if (max_size != 0) { if (max_size > SIZE_MAX - 10 * 2) { ALOGE("max sample size too big: %zu", max_size); return ERROR_MALFORMED; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); } else { uint32_t width, height; if (!mLastTrack->meta->findInt32(kKeyWidth, (int32_t*)&width) || !mLastTrack->meta->findInt32(kKeyHeight,(int32_t*) &height)) { ALOGE("No width or height, assuming worst case 1080p"); width = 1920; height = 1080; } else { if (width > 32768 || height > 32768) { ALOGE("can't support %u x %u video", width, height); return ERROR_MALFORMED; } } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) || !strcmp(mime, MEDIA_MIMETYPE_VIDEO_HEVC)) { max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; } else { max_size = width * height * 3 / 2; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp("video/", mime, 6)) { size_t nSamples = mLastTrack->sampleTable->countSamples(); if (nSamples == 0) { int32_t trackId; if (mLastTrack->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(i); if (t->track_ID == (uint32_t) trackId) { if (t->default_sample_duration > 0) { int32_t frameRate = mLastTrack->timescale / t->default_sample_duration; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } break; } } } } else { int64_t durationUs; if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > 0) { int32_t frameRate = (nSamples * 1000000LL + (durationUs >> 1)) / durationUs; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } } } } break; } case FOURCC('s', 't', 't', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('c', 't', 't', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setCompositionTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setSyncSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC(0xA9, 'x', 'y', 'z'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } char buffer[18 + 8]; off64_t location_length = chunk_data_size - 5; if (location_length >= (off64_t) sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset + 4, buffer, location_length) < location_length) { return ERROR_IO; } buffer[location_length] = '\0'; mFileMetaData->setCString(kKeyLocation, buffer); break; } case FOURCC('e', 's', 'd', 's'): { *offset += chunk_size; if (chunk_data_size < 4) { return ERROR_MALFORMED; } uint8_t buffer[256]; if (chunk_data_size > (off64_t)sizeof(buffer)) { return ERROR_BUFFER_TOO_SMALL; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( &buffer[4], chunk_data_size - 4); if (err != OK) { return err; } } if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'v')) { ESDS esds(&buffer[4], chunk_data_size - 4); uint8_t objectTypeIndication; if (esds.getObjectTypeIndication(&objectTypeIndication) == OK) { if (objectTypeIndication >= 0x60 && objectTypeIndication <= 0x65) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2); } } } break; } case FOURCC('b', 't', 'r', 't'): { *offset += chunk_size; if (mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t buffer[12]; if (chunk_data_size != sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } uint32_t maxBitrate = U32_AT(&buffer[4]); uint32_t avgBitrate = U32_AT(&buffer[8]); if (maxBitrate > 0 && maxBitrate < INT32_MAX) { mLastTrack->meta->setInt32(kKeyMaxBitRate, (int32_t)maxBitrate); } if (avgBitrate > 0 && avgBitrate < INT32_MAX) { mLastTrack->meta->setInt32(kKeyBitRate, (int32_t)avgBitrate); } break; } case FOURCC('a', 'v', 'c', 'C'): { *offset += chunk_size; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); break; } case FOURCC('h', 'v', 'c', 'C'): { sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); *offset += chunk_size; break; } case FOURCC('d', '2', '6', '3'): { *offset += chunk_size; /* * d263 contains a fixed 7 bytes part: * vendor - 4 bytes * version - 1 byte * level - 1 byte * profile - 1 byte * optionally, "d263" box itself may contain a 16-byte * bit rate box (bitr) * average bit rate - 4 bytes * max bit rate - 4 bytes */ char buffer[23]; if (chunk_data_size != 7 && chunk_data_size != 23) { ALOGE("Incorrect D263 box size %lld", (long long)chunk_data_size); return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); break; } case FOURCC('m', 'e', 't', 'a'): { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; bool isParsingMetaKeys = underQTMetaPath(mPath, 2); if (!isParsingMetaKeys) { uint8_t buffer[4]; if (chunk_data_size < (off64_t)sizeof(buffer)) { *offset = stop_offset; return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 4) < 4) { *offset = stop_offset; return ERROR_IO; } if (U32_AT(buffer) != 0) { *offset = stop_offset; return OK; } *offset += sizeof(buffer); } while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 'a', 'n'): case FOURCC('n', 'a', 'm', 'e'): case FOURCC('d', 'a', 't', 'a'): { *offset += chunk_size; if (mPath.size() == 6 && underMetaDataPath(mPath)) { status_t err = parseITunesMetaData(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('m', 'v', 'h', 'd'): { *offset += chunk_size; if (depth != 1) { ALOGE("mvhd: depth %d", depth); return ERROR_MALFORMED; } if (chunk_data_size < 32) { return ERROR_MALFORMED; } uint8_t header[32]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } uint64_t creationTime; uint64_t duration = 0; if (header[0] == 1) { creationTime = U64_AT(&header[4]); mHeaderTimescale = U32_AT(&header[20]); duration = U64_AT(&header[24]); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (header[0] != 0) { return ERROR_MALFORMED; } else { creationTime = U32_AT(&header[4]); mHeaderTimescale = U32_AT(&header[12]); uint32_t d32 = U32_AT(&header[16]); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } if (duration != 0 && mHeaderTimescale != 0 && duration < UINT64_MAX / 1000000) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } String8 s; if (convertTimeToDate(creationTime, &s)) { mFileMetaData->setCString(kKeyDate, s.string()); } break; } case FOURCC('m', 'e', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t flags[4]; if (mDataSource->readAt( data_offset, flags, sizeof(flags)) < (ssize_t)sizeof(flags)) { return ERROR_IO; } uint64_t duration = 0; if (flags[0] == 1) { if (chunk_data_size < 12) { return ERROR_MALFORMED; } mDataSource->getUInt64(data_offset + 4, &duration); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (flags[0] == 0) { uint32_t d32; mDataSource->getUInt32(data_offset + 4, &d32); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } else { return ERROR_MALFORMED; } if (duration != 0 && mHeaderTimescale != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } break; } case FOURCC('m', 'd', 'a', 't'): { ALOGV("mdat chunk, drm: %d", mIsDrm); mMdatFound = true; if (!mIsDrm) { *offset += chunk_size; break; } if (chunk_size < 8) { return ERROR_MALFORMED; } return parseDrmSINF(offset, data_offset); } case FOURCC('h', 'd', 'l', 'r'): { *offset += chunk_size; if (underQTMetaPath(mPath, 3)) { break; } uint32_t buffer; if (mDataSource->readAt( data_offset + 8, &buffer, 4) < 4) { return ERROR_IO; } uint32_t type = ntohl(buffer); if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { if (mLastTrack != NULL) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); } } break; } case FOURCC('k', 'e', 'y', 's'): { *offset += chunk_size; if (underQTMetaPath(mPath, 3)) { status_t err = parseQTMetaKey(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('t', 'r', 'e', 'x'): { *offset += chunk_size; if (chunk_data_size < 24) { return ERROR_IO; } Trex trex; if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { return ERROR_IO; } mTrex.add(trex); break; } case FOURCC('t', 'x', '3', 'g'): { if (mLastTrack == NULL) return ERROR_MALFORMED; uint32_t type; const void *data; size_t size = 0; if (!mLastTrack->meta->findData( kKeyTextFormatData, &type, &data, &size)) { size = 0; } if ((chunk_size > SIZE_MAX) || (SIZE_MAX - chunk_size <= size)) { return ERROR_MALFORMED; } uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size]; if (buffer == NULL) { return ERROR_MALFORMED; } if (size > 0) { memcpy(buffer, data, size); } if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) < chunk_size) { delete[] buffer; buffer = NULL; *offset += chunk_size; return ERROR_IO; } mLastTrack->meta->setData( kKeyTextFormatData, 0, buffer, size + chunk_size); delete[] buffer; *offset += chunk_size; break; } case FOURCC('c', 'o', 'v', 'r'): { *offset += chunk_size; if (mFileMetaData != NULL) { ALOGV("chunk_data_size = %" PRId64 " and data_offset = %" PRId64, chunk_data_size, data_offset); if (chunk_data_size < 0 || static_cast<uint64_t>(chunk_data_size) >= SIZE_MAX - 1) { return ERROR_MALFORMED; } sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { return ERROR_IO; } const int kSkipBytesOfDataBox = 16; if (chunk_data_size <= kSkipBytesOfDataBox) { return ERROR_MALFORMED; } mFileMetaData->setData( kKeyAlbumArt, MetaData::TYPE_NONE, buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); } break; } case FOURCC('c', 'o', 'l', 'r'): { *offset += chunk_size; if (depth >= 2 && mPath[depth - 2] == FOURCC('s', 't', 's', 'd')) { status_t err = parseColorInfo(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('t', 'i', 't', 'l'): case FOURCC('p', 'e', 'r', 'f'): case FOURCC('a', 'u', 't', 'h'): case FOURCC('g', 'n', 'r', 'e'): case FOURCC('a', 'l', 'b', 'm'): case FOURCC('y', 'r', 'r', 'c'): { *offset += chunk_size; status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); if (err != OK) { return err; } break; } case FOURCC('I', 'D', '3', '2'): { *offset += chunk_size; if (chunk_data_size < 6) { return ERROR_MALFORMED; } parseID3v2MetaData(data_offset + 6); break; } case FOURCC('-', '-', '-', '-'): { mLastCommentMean.clear(); mLastCommentName.clear(); mLastCommentData.clear(); *offset += chunk_size; break; } case FOURCC('s', 'i', 'd', 'x'): { status_t err = parseSegmentIndex(data_offset, chunk_data_size); if (err != OK) { return err; } *offset += chunk_size; return UNKNOWN_ERROR; // stop parsing after sidx } case FOURCC('a', 'c', '-', '3'): { *offset += chunk_size; return parseAC3SampleEntry(data_offset); } case FOURCC('f', 't', 'y', 'p'): { if (chunk_data_size < 8 || depth != 0) { return ERROR_MALFORMED; } off64_t stop_offset = *offset + chunk_size; uint32_t numCompatibleBrands = (chunk_data_size - 8) / 4; for (size_t i = 0; i < numCompatibleBrands + 2; ++i) { if (i == 1) { continue; } uint32_t brand; if (mDataSource->readAt(data_offset + 4 * i, &brand, 4) < 4) { return ERROR_MALFORMED; } brand = ntohl(brand); if (brand == FOURCC('q', 't', ' ', ' ')) { mIsQT = true; break; } } *offset = stop_offset; break; } default: { if (underQTMetaPath(mPath, 3)) { status_t err = parseQTMetaVal(chunk_type, data_offset, chunk_data_size); if (err != OK) { return err; } } *offset += chunk_size; break; } } return OK; } Commit Message: Skip track if verification fails Bug: 62187433 Test: ran poc, CTS Change-Id: Ib9b0b6de88d046d8149e9ea5073d6c40ffec7b0c (cherry picked from commit ef8c7830d838d877e6b37b75b47294b064c79397) CWE ID:
status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { ALOGV("entering parseChunk %lld/%d", (long long)*offset, depth); if (*offset < 0) { ALOGE("b/23540914"); return ERROR_MALFORMED; } if (depth > 100) { ALOGE("b/27456299"); return ERROR_MALFORMED; } uint32_t hdr[2]; if (mDataSource->readAt(*offset, hdr, 8) < 8) { return ERROR_IO; } uint64_t chunk_size = ntohl(hdr[0]); int32_t chunk_type = ntohl(hdr[1]); off64_t data_offset = *offset + 8; if (chunk_size == 1) { if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { return ERROR_IO; } chunk_size = ntoh64(chunk_size); data_offset += 8; if (chunk_size < 16) { return ERROR_MALFORMED; } } else if (chunk_size == 0) { if (depth == 0) { off64_t sourceSize; if (mDataSource->getSize(&sourceSize) == OK) { chunk_size = (sourceSize - *offset); } else { ALOGE("atom size is 0, and data source has no size"); return ERROR_MALFORMED; } } else { *offset += 4; return OK; } } else if (chunk_size < 8) { ALOGE("invalid chunk size: %" PRIu64, chunk_size); return ERROR_MALFORMED; } char chunk[5]; MakeFourCCString(chunk_type, chunk); ALOGV("chunk: %s @ %lld, %d", chunk, (long long)*offset, depth); if (kUseHexDump) { static const char kWhitespace[] = " "; const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size); char buffer[256]; size_t n = chunk_size; if (n > sizeof(buffer)) { n = sizeof(buffer); } if (mDataSource->readAt(*offset, buffer, n) < (ssize_t)n) { return ERROR_IO; } hexdump(buffer, n); } PathAdder autoAdder(&mPath, chunk_type); off64_t chunk_data_size = chunk_size - (data_offset - *offset); if (chunk_data_size < 0) { ALOGE("b/23540914"); return ERROR_MALFORMED; } if (chunk_type != FOURCC('m', 'd', 'a', 't') && chunk_data_size > kMaxAtomSize) { char errMsg[100]; sprintf(errMsg, "%s atom has size %" PRId64, chunk, chunk_data_size); ALOGE("%s (b/28615448)", errMsg); android_errorWriteWithInfoLog(0x534e4554, "28615448", -1, errMsg, strlen(errMsg)); return ERROR_MALFORMED; } if (chunk_type != FOURCC('c', 'p', 'r', 't') && chunk_type != FOURCC('c', 'o', 'v', 'r') && mPath.size() == 5 && underMetaDataPath(mPath)) { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } return OK; } switch(chunk_type) { case FOURCC('m', 'o', 'o', 'v'): case FOURCC('t', 'r', 'a', 'k'): case FOURCC('m', 'd', 'i', 'a'): case FOURCC('m', 'i', 'n', 'f'): case FOURCC('d', 'i', 'n', 'f'): case FOURCC('s', 't', 'b', 'l'): case FOURCC('m', 'v', 'e', 'x'): case FOURCC('m', 'o', 'o', 'f'): case FOURCC('t', 'r', 'a', 'f'): case FOURCC('m', 'f', 'r', 'a'): case FOURCC('u', 'd', 't', 'a'): case FOURCC('i', 'l', 's', 't'): case FOURCC('s', 'i', 'n', 'f'): case FOURCC('s', 'c', 'h', 'i'): case FOURCC('e', 'd', 't', 's'): case FOURCC('w', 'a', 'v', 'e'): { if (chunk_type == FOURCC('m', 'o', 'o', 'v') && depth != 0) { ALOGE("moov: depth %d", depth); return ERROR_MALFORMED; } if (chunk_type == FOURCC('m', 'o', 'o', 'v') && mInitCheck == OK) { ALOGE("duplicate moov"); return ERROR_MALFORMED; } if (chunk_type == FOURCC('m', 'o', 'o', 'f') && !mMoofFound) { mMoofFound = true; mMoofOffset = *offset; } if (chunk_type == FOURCC('s', 't', 'b', 'l')) { ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size); if (mDataSource->flags() & (DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) { sp<MPEG4DataSource> cachedSource = new MPEG4DataSource(mDataSource); if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { mDataSource = cachedSource; } } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->sampleTable = new SampleTable(mDataSource); } bool isTrack = false; if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { if (depth != 1) { ALOGE("trak: depth %d", depth); return ERROR_MALFORMED; } isTrack = true; Track *track = new Track; track->next = NULL; if (mLastTrack) { mLastTrack->next = track; } else { mFirstTrack = track; } mLastTrack = track; track->meta = new MetaData; track->includes_expensive_metadata = false; track->skipTrack = false; track->timescale = 0; track->meta->setCString(kKeyMIMEType, "application/octet-stream"); } off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { if (isTrack) { mLastTrack->skipTrack = true; break; } return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } if (isTrack) { int32_t trackId; if (!mLastTrack->meta->findInt32(kKeyTrackID, &trackId)) { mLastTrack->skipTrack = true; } status_t err = verifyTrack(mLastTrack); if (err != OK) { mLastTrack->skipTrack = true; } if (mLastTrack->skipTrack) { Track *cur = mFirstTrack; if (cur == mLastTrack) { delete cur; mFirstTrack = mLastTrack = NULL; } else { while (cur && cur->next != mLastTrack) { cur = cur->next; } if (cur) { cur->next = NULL; } delete mLastTrack; mLastTrack = cur; } return OK; } } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { mInitCheck = OK; if (!mIsDrm) { return UNKNOWN_ERROR; // Return a dummy error. } else { return OK; } } break; } case FOURCC('e', 'l', 's', 't'): { *offset += chunk_size; uint8_t version; if (mDataSource->readAt(data_offset, &version, 1) < 1) { return ERROR_IO; } uint32_t entry_count; if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { return ERROR_IO; } if (entry_count != 1) { ALOGW("ignoring edit list with %d entries", entry_count); } else if (mHeaderTimescale == 0) { ALOGW("ignoring edit list because timescale is 0"); } else { off64_t entriesoffset = data_offset + 8; uint64_t segment_duration; int64_t media_time; if (version == 1) { if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { return ERROR_IO; } } else if (version == 0) { uint32_t sd; int32_t mt; if (!mDataSource->getUInt32(entriesoffset, &sd) || !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { return ERROR_IO; } segment_duration = sd; media_time = mt; } else { return ERROR_IO; } uint64_t halfscale = mHeaderTimescale / 2; segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; int64_t duration; int32_t samplerate; if (!mLastTrack) { return ERROR_MALFORMED; } if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { int64_t delay = (media_time * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); int64_t paddingus = duration - (int64_t)(segment_duration + media_time); if (paddingus < 0) { paddingus = 0; } int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); } } break; } case FOURCC('f', 'r', 'm', 'a'): { *offset += chunk_size; uint32_t original_fourcc; if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { return ERROR_IO; } original_fourcc = ntohl(original_fourcc); ALOGV("read original format: %d", original_fourcc); if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); uint32_t num_channels = 0; uint32_t sample_rate = 0; if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); } break; } case FOURCC('t', 'e', 'n', 'c'): { *offset += chunk_size; if (chunk_size < 32) { return ERROR_MALFORMED; } char buf[4]; memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { return ERROR_IO; } uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); if (defaultAlgorithmId > 1) { return ERROR_MALFORMED; } memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { return ERROR_IO; } uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || (defaultAlgorithmId != 0 && defaultIVSize == 0)) { return ERROR_MALFORMED; } else if (defaultIVSize != 0 && defaultIVSize != 8 && defaultIVSize != 16) { return ERROR_MALFORMED; } uint8_t defaultKeyId[16]; if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); break; } case FOURCC('t', 'k', 'h', 'd'): { *offset += chunk_size; status_t err; if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { return err; } break; } case FOURCC('p', 's', 's', 'h'): { *offset += chunk_size; PsshInfo pssh; if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { return ERROR_IO; } uint32_t psshdatalen = 0; if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { return ERROR_IO; } pssh.datalen = ntohl(psshdatalen); ALOGV("pssh data size: %d", pssh.datalen); if (chunk_size < 20 || pssh.datalen > chunk_size - 20) { return ERROR_MALFORMED; } pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; if (pssh.data == NULL) { return ERROR_MALFORMED; } ALOGV("allocated pssh @ %p", pssh.data); ssize_t requested = (ssize_t) pssh.datalen; if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { delete[] pssh.data; return ERROR_IO; } mPssh.push_back(pssh); break; } case FOURCC('m', 'd', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 4 || mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t version; if (mDataSource->readAt( data_offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } off64_t timescale_offset; if (version == 1) { timescale_offset = data_offset + 4 + 16; } else if (version == 0) { timescale_offset = data_offset + 4 + 8; } else { return ERROR_IO; } uint32_t timescale; if (mDataSource->readAt( timescale_offset, &timescale, sizeof(timescale)) < (ssize_t)sizeof(timescale)) { return ERROR_IO; } if (!timescale) { ALOGE("timescale should not be ZERO."); return ERROR_MALFORMED; } mLastTrack->timescale = ntohl(timescale); int64_t duration = 0; if (version == 1) { if (mDataSource->readAt( timescale_offset + 4, &duration, sizeof(duration)) < (ssize_t)sizeof(duration)) { return ERROR_IO; } if (duration != -1) { duration = ntoh64(duration); } } else { uint32_t duration32; if (mDataSource->readAt( timescale_offset + 4, &duration32, sizeof(duration32)) < (ssize_t)sizeof(duration32)) { return ERROR_IO; } if (duration32 != 0xffffffff) { duration = ntohl(duration32); } } if (duration != 0 && mLastTrack->timescale != 0) { mLastTrack->meta->setInt64( kKeyDuration, (duration * 1000000) / mLastTrack->timescale); } uint8_t lang[2]; off64_t lang_offset; if (version == 1) { lang_offset = timescale_offset + 4 + 8; } else if (version == 0) { lang_offset = timescale_offset + 4 + 4; } else { return ERROR_IO; } if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) < (ssize_t)sizeof(lang)) { return ERROR_IO; } char lang_code[4]; lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; lang_code[2] = (lang[1] & 0x1f) + 0x60; lang_code[3] = '\0'; mLastTrack->meta->setCString( kKeyMediaLanguage, lang_code); break; } case FOURCC('s', 't', 's', 'd'): { uint8_t buffer[8]; if (chunk_data_size < (off64_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 8) < 8) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } uint32_t entry_count = U32_AT(&buffer[4]); if (entry_count > 1) { const char *mime; if (mLastTrack == NULL) return ERROR_MALFORMED; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && strcasecmp(mime, "application/octet-stream")) { mLastTrack->skipTrack = true; *offset += chunk_size; break; } } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + 8; for (uint32_t i = 0; i < entry_count; ++i) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 't', 't'): { *offset += chunk_size; if (mLastTrack == NULL) return ERROR_MALFORMED; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } String8 mimeFormat((const char *)(buffer->data()), chunk_data_size); mLastTrack->meta->setCString(kKeyMIMEType, mimeFormat.string()); break; } case FOURCC('m', 'p', '4', 'a'): case FOURCC('e', 'n', 'c', 'a'): case FOURCC('s', 'a', 'm', 'r'): case FOURCC('s', 'a', 'w', 'b'): { if (mIsQT && chunk_type == FOURCC('m', 'p', '4', 'a') && depth >= 1 && mPath[depth - 1] == FOURCC('w', 'a', 'v', 'e')) { *offset += chunk_size; break; } uint8_t buffer[8 + 20]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index __unused = U16_AT(&buffer[6]); uint16_t version = U16_AT(&buffer[8]); uint32_t num_channels = U16_AT(&buffer[16]); uint16_t sample_size = U16_AT(&buffer[18]); uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; if (mLastTrack == NULL) return ERROR_MALFORMED; off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); if (mIsQT && chunk_type == FOURCC('m', 'p', '4', 'a')) { if (version == 1) { if (mDataSource->readAt(*offset, buffer, 16) < 16) { return ERROR_IO; } #if 0 U32_AT(buffer); // samples per packet U32_AT(&buffer[4]); // bytes per packet U32_AT(&buffer[8]); // bytes per frame U32_AT(&buffer[12]); // bytes per sample #endif *offset += 16; } else if (version == 2) { uint8_t v2buffer[36]; if (mDataSource->readAt(*offset, v2buffer, 36) < 36) { return ERROR_IO; } #if 0 U32_AT(v2buffer); // size of struct only sample_rate = (uint32_t)U64_AT(&v2buffer[4]); // audio sample rate num_channels = U32_AT(&v2buffer[12]); // num audio channels U32_AT(&v2buffer[16]); // always 0x7f000000 sample_size = (uint16_t)U32_AT(&v2buffer[20]); // const bits per channel U32_AT(&v2buffer[24]); // format specifc flags U32_AT(&v2buffer[28]); // const bytes per audio packet U32_AT(&v2buffer[32]); // const LPCM frames per audio packet #endif *offset += 36; } } if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); } ALOGV("*** coding='%s' %d channels, size %d, rate %d\n", chunk, num_channels, sample_size, sample_rate); mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'v'): case FOURCC('e', 'n', 'c', 'v'): case FOURCC('s', '2', '6', '3'): case FOURCC('H', '2', '6', '3'): case FOURCC('h', '2', '6', '3'): case FOURCC('a', 'v', 'c', '1'): case FOURCC('h', 'v', 'c', '1'): case FOURCC('h', 'e', 'v', '1'): { uint8_t buffer[78]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index __unused = U16_AT(&buffer[6]); uint16_t width = U16_AT(&buffer[6 + 18]); uint16_t height = U16_AT(&buffer[6 + 20]); if (width == 0) width = 352; if (height == 0) height = 288; if (mLastTrack == NULL) return ERROR_MALFORMED; if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); } mLastTrack->meta->setInt32(kKeyWidth, width); mLastTrack->meta->setInt32(kKeyHeight, height); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('s', 't', 'c', 'o'): case FOURCC('c', 'o', '6', '4'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setChunkOffsetParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'c'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setSampleToChunkParams( data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'z'): case FOURCC('s', 't', 'z', '2'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setSampleSizeParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } size_t max_size; err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); if (err != OK) { return err; } if (max_size != 0) { if (max_size > SIZE_MAX - 10 * 2) { ALOGE("max sample size too big: %zu", max_size); return ERROR_MALFORMED; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); } else { uint32_t width, height; if (!mLastTrack->meta->findInt32(kKeyWidth, (int32_t*)&width) || !mLastTrack->meta->findInt32(kKeyHeight,(int32_t*) &height)) { ALOGE("No width or height, assuming worst case 1080p"); width = 1920; height = 1080; } else { if (width > 32768 || height > 32768) { ALOGE("can't support %u x %u video", width, height); return ERROR_MALFORMED; } } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) || !strcmp(mime, MEDIA_MIMETYPE_VIDEO_HEVC)) { max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; } else { max_size = width * height * 3 / 2; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp("video/", mime, 6)) { size_t nSamples = mLastTrack->sampleTable->countSamples(); if (nSamples == 0) { int32_t trackId; if (mLastTrack->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(i); if (t->track_ID == (uint32_t) trackId) { if (t->default_sample_duration > 0) { int32_t frameRate = mLastTrack->timescale / t->default_sample_duration; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } break; } } } } else { int64_t durationUs; if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > 0) { int32_t frameRate = (nSamples * 1000000LL + (durationUs >> 1)) / durationUs; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } } } } break; } case FOURCC('s', 't', 't', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('c', 't', 't', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setCompositionTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setSyncSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC(0xA9, 'x', 'y', 'z'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } char buffer[18 + 8]; off64_t location_length = chunk_data_size - 5; if (location_length >= (off64_t) sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset + 4, buffer, location_length) < location_length) { return ERROR_IO; } buffer[location_length] = '\0'; mFileMetaData->setCString(kKeyLocation, buffer); break; } case FOURCC('e', 's', 'd', 's'): { *offset += chunk_size; if (chunk_data_size < 4) { return ERROR_MALFORMED; } uint8_t buffer[256]; if (chunk_data_size > (off64_t)sizeof(buffer)) { return ERROR_BUFFER_TOO_SMALL; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( &buffer[4], chunk_data_size - 4); if (err != OK) { return err; } } if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'v')) { ESDS esds(&buffer[4], chunk_data_size - 4); uint8_t objectTypeIndication; if (esds.getObjectTypeIndication(&objectTypeIndication) == OK) { if (objectTypeIndication >= 0x60 && objectTypeIndication <= 0x65) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2); } } } break; } case FOURCC('b', 't', 'r', 't'): { *offset += chunk_size; if (mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t buffer[12]; if (chunk_data_size != sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } uint32_t maxBitrate = U32_AT(&buffer[4]); uint32_t avgBitrate = U32_AT(&buffer[8]); if (maxBitrate > 0 && maxBitrate < INT32_MAX) { mLastTrack->meta->setInt32(kKeyMaxBitRate, (int32_t)maxBitrate); } if (avgBitrate > 0 && avgBitrate < INT32_MAX) { mLastTrack->meta->setInt32(kKeyBitRate, (int32_t)avgBitrate); } break; } case FOURCC('a', 'v', 'c', 'C'): { *offset += chunk_size; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); break; } case FOURCC('h', 'v', 'c', 'C'): { sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); *offset += chunk_size; break; } case FOURCC('d', '2', '6', '3'): { *offset += chunk_size; /* * d263 contains a fixed 7 bytes part: * vendor - 4 bytes * version - 1 byte * level - 1 byte * profile - 1 byte * optionally, "d263" box itself may contain a 16-byte * bit rate box (bitr) * average bit rate - 4 bytes * max bit rate - 4 bytes */ char buffer[23]; if (chunk_data_size != 7 && chunk_data_size != 23) { ALOGE("Incorrect D263 box size %lld", (long long)chunk_data_size); return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); break; } case FOURCC('m', 'e', 't', 'a'): { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; bool isParsingMetaKeys = underQTMetaPath(mPath, 2); if (!isParsingMetaKeys) { uint8_t buffer[4]; if (chunk_data_size < (off64_t)sizeof(buffer)) { *offset = stop_offset; return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 4) < 4) { *offset = stop_offset; return ERROR_IO; } if (U32_AT(buffer) != 0) { *offset = stop_offset; return OK; } *offset += sizeof(buffer); } while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 'a', 'n'): case FOURCC('n', 'a', 'm', 'e'): case FOURCC('d', 'a', 't', 'a'): { *offset += chunk_size; if (mPath.size() == 6 && underMetaDataPath(mPath)) { status_t err = parseITunesMetaData(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('m', 'v', 'h', 'd'): { *offset += chunk_size; if (depth != 1) { ALOGE("mvhd: depth %d", depth); return ERROR_MALFORMED; } if (chunk_data_size < 32) { return ERROR_MALFORMED; } uint8_t header[32]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } uint64_t creationTime; uint64_t duration = 0; if (header[0] == 1) { creationTime = U64_AT(&header[4]); mHeaderTimescale = U32_AT(&header[20]); duration = U64_AT(&header[24]); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (header[0] != 0) { return ERROR_MALFORMED; } else { creationTime = U32_AT(&header[4]); mHeaderTimescale = U32_AT(&header[12]); uint32_t d32 = U32_AT(&header[16]); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } if (duration != 0 && mHeaderTimescale != 0 && duration < UINT64_MAX / 1000000) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } String8 s; if (convertTimeToDate(creationTime, &s)) { mFileMetaData->setCString(kKeyDate, s.string()); } break; } case FOURCC('m', 'e', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t flags[4]; if (mDataSource->readAt( data_offset, flags, sizeof(flags)) < (ssize_t)sizeof(flags)) { return ERROR_IO; } uint64_t duration = 0; if (flags[0] == 1) { if (chunk_data_size < 12) { return ERROR_MALFORMED; } mDataSource->getUInt64(data_offset + 4, &duration); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (flags[0] == 0) { uint32_t d32; mDataSource->getUInt32(data_offset + 4, &d32); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } else { return ERROR_MALFORMED; } if (duration != 0 && mHeaderTimescale != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } break; } case FOURCC('m', 'd', 'a', 't'): { ALOGV("mdat chunk, drm: %d", mIsDrm); mMdatFound = true; if (!mIsDrm) { *offset += chunk_size; break; } if (chunk_size < 8) { return ERROR_MALFORMED; } return parseDrmSINF(offset, data_offset); } case FOURCC('h', 'd', 'l', 'r'): { *offset += chunk_size; if (underQTMetaPath(mPath, 3)) { break; } uint32_t buffer; if (mDataSource->readAt( data_offset + 8, &buffer, 4) < 4) { return ERROR_IO; } uint32_t type = ntohl(buffer); if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { if (mLastTrack != NULL) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); } } break; } case FOURCC('k', 'e', 'y', 's'): { *offset += chunk_size; if (underQTMetaPath(mPath, 3)) { status_t err = parseQTMetaKey(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('t', 'r', 'e', 'x'): { *offset += chunk_size; if (chunk_data_size < 24) { return ERROR_IO; } Trex trex; if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { return ERROR_IO; } mTrex.add(trex); break; } case FOURCC('t', 'x', '3', 'g'): { if (mLastTrack == NULL) return ERROR_MALFORMED; uint32_t type; const void *data; size_t size = 0; if (!mLastTrack->meta->findData( kKeyTextFormatData, &type, &data, &size)) { size = 0; } if ((chunk_size > SIZE_MAX) || (SIZE_MAX - chunk_size <= size)) { return ERROR_MALFORMED; } uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size]; if (buffer == NULL) { return ERROR_MALFORMED; } if (size > 0) { memcpy(buffer, data, size); } if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) < chunk_size) { delete[] buffer; buffer = NULL; *offset += chunk_size; return ERROR_IO; } mLastTrack->meta->setData( kKeyTextFormatData, 0, buffer, size + chunk_size); delete[] buffer; *offset += chunk_size; break; } case FOURCC('c', 'o', 'v', 'r'): { *offset += chunk_size; if (mFileMetaData != NULL) { ALOGV("chunk_data_size = %" PRId64 " and data_offset = %" PRId64, chunk_data_size, data_offset); if (chunk_data_size < 0 || static_cast<uint64_t>(chunk_data_size) >= SIZE_MAX - 1) { return ERROR_MALFORMED; } sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { return ERROR_IO; } const int kSkipBytesOfDataBox = 16; if (chunk_data_size <= kSkipBytesOfDataBox) { return ERROR_MALFORMED; } mFileMetaData->setData( kKeyAlbumArt, MetaData::TYPE_NONE, buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); } break; } case FOURCC('c', 'o', 'l', 'r'): { *offset += chunk_size; if (depth >= 2 && mPath[depth - 2] == FOURCC('s', 't', 's', 'd')) { status_t err = parseColorInfo(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('t', 'i', 't', 'l'): case FOURCC('p', 'e', 'r', 'f'): case FOURCC('a', 'u', 't', 'h'): case FOURCC('g', 'n', 'r', 'e'): case FOURCC('a', 'l', 'b', 'm'): case FOURCC('y', 'r', 'r', 'c'): { *offset += chunk_size; status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); if (err != OK) { return err; } break; } case FOURCC('I', 'D', '3', '2'): { *offset += chunk_size; if (chunk_data_size < 6) { return ERROR_MALFORMED; } parseID3v2MetaData(data_offset + 6); break; } case FOURCC('-', '-', '-', '-'): { mLastCommentMean.clear(); mLastCommentName.clear(); mLastCommentData.clear(); *offset += chunk_size; break; } case FOURCC('s', 'i', 'd', 'x'): { status_t err = parseSegmentIndex(data_offset, chunk_data_size); if (err != OK) { return err; } *offset += chunk_size; return UNKNOWN_ERROR; // stop parsing after sidx } case FOURCC('a', 'c', '-', '3'): { *offset += chunk_size; return parseAC3SampleEntry(data_offset); } case FOURCC('f', 't', 'y', 'p'): { if (chunk_data_size < 8 || depth != 0) { return ERROR_MALFORMED; } off64_t stop_offset = *offset + chunk_size; uint32_t numCompatibleBrands = (chunk_data_size - 8) / 4; for (size_t i = 0; i < numCompatibleBrands + 2; ++i) { if (i == 1) { continue; } uint32_t brand; if (mDataSource->readAt(data_offset + 4 * i, &brand, 4) < 4) { return ERROR_MALFORMED; } brand = ntohl(brand); if (brand == FOURCC('q', 't', ' ', ' ')) { mIsQT = true; break; } } *offset = stop_offset; break; } default: { if (underQTMetaPath(mPath, 3)) { status_t err = parseQTMetaVal(chunk_type, data_offset, chunk_data_size); if (err != OK) { return err; } } *offset += chunk_size; break; } } return OK; }
1,797
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.
Code: void ShellWindow::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const extensions::Extension* unloaded_extension = content::Details<extensions::UnloadedExtensionInfo>( details)->extension; if (extension_ == unloaded_extension) Close(); break; } case content::NOTIFICATION_APP_TERMINATING: Close(); break; default: NOTREACHED() << "Received unexpected notification"; } } Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time. When you first create a window with chrome.appWindow.create(), it won't have loaded any resources. So, at create time, you are guaranteed that: child_window.location.href == 'about:blank' child_window.document.documentElement.outerHTML == '<html><head></head><body></body></html>' This is in line with the behaviour of window.open(). BUG=131735 TEST=browser_tests:PlatformAppBrowserTest.WindowsApi Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072 Review URL: https://chromiumcodereview.appspot.com/10644006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ShellWindow::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED: { // TODO(jeremya): once http://crbug.com/123007 is fixed, we'll no longer // need to suspend resource requests here (the call in the constructor // should be enough). content::Details<std::pair<RenderViewHost*, RenderViewHost*> > host_details(details); if (host_details->first) SuspendRenderViewHost(host_details->second); break; } case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const extensions::Extension* unloaded_extension = content::Details<extensions::UnloadedExtensionInfo>( details)->extension; if (extension_ == unloaded_extension) Close(); break; } case content::NOTIFICATION_APP_TERMINATING: Close(); break; default: NOTREACHED() << "Received unexpected notification"; } }
6,507
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.
Code: void StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!process_) return callback->sendFailure(Response::InternalError()); StoragePartition* partition = process_->GetStoragePartition(); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } partition->ClearData(remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, std::move(callback))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!storage_partition_) return callback->sendFailure(Response::InternalError()); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } storage_partition_->ClearData( remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, std::move(callback))); }
23,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.
Code: int ar6000_create_ap_interface(struct ar6_softc *ar, char *ap_ifname) { struct net_device *dev; struct ar_virtual_interface *arApDev; dev = alloc_etherdev(sizeof(struct ar_virtual_interface)); if (dev == NULL) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: can't alloc etherdev\n")); return A_ERROR; } ether_setup(dev); init_netdev(dev, ap_ifname); if (register_netdev(dev)) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: register_netdev failed\n")); return A_ERROR; } arApDev = netdev_priv(dev); arApDev->arDev = ar; arApDev->arNetDev = dev; arApDev->arStaNetDev = ar->arNetDev; ar->arApDev = arApDev; arApNetDev = dev; /* Copy the MAC address */ memcpy(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN); return 0; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <nhorman@tuxdriver.com> CC: Karsten Keil <isdn@linux-pingi.de> CC: "David S. Miller" <davem@davemloft.net> CC: Jay Vosburgh <fubar@us.ibm.com> CC: Andy Gospodarek <andy@greyhouse.net> CC: Patrick McHardy <kaber@trash.net> CC: Krzysztof Halasa <khc@pm.waw.pl> CC: "John W. Linville" <linville@tuxdriver.com> CC: Greg Kroah-Hartman <gregkh@suse.de> CC: Marcel Holtmann <marcel@holtmann.org> CC: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-264
int ar6000_create_ap_interface(struct ar6_softc *ar, char *ap_ifname) { struct net_device *dev; struct ar_virtual_interface *arApDev; dev = alloc_etherdev(sizeof(struct ar_virtual_interface)); if (dev == NULL) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: can't alloc etherdev\n")); return A_ERROR; } ether_setup(dev); init_netdev(dev, ap_ifname); dev->priv_flags &= ~IFF_TX_SKB_SHARING; if (register_netdev(dev)) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: register_netdev failed\n")); return A_ERROR; } arApDev = netdev_priv(dev); arApDev->arDev = ar; arApDev->arNetDev = dev; arApDev->arStaNetDev = ar->arNetDev; ar->arApDev = arApDev; arApNetDev = dev; /* Copy the MAC address */ memcpy(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN); return 0; }
5,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.
Code: WebRunnerContentBrowserClient::CreateBrowserMainParts( const content::MainFunctionParams& parameters) { DCHECK(context_channel_); return new WebRunnerBrowserMainParts(std::move(context_channel_)); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <kmarshall@chromium.org> Reviewed-by: Wez <wez@chromium.org> Reviewed-by: Fabrice de Gans-Riberi <fdegans@chromium.org> Reviewed-by: Scott Violet <sky@chromium.org> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
WebRunnerContentBrowserClient::CreateBrowserMainParts( const content::MainFunctionParams& parameters) { DCHECK(context_channel_); main_parts_ = new WebRunnerBrowserMainParts(std::move(context_channel_)); return main_parts_; }
15,434
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.
Code: png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { int copy = output_size - count; if (avail < copy) copy = avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = "Buffer error in compressed datastream in %s chunk"; break; case Z_DATA_ERROR: msg = "Data error in compressed datastream in %s chunk"; break; default: msg = "Incomplete compressed datastream in %s chunk"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = "Damaged compressed datastream in chunk other than IDAT"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } } Commit Message: Pull follow-up tweak from upstream. BUG=116162 Review URL: http://codereview.chromium.org/9546033 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125311 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { png_size_t copy = output_size - count; if ((png_size_t) avail < copy) copy = (png_size_t) avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = "Buffer error in compressed datastream in %s chunk"; break; case Z_DATA_ERROR: msg = "Data error in compressed datastream in %s chunk"; break; default: msg = "Incomplete compressed datastream in %s chunk"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = "Damaged compressed datastream in chunk other than IDAT"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } }
24,755
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.
Code: static int php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; php_stream *file; size_t memsize; char *membuf; off_t pos; assert(ts != NULL); if (!ts->innerstream) { return FAILURE; } if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) { return php_stream_cast(ts->innerstream, castas, ret, 0); } /* we are still using a memory based backing. If they are if we can be * a FILE*, say yes because we can perform the conversion. * If they actually want to perform the conversion, we need to switch * the memory stream to a tmpfile stream */ if (ret == NULL && castas == PHP_STREAM_AS_STDIO) { return SUCCESS; } /* say "no" to other stream forms */ if (ret == NULL) { return FAILURE; } /* perform the conversion and then pass the request on to the innerstream */ membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize); file = php_stream_fopen_tmpfile(); php_stream_write(file, membuf, memsize); pos = php_stream_tell(ts->innerstream); php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE); ts->innerstream = file; php_stream_encloses(stream, ts->innerstream); php_stream_seek(ts->innerstream, pos, SEEK_SET); return php_stream_cast(ts->innerstream, castas, ret, 1); } Commit Message: CWE ID: CWE-20
static int php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; php_stream *file; size_t memsize; char *membuf; off_t pos; assert(ts != NULL); if (!ts->innerstream) { return FAILURE; } if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) { return php_stream_cast(ts->innerstream, castas, ret, 0); } /* we are still using a memory based backing. If they are if we can be * a FILE*, say yes because we can perform the conversion. * If they actually want to perform the conversion, we need to switch * the memory stream to a tmpfile stream */ if (ret == NULL && castas == PHP_STREAM_AS_STDIO) { return SUCCESS; } /* say "no" to other stream forms */ if (ret == NULL) { return FAILURE; } /* perform the conversion and then pass the request on to the innerstream */ membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize); file = php_stream_fopen_tmpfile(); php_stream_write(file, membuf, memsize); pos = php_stream_tell(ts->innerstream); php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE); ts->innerstream = file; php_stream_encloses(stream, ts->innerstream); php_stream_seek(ts->innerstream, pos, SEEK_SET); return php_stream_cast(ts->innerstream, castas, ret, 1); }
597
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.
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; }
9,842
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.
Code: status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsSecure && !audio) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119
status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; }
8,218
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.
Code: static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof) { char *ksep, *vsep, *val; size_t klen, vlen; size_t new_vlen; if (var->ptr >= var->end) { return 0; } vsep = memchr(var->ptr, '&', var->end - var->ptr); if (!vsep) { if (!eof) { return 0; } else { vsep = var->end; } } ksep = memchr(var->ptr, '=', vsep - var->ptr); if (ksep) { *ksep = '\0'; /* "foo=bar&" or "foo=&" */ klen = ksep - var->ptr; vlen = vsep - ++ksep; } else { ksep = ""; /* "foo&" */ klen = vsep - var->ptr; vlen = 0; } php_url_decode(var->ptr, klen); val = estrndup(ksep, vlen); if (vlen) { vlen = php_url_decode(val, vlen); } if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) { php_register_variable_safe(var->ptr, val, new_vlen, arr); } efree(val); var->ptr = vsep + (vsep != var->end); return 1; } Commit Message: Fix bug #73807 CWE ID: CWE-400
static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof) { char *start, *ksep, *vsep, *val; size_t klen, vlen; size_t new_vlen; if (var->ptr >= var->end) { return 0; } start = var->ptr + var->already_scanned; vsep = memchr(start, '&', var->end - start); if (!vsep) { if (!eof) { var->already_scanned = var->end - var->ptr; return 0; } else { vsep = var->end; } } ksep = memchr(var->ptr, '=', vsep - var->ptr); if (ksep) { *ksep = '\0'; /* "foo=bar&" or "foo=&" */ klen = ksep - var->ptr; vlen = vsep - ++ksep; } else { ksep = ""; /* "foo&" */ klen = vsep - var->ptr; vlen = 0; } php_url_decode(var->ptr, klen); val = estrndup(ksep, vlen); if (vlen) { vlen = php_url_decode(val, vlen); } if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) { php_register_variable_safe(var->ptr, val, new_vlen, arr); } efree(val); var->ptr = vsep + (vsep != var->end); var->already_scanned = 0; return 1; }
22,547
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.
Code: void QuicClientPromisedInfo::OnPromiseHeaders(const SpdyHeaderBlock& headers) { SpdyHeaderBlock::const_iterator it = headers.find(kHttp2MethodHeader); DCHECK(it != headers.end()); if (!(it->second == "GET" || it->second == "HEAD")) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid method " << it->second; Reset(QUIC_INVALID_PROMISE_METHOD); return; } if (!SpdyUtils::UrlIsValid(headers)) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid URL " << url_; Reset(QUIC_INVALID_PROMISE_URL); return; } if (!session_->IsAuthorized(SpdyUtils::GetHostNameFromHeaderBlock(headers))) { Reset(QUIC_UNAUTHORIZED_PROMISE_URL); return; } request_headers_.reset(new SpdyHeaderBlock(headers.Clone())); } Commit Message: Fix Stack Buffer Overflow in QuicClientPromisedInfo::OnPromiseHeaders BUG=777728 Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I6a80db88aafdf20c7abd3847404b818565681310 Reviewed-on: https://chromium-review.googlesource.com/748425 Reviewed-by: Zhongyi Shi <zhongyi@chromium.org> Commit-Queue: Ryan Hamilton <rch@chromium.org> Cr-Commit-Position: refs/heads/master@{#513105} CWE ID: CWE-119
void QuicClientPromisedInfo::OnPromiseHeaders(const SpdyHeaderBlock& headers) { SpdyHeaderBlock::const_iterator it = headers.find(kHttp2MethodHeader); if (it == headers.end()) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has no method"; Reset(QUIC_INVALID_PROMISE_METHOD); return; } if (!(it->second == "GET" || it->second == "HEAD")) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid method " << it->second; Reset(QUIC_INVALID_PROMISE_METHOD); return; } if (!SpdyUtils::UrlIsValid(headers)) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid URL " << url_; Reset(QUIC_INVALID_PROMISE_URL); return; } if (!session_->IsAuthorized(SpdyUtils::GetHostNameFromHeaderBlock(headers))) { Reset(QUIC_UNAUTHORIZED_PROMISE_URL); return; } request_headers_.reset(new SpdyHeaderBlock(headers.Clone())); }
27,144
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.
Code: void CmdBufferImageTransportFactory::DestroySharedSurfaceHandle( const gfx::GLSurfaceHandle& handle) { if (!context_->makeContextCurrent()) { NOTREACHED() << "Failed to make shared graphics context current"; return; } context_->deleteTexture(handle.parent_texture_id[0]); context_->deleteTexture(handle.parent_texture_id[1]); context_->finish(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void CmdBufferImageTransportFactory::DestroySharedSurfaceHandle( const gfx::GLSurfaceHandle& handle) { if (!context_->makeContextCurrent()) { NOTREACHED() << "Failed to make shared graphics context current"; return; } }
24,751
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.
Code: int main(int argc, char **argv) { volatile int summary = 1; /* Print the error summary at the end */ volatile int memstats = 0; /* Print memory statistics at the end */ /* Create the given output file on success: */ PNG_CONST char *volatile touch = NULL; /* This is an array of standard gamma values (believe it or not I've seen * every one of these mentioned somewhere.) * * In the following list the most useful values are first! */ static double gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9}; /* This records the command and arguments: */ size_t cp = 0; char command[1024]; anon_context(&pm.this); /* Add appropriate signal handlers, just the ANSI specified ones: */ signal(SIGABRT, signal_handler); signal(SIGFPE, signal_handler); signal(SIGILL, signal_handler); signal(SIGINT, signal_handler); signal(SIGSEGV, signal_handler); signal(SIGTERM, signal_handler); #ifdef HAVE_FEENABLEEXCEPT /* Only required to enable FP exceptions on platforms where they start off * disabled; this is not necessary but if it is not done pngvalid will likely * end up ignoring FP conditions that other platforms fault. */ feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif modifier_init(&pm); /* Preallocate the image buffer, because we know how big it needs to be, * note that, for testing purposes, it is deliberately mis-aligned by tag * bytes either side. All rows have an additional five bytes of padding for * overwrite checking. */ store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX); /* Don't give argv[0], it's normally some horrible libtool string: */ cp = safecat(command, sizeof command, cp, "pngvalid"); /* Default to error on warning: */ pm.this.treat_warnings_as_errors = 1; /* Default assume_16_bit_calculations appropriately; this tells the checking * code that 16-bit arithmetic is used for 8-bit samples when it would make a * difference. */ pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700; /* Currently 16 bit expansion happens at the end of the pipeline, so the * calculations are done in the input bit depth not the output. * * TODO: fix this */ pm.calculations_use_input_precision = 1U; /* Store the test gammas */ pm.gammas = gammas; pm.ngammas = (sizeof gammas) / (sizeof gammas[0]); pm.ngamma_tests = 0; /* default to off */ /* And the test encodings */ pm.encodings = test_encodings; pm.nencodings = (sizeof test_encodings) / (sizeof test_encodings[0]); pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */ /* The following allows results to pass if they correspond to anything in the * transformed range [input-.5,input+.5]; this is is required because of the * way libpng treates the 16_TO_8 flag when building the gamma tables in * releases up to 1.6.0. * * TODO: review this */ pm.use_input_precision_16to8 = 1U; pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */ /* Some default values (set the behavior for 'make check' here). * These values simply control the maximum error permitted in the gamma * transformations. The practial limits for human perception are described * below (the setting for maxpc16), however for 8 bit encodings it isn't * possible to meet the accepted capabilities of human vision - i.e. 8 bit * images can never be good enough, regardless of encoding. */ pm.maxout8 = .1; /* Arithmetic error in *encoded* value */ pm.maxabs8 = .00005; /* 1/20000 */ pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */ pm.maxpc8 = .499; /* I.e., .499% fractional error */ pm.maxout16 = .499; /* Error in *encoded* value */ pm.maxabs16 = .00005;/* 1/20000 */ pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */ pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1); /* NOTE: this is a reasonable perceptual limit. We assume that humans can * perceive light level differences of 1% over a 100:1 range, so we need to * maintain 1 in 10000 accuracy (in linear light space), which is what the * following guarantees. It also allows significantly higher errors at * higher 16 bit values, which is important for performance. The actual * maximum 16 bit error is about +/-1.9 in the fixed point implementation but * this is only allowed for values >38149 by the following: */ pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */ /* Now parse the command line options. */ while (--argc >= 1) { int catmore = 0; /* Set if the argument has an argument. */ /* Record each argument for posterity: */ cp = safecat(command, sizeof command, cp, " "); cp = safecat(command, sizeof command, cp, *++argv); if (strcmp(*argv, "-v") == 0) pm.this.verbose = 1; else if (strcmp(*argv, "-l") == 0) pm.log = 1; else if (strcmp(*argv, "-q") == 0) summary = pm.this.verbose = pm.log = 0; else if (strcmp(*argv, "-w") == 0) pm.this.treat_warnings_as_errors = 0; else if (strcmp(*argv, "--speed") == 0) pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0, summary = 0; else if (strcmp(*argv, "--memory") == 0) memstats = 1; else if (strcmp(*argv, "--size") == 0) pm.test_size = 1; else if (strcmp(*argv, "--nosize") == 0) pm.test_size = 0; else if (strcmp(*argv, "--standard") == 0) pm.test_standard = 1; else if (strcmp(*argv, "--nostandard") == 0) pm.test_standard = 0; else if (strcmp(*argv, "--transform") == 0) pm.test_transform = 1; else if (strcmp(*argv, "--notransform") == 0) pm.test_transform = 0; #ifdef PNG_READ_TRANSFORMS_SUPPORTED else if (strncmp(*argv, "--transform-disable=", sizeof "--transform-disable") == 0) { pm.test_transform = 1; transform_disable(*argv + sizeof "--transform-disable"); } else if (strncmp(*argv, "--transform-enable=", sizeof "--transform-enable") == 0) { pm.test_transform = 1; transform_enable(*argv + sizeof "--transform-enable"); } #endif /* PNG_READ_TRANSFORMS_SUPPORTED */ else if (strcmp(*argv, "--gamma") == 0) { /* Just do two gamma tests here (2.2 and linear) for speed: */ pm.ngamma_tests = 2U; pm.test_gamma_threshold = 1; pm.test_gamma_transform = 1; pm.test_gamma_sbit = 1; pm.test_gamma_scale16 = 1; pm.test_gamma_background = 1; pm.test_gamma_alpha_mode = 1; } else if (strcmp(*argv, "--nogamma") == 0) pm.ngamma_tests = 0; else if (strcmp(*argv, "--gamma-threshold") == 0) pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1; else if (strcmp(*argv, "--nogamma-threshold") == 0) pm.test_gamma_threshold = 0; else if (strcmp(*argv, "--gamma-transform") == 0) pm.ngamma_tests = 2U, pm.test_gamma_transform = 1; else if (strcmp(*argv, "--nogamma-transform") == 0) pm.test_gamma_transform = 0; else if (strcmp(*argv, "--gamma-sbit") == 0) pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1; else if (strcmp(*argv, "--nogamma-sbit") == 0) pm.test_gamma_sbit = 0; else if (strcmp(*argv, "--gamma-16-to-8") == 0) pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1; else if (strcmp(*argv, "--nogamma-16-to-8") == 0) pm.test_gamma_scale16 = 0; else if (strcmp(*argv, "--gamma-background") == 0) pm.ngamma_tests = 2U, pm.test_gamma_background = 1; else if (strcmp(*argv, "--nogamma-background") == 0) pm.test_gamma_background = 0; else if (strcmp(*argv, "--gamma-alpha-mode") == 0) pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1; else if (strcmp(*argv, "--nogamma-alpha-mode") == 0) pm.test_gamma_alpha_mode = 0; else if (strcmp(*argv, "--expand16") == 0) pm.test_gamma_expand16 = 1; else if (strcmp(*argv, "--noexpand16") == 0) pm.test_gamma_expand16 = 0; else if (strcmp(*argv, "--more-gammas") == 0) pm.ngamma_tests = 3U; else if (strcmp(*argv, "--all-gammas") == 0) pm.ngamma_tests = pm.ngammas; else if (strcmp(*argv, "--progressive-read") == 0) pm.this.progressive = 1; else if (strcmp(*argv, "--use-update-info") == 0) ++pm.use_update_info; /* Can call multiple times */ else if (strcmp(*argv, "--interlace") == 0) { # ifdef PNG_WRITE_INTERLACING_SUPPORTED pm.interlace_type = PNG_INTERLACE_ADAM7; # else fprintf(stderr, "pngvalid: no write interlace support\n"); return SKIP; # endif } else if (strcmp(*argv, "--use-input-precision") == 0) pm.use_input_precision = 1U; else if (strcmp(*argv, "--use-calculation-precision") == 0) pm.use_input_precision = 0; else if (strcmp(*argv, "--calculations-use-input-precision") == 0) pm.calculations_use_input_precision = 1U; else if (strcmp(*argv, "--assume-16-bit-calculations") == 0) pm.assume_16_bit_calculations = 1U; else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0) pm.calculations_use_input_precision = pm.assume_16_bit_calculations = 0; else if (strcmp(*argv, "--exhaustive") == 0) pm.test_exhaustive = 1; else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0) --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1; else if (argc > 1 && strcmp(*argv, "--touch") == 0) --argc, touch = *++argv, catmore = 1; else if (argc > 1 && strncmp(*argv, "--max", 5) == 0) { --argc; if (strcmp(5+*argv, "abs8") == 0) pm.maxabs8 = atof(*++argv); else if (strcmp(5+*argv, "abs16") == 0) pm.maxabs16 = atof(*++argv); else if (strcmp(5+*argv, "calc8") == 0) pm.maxcalc8 = atof(*++argv); else if (strcmp(5+*argv, "calc16") == 0) pm.maxcalc16 = atof(*++argv); else if (strcmp(5+*argv, "out8") == 0) pm.maxout8 = atof(*++argv); else if (strcmp(5+*argv, "out16") == 0) pm.maxout16 = atof(*++argv); else if (strcmp(5+*argv, "pc8") == 0) pm.maxpc8 = atof(*++argv); else if (strcmp(5+*argv, "pc16") == 0) pm.maxpc16 = atof(*++argv); else { fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv); exit(99); } catmore = 1; } else if (strcmp(*argv, "--log8") == 0) --argc, pm.log8 = atof(*++argv), catmore = 1; else if (strcmp(*argv, "--log16") == 0) --argc, pm.log16 = atof(*++argv), catmore = 1; #ifdef PNG_SET_OPTION_SUPPORTED else if (strncmp(*argv, "--option=", 9) == 0) { /* Syntax of the argument is <option>:{on|off} */ const char *arg = 9+*argv; unsigned char option=0, setting=0; #ifdef PNG_ARM_NEON_API_SUPPORTED if (strncmp(arg, "arm-neon:", 9) == 0) option = PNG_ARM_NEON, arg += 9; else #endif #ifdef PNG_MAXIMUM_INFLATE_WINDOW if (strncmp(arg, "max-inflate-window:", 19) == 0) option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19; else #endif { fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg); exit(99); } if (strcmp(arg, "off") == 0) setting = PNG_OPTION_OFF; else if (strcmp(arg, "on") == 0) setting = PNG_OPTION_ON; else { fprintf(stderr, "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n", *argv, arg); exit(99); } pm.this.options[pm.this.noptions].option = option; pm.this.options[pm.this.noptions++].setting = setting; } #endif /* PNG_SET_OPTION_SUPPORTED */ else { fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv); exit(99); } if (catmore) /* consumed an extra *argv */ { cp = safecat(command, sizeof command, cp, " "); cp = safecat(command, sizeof command, cp, *argv); } } /* If pngvalid is run with no arguments default to a reasonable set of the * tests. */ if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 && pm.ngamma_tests == 0) { /* Make this do all the tests done in the test shell scripts with the same * parameters, where possible. The limitation is that all the progressive * read and interlace stuff has to be done in separate runs, so only the * basic 'standard' and 'size' tests are done. */ pm.test_standard = 1; pm.test_size = 1; pm.test_transform = 1; pm.ngamma_tests = 2U; } if (pm.ngamma_tests > 0 && pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 && pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 && pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0) { pm.test_gamma_threshold = 1; pm.test_gamma_transform = 1; pm.test_gamma_sbit = 1; pm.test_gamma_scale16 = 1; pm.test_gamma_background = 1; pm.test_gamma_alpha_mode = 1; } else if (pm.ngamma_tests == 0) { /* Nothing to test so turn everything off: */ pm.test_gamma_threshold = 0; pm.test_gamma_transform = 0; pm.test_gamma_sbit = 0; pm.test_gamma_scale16 = 0; pm.test_gamma_background = 0; pm.test_gamma_alpha_mode = 0; } Try { /* Make useful base images */ make_transform_images(&pm.this); /* Perform the standard and gamma tests. */ if (pm.test_standard) { perform_interlace_macro_validation(); perform_formatting_test(&pm.this); # ifdef PNG_READ_SUPPORTED perform_standard_test(&pm); # endif perform_error_test(&pm); } /* Various oddly sized images: */ if (pm.test_size) { make_size_images(&pm.this); # ifdef PNG_READ_SUPPORTED perform_size_test(&pm); # endif } #ifdef PNG_READ_TRANSFORMS_SUPPORTED /* Combinatorial transforms: */ if (pm.test_transform) perform_transform_test(&pm); #endif /* PNG_READ_TRANSFORMS_SUPPORTED */ #ifdef PNG_READ_GAMMA_SUPPORTED if (pm.ngamma_tests > 0) perform_gamma_test(&pm, summary); #endif } Catch_anonymous { fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n"); if (!pm.this.verbose) { if (pm.this.error[0] != 0) fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error); fprintf(stderr, "pngvalid: run with -v to see what happened\n"); } exit(1); } if (summary) { printf("%s: %s (%s point arithmetic)\n", (pm.this.nerrors || (pm.this.treat_warnings_as_errors && pm.this.nwarnings)) ? "FAIL" : "PASS", command, #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500 "floating" #else "fixed" #endif ); } if (memstats) { printf("Allocated memory statistics (in bytes):\n" "\tread %lu maximum single, %lu peak, %lu total\n" "\twrite %lu maximum single, %lu peak, %lu total\n", (unsigned long)pm.this.read_memory_pool.max_max, (unsigned long)pm.this.read_memory_pool.max_limit, (unsigned long)pm.this.read_memory_pool.max_total, (unsigned long)pm.this.write_memory_pool.max_max, (unsigned long)pm.this.write_memory_pool.max_limit, (unsigned long)pm.this.write_memory_pool.max_total); } /* Do this here to provoke memory corruption errors in memory not directly * allocated by libpng - not a complete test, but better than nothing. */ store_delete(&pm.this); /* Error exit if there are any errors, and maybe if there are any * warnings. */ if (pm.this.nerrors || (pm.this.treat_warnings_as_errors && pm.this.nwarnings)) { if (!pm.this.verbose) fprintf(stderr, "pngvalid: %s\n", pm.this.error); fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors, pm.this.nwarnings); exit(1); } /* Success case. */ if (touch != NULL) { FILE *fsuccess = fopen(touch, "wt"); if (fsuccess != NULL) { int error = 0; fprintf(fsuccess, "PNG validation succeeded\n"); fflush(fsuccess); error = ferror(fsuccess); if (fclose(fsuccess) || error) { fprintf(stderr, "%s: write failed\n", touch); exit(1); } } else { fprintf(stderr, "%s: open failed\n", touch); exit(1); } } /* This is required because some very minimal configurations do not use it: */ UNUSED(fail) 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) { int summary = 1; /* Print the error summary at the end */ int memstats = 0; /* Print memory statistics at the end */ /* Create the given output file on success: */ const char *touch = NULL; /* This is an array of standard gamma values (believe it or not I've seen * every one of these mentioned somewhere.) * * In the following list the most useful values are first! */ static double gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9}; /* This records the command and arguments: */ size_t cp = 0; char command[1024]; anon_context(&pm.this); gnu_volatile(summary) gnu_volatile(memstats) gnu_volatile(touch) /* Add appropriate signal handlers, just the ANSI specified ones: */ signal(SIGABRT, signal_handler); signal(SIGFPE, signal_handler); signal(SIGILL, signal_handler); signal(SIGINT, signal_handler); signal(SIGSEGV, signal_handler); signal(SIGTERM, signal_handler); #ifdef HAVE_FEENABLEEXCEPT /* Only required to enable FP exceptions on platforms where they start off * disabled; this is not necessary but if it is not done pngvalid will likely * end up ignoring FP conditions that other platforms fault. */ feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif modifier_init(&pm); /* Preallocate the image buffer, because we know how big it needs to be, * note that, for testing purposes, it is deliberately mis-aligned by tag * bytes either side. All rows have an additional five bytes of padding for * overwrite checking. */ store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX); /* Don't give argv[0], it's normally some horrible libtool string: */ cp = safecat(command, sizeof command, cp, "pngvalid"); /* Default to error on warning: */ pm.this.treat_warnings_as_errors = 1; /* Default assume_16_bit_calculations appropriately; this tells the checking * code that 16-bit arithmetic is used for 8-bit samples when it would make a * difference. */ pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700; /* Currently 16 bit expansion happens at the end of the pipeline, so the * calculations are done in the input bit depth not the output. * * TODO: fix this */ pm.calculations_use_input_precision = 1U; /* Store the test gammas */ pm.gammas = gammas; pm.ngammas = ARRAY_SIZE(gammas); pm.ngamma_tests = 0; /* default to off */ /* Low bit depth gray images don't do well in the gamma tests, until * this is fixed turn them off for some gamma cases: */ # ifdef PNG_WRITE_tRNS_SUPPORTED pm.test_tRNS = 1; # endif pm.test_lbg = PNG_LIBPNG_VER >= 10600; pm.test_lbg_gamma_threshold = 1; pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600; pm.test_lbg_gamma_sbit = 1; pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700; /* And the test encodings */ pm.encodings = test_encodings; pm.nencodings = ARRAY_SIZE(test_encodings); # if PNG_LIBPNG_VER < 10700 pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */ # else pm.sbitlow = 1U; # endif /* The following allows results to pass if they correspond to anything in the * transformed range [input-.5,input+.5]; this is is required because of the * way libpng treates the 16_TO_8 flag when building the gamma tables in * releases up to 1.6.0. * * TODO: review this */ pm.use_input_precision_16to8 = 1U; pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */ /* Some default values (set the behavior for 'make check' here). * These values simply control the maximum error permitted in the gamma * transformations. The practial limits for human perception are described * below (the setting for maxpc16), however for 8 bit encodings it isn't * possible to meet the accepted capabilities of human vision - i.e. 8 bit * images can never be good enough, regardless of encoding. */ pm.maxout8 = .1; /* Arithmetic error in *encoded* value */ pm.maxabs8 = .00005; /* 1/20000 */ pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */ pm.maxpc8 = .499; /* I.e., .499% fractional error */ pm.maxout16 = .499; /* Error in *encoded* value */ pm.maxabs16 = .00005;/* 1/20000 */ pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */ # if PNG_LIBPNG_VER < 10700 pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1); # else pm.maxcalcG = 1./((1<<16)-1); # endif /* NOTE: this is a reasonable perceptual limit. We assume that humans can * perceive light level differences of 1% over a 100:1 range, so we need to * maintain 1 in 10000 accuracy (in linear light space), which is what the * following guarantees. It also allows significantly higher errors at * higher 16 bit values, which is important for performance. The actual * maximum 16 bit error is about +/-1.9 in the fixed point implementation but * this is only allowed for values >38149 by the following: */ pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */ /* Now parse the command line options. */ while (--argc >= 1) { int catmore = 0; /* Set if the argument has an argument. */ /* Record each argument for posterity: */ cp = safecat(command, sizeof command, cp, " "); cp = safecat(command, sizeof command, cp, *++argv); if (strcmp(*argv, "-v") == 0) pm.this.verbose = 1; else if (strcmp(*argv, "-l") == 0) pm.log = 1; else if (strcmp(*argv, "-q") == 0) summary = pm.this.verbose = pm.log = 0; else if (strcmp(*argv, "-w") == 0 || strcmp(*argv, "--strict") == 0) pm.this.treat_warnings_as_errors = 0; else if (strcmp(*argv, "--speed") == 0) pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0, summary = 0; else if (strcmp(*argv, "--memory") == 0) memstats = 1; else if (strcmp(*argv, "--size") == 0) pm.test_size = 1; else if (strcmp(*argv, "--nosize") == 0) pm.test_size = 0; else if (strcmp(*argv, "--standard") == 0) pm.test_standard = 1; else if (strcmp(*argv, "--nostandard") == 0) pm.test_standard = 0; else if (strcmp(*argv, "--transform") == 0) pm.test_transform = 1; else if (strcmp(*argv, "--notransform") == 0) pm.test_transform = 0; #ifdef PNG_READ_TRANSFORMS_SUPPORTED else if (strncmp(*argv, "--transform-disable=", sizeof "--transform-disable") == 0) { pm.test_transform = 1; transform_disable(*argv + sizeof "--transform-disable"); } else if (strncmp(*argv, "--transform-enable=", sizeof "--transform-enable") == 0) { pm.test_transform = 1; transform_enable(*argv + sizeof "--transform-enable"); } #endif /* PNG_READ_TRANSFORMS_SUPPORTED */ else if (strcmp(*argv, "--gamma") == 0) { /* Just do two gamma tests here (2.2 and linear) for speed: */ pm.ngamma_tests = 2U; pm.test_gamma_threshold = 1; pm.test_gamma_transform = 1; pm.test_gamma_sbit = 1; pm.test_gamma_scale16 = 1; pm.test_gamma_background = 1; /* composition */ pm.test_gamma_alpha_mode = 1; } else if (strcmp(*argv, "--nogamma") == 0) pm.ngamma_tests = 0; else if (strcmp(*argv, "--gamma-threshold") == 0) pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1; else if (strcmp(*argv, "--nogamma-threshold") == 0) pm.test_gamma_threshold = 0; else if (strcmp(*argv, "--gamma-transform") == 0) pm.ngamma_tests = 2U, pm.test_gamma_transform = 1; else if (strcmp(*argv, "--nogamma-transform") == 0) pm.test_gamma_transform = 0; else if (strcmp(*argv, "--gamma-sbit") == 0) pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1; else if (strcmp(*argv, "--nogamma-sbit") == 0) pm.test_gamma_sbit = 0; else if (strcmp(*argv, "--gamma-16-to-8") == 0) pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1; else if (strcmp(*argv, "--nogamma-16-to-8") == 0) pm.test_gamma_scale16 = 0; else if (strcmp(*argv, "--gamma-background") == 0) pm.ngamma_tests = 2U, pm.test_gamma_background = 1; else if (strcmp(*argv, "--nogamma-background") == 0) pm.test_gamma_background = 0; else if (strcmp(*argv, "--gamma-alpha-mode") == 0) pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1; else if (strcmp(*argv, "--nogamma-alpha-mode") == 0) pm.test_gamma_alpha_mode = 0; else if (strcmp(*argv, "--expand16") == 0) pm.test_gamma_expand16 = 1; else if (strcmp(*argv, "--noexpand16") == 0) pm.test_gamma_expand16 = 0; else if (strcmp(*argv, "--low-depth-gray") == 0) pm.test_lbg = pm.test_lbg_gamma_threshold = pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit = pm.test_lbg_gamma_composition = 1; else if (strcmp(*argv, "--nolow-depth-gray") == 0) pm.test_lbg = pm.test_lbg_gamma_threshold = pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit = pm.test_lbg_gamma_composition = 0; # ifdef PNG_WRITE_tRNS_SUPPORTED else if (strcmp(*argv, "--tRNS") == 0) pm.test_tRNS = 1; # endif else if (strcmp(*argv, "--notRNS") == 0) pm.test_tRNS = 0; else if (strcmp(*argv, "--more-gammas") == 0) pm.ngamma_tests = 3U; else if (strcmp(*argv, "--all-gammas") == 0) pm.ngamma_tests = pm.ngammas; else if (strcmp(*argv, "--progressive-read") == 0) pm.this.progressive = 1; else if (strcmp(*argv, "--use-update-info") == 0) ++pm.use_update_info; /* Can call multiple times */ else if (strcmp(*argv, "--interlace") == 0) { # if CAN_WRITE_INTERLACE pm.interlace_type = PNG_INTERLACE_ADAM7; # else /* !CAN_WRITE_INTERLACE */ fprintf(stderr, "pngvalid: no write interlace support\n"); return SKIP; # endif /* !CAN_WRITE_INTERLACE */ } else if (strcmp(*argv, "--use-input-precision") == 0) pm.use_input_precision = 1U; else if (strcmp(*argv, "--use-calculation-precision") == 0) pm.use_input_precision = 0; else if (strcmp(*argv, "--calculations-use-input-precision") == 0) pm.calculations_use_input_precision = 1U; else if (strcmp(*argv, "--assume-16-bit-calculations") == 0) pm.assume_16_bit_calculations = 1U; else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0) pm.calculations_use_input_precision = pm.assume_16_bit_calculations = 0; else if (strcmp(*argv, "--exhaustive") == 0) pm.test_exhaustive = 1; else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0) --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1; else if (argc > 1 && strcmp(*argv, "--touch") == 0) --argc, touch = *++argv, catmore = 1; else if (argc > 1 && strncmp(*argv, "--max", 5) == 0) { --argc; if (strcmp(5+*argv, "abs8") == 0) pm.maxabs8 = atof(*++argv); else if (strcmp(5+*argv, "abs16") == 0) pm.maxabs16 = atof(*++argv); else if (strcmp(5+*argv, "calc8") == 0) pm.maxcalc8 = atof(*++argv); else if (strcmp(5+*argv, "calc16") == 0) pm.maxcalc16 = atof(*++argv); else if (strcmp(5+*argv, "out8") == 0) pm.maxout8 = atof(*++argv); else if (strcmp(5+*argv, "out16") == 0) pm.maxout16 = atof(*++argv); else if (strcmp(5+*argv, "pc8") == 0) pm.maxpc8 = atof(*++argv); else if (strcmp(5+*argv, "pc16") == 0) pm.maxpc16 = atof(*++argv); else { fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv); exit(99); } catmore = 1; } else if (strcmp(*argv, "--log8") == 0) --argc, pm.log8 = atof(*++argv), catmore = 1; else if (strcmp(*argv, "--log16") == 0) --argc, pm.log16 = atof(*++argv), catmore = 1; #ifdef PNG_SET_OPTION_SUPPORTED else if (strncmp(*argv, "--option=", 9) == 0) { /* Syntax of the argument is <option>:{on|off} */ const char *arg = 9+*argv; unsigned char option=0, setting=0; #ifdef PNG_ARM_NEON if (strncmp(arg, "arm-neon:", 9) == 0) option = PNG_ARM_NEON, arg += 9; else #endif #ifdef PNG_EXTENSIONS if (strncmp(arg, "extensions:", 11) == 0) option = PNG_EXTENSIONS, arg += 11; else #endif #ifdef PNG_MAXIMUM_INFLATE_WINDOW if (strncmp(arg, "max-inflate-window:", 19) == 0) option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19; else #endif { fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg); exit(99); } if (strcmp(arg, "off") == 0) setting = PNG_OPTION_OFF; else if (strcmp(arg, "on") == 0) setting = PNG_OPTION_ON; else { fprintf(stderr, "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n", *argv, arg); exit(99); } pm.this.options[pm.this.noptions].option = option; pm.this.options[pm.this.noptions++].setting = setting; } #endif /* PNG_SET_OPTION_SUPPORTED */ else { fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv); exit(99); } if (catmore) /* consumed an extra *argv */ { cp = safecat(command, sizeof command, cp, " "); cp = safecat(command, sizeof command, cp, *argv); } } /* If pngvalid is run with no arguments default to a reasonable set of the * tests. */ if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 && pm.ngamma_tests == 0) { /* Make this do all the tests done in the test shell scripts with the same * parameters, where possible. The limitation is that all the progressive * read and interlace stuff has to be done in separate runs, so only the * basic 'standard' and 'size' tests are done. */ pm.test_standard = 1; pm.test_size = 1; pm.test_transform = 1; pm.ngamma_tests = 2U; } if (pm.ngamma_tests > 0 && pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 && pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 && pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0) { pm.test_gamma_threshold = 1; pm.test_gamma_transform = 1; pm.test_gamma_sbit = 1; pm.test_gamma_scale16 = 1; pm.test_gamma_background = 1; pm.test_gamma_alpha_mode = 1; } else if (pm.ngamma_tests == 0) { /* Nothing to test so turn everything off: */ pm.test_gamma_threshold = 0; pm.test_gamma_transform = 0; pm.test_gamma_sbit = 0; pm.test_gamma_scale16 = 0; pm.test_gamma_background = 0; pm.test_gamma_alpha_mode = 0; } Try { /* Make useful base images */ make_transform_images(&pm); /* Perform the standard and gamma tests. */ if (pm.test_standard) { perform_interlace_macro_validation(); perform_formatting_test(&pm.this); # ifdef PNG_READ_SUPPORTED perform_standard_test(&pm); # endif perform_error_test(&pm); } /* Various oddly sized images: */ if (pm.test_size) { make_size_images(&pm.this); # ifdef PNG_READ_SUPPORTED perform_size_test(&pm); # endif } #ifdef PNG_READ_TRANSFORMS_SUPPORTED /* Combinatorial transforms: */ if (pm.test_transform) perform_transform_test(&pm); #endif /* PNG_READ_TRANSFORMS_SUPPORTED */ #ifdef PNG_READ_GAMMA_SUPPORTED if (pm.ngamma_tests > 0) perform_gamma_test(&pm, summary); #endif } Catch_anonymous { fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n"); if (!pm.this.verbose) { if (pm.this.error[0] != 0) fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error); fprintf(stderr, "pngvalid: run with -v to see what happened\n"); } exit(1); } if (summary) { printf("%s: %s (%s point arithmetic)\n", (pm.this.nerrors || (pm.this.treat_warnings_as_errors && pm.this.nwarnings)) ? "FAIL" : "PASS", command, #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500 "floating" #else "fixed" #endif ); } if (memstats) { printf("Allocated memory statistics (in bytes):\n" "\tread %lu maximum single, %lu peak, %lu total\n" "\twrite %lu maximum single, %lu peak, %lu total\n", (unsigned long)pm.this.read_memory_pool.max_max, (unsigned long)pm.this.read_memory_pool.max_limit, (unsigned long)pm.this.read_memory_pool.max_total, (unsigned long)pm.this.write_memory_pool.max_max, (unsigned long)pm.this.write_memory_pool.max_limit, (unsigned long)pm.this.write_memory_pool.max_total); } /* Do this here to provoke memory corruption errors in memory not directly * allocated by libpng - not a complete test, but better than nothing. */ store_delete(&pm.this); /* Error exit if there are any errors, and maybe if there are any * warnings. */ if (pm.this.nerrors || (pm.this.treat_warnings_as_errors && pm.this.nwarnings)) { if (!pm.this.verbose) fprintf(stderr, "pngvalid: %s\n", pm.this.error); fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors, pm.this.nwarnings); exit(1); } /* Success case. */ if (touch != NULL) { FILE *fsuccess = fopen(touch, "wt"); if (fsuccess != NULL) { int error = 0; fprintf(fsuccess, "PNG validation succeeded\n"); fflush(fsuccess); error = ferror(fsuccess); if (fclose(fsuccess) || error) { fprintf(stderr, "%s: write failed\n", touch); exit(1); } } else { fprintf(stderr, "%s: open failed\n", touch); exit(1); } } /* This is required because some very minimal configurations do not use it: */ UNUSED(fail) return 0; }
14,572