prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void SetUpTestCase() { source_data_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBlockSize)); reference_data_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBufferSize)); } 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 Target: 1 Example 2: Code: const char *FS_ReferencedPakPureChecksums( void ) { static char info[BIG_INFO_STRING]; searchpath_t *search; int nFlags, numPaks, checksum; info[0] = 0; checksum = fs_checksumFeed; numPaks = 0; for ( nFlags = FS_GENERAL_REF; nFlags; nFlags = nFlags >> 1 ) { for ( search = fs_searchpaths ; search ; search = search->next ) { if ( search->pack && ( search->pack->referenced & nFlags ) ) { Q_strcat( info, sizeof( info ), va( "%i ", search->pack->pure_checksum ) ); checksum ^= search->pack->pure_checksum; numPaks++; } } } checksum ^= numPaks; Q_strcat( info, sizeof( info ), va( "%i ", checksum ) ); return info; } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SetOnClose(const base::Callback<void(SocketStreamEvent*)>& callback) { on_close_ = callback; } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: archive_acl_from_text_l(struct archive_acl *acl, const char *text, int want_type, struct archive_string_conv *sc) { struct { const char *start; const char *end; } field[6], name; const char *s, *st; int numfields, fields, n, r, sol, ret; int type, types, tag, permset, id; size_t len; char sep; switch (want_type) { case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; __LA_FALLTHROUGH; case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: numfields = 5; break; case ARCHIVE_ENTRY_ACL_TYPE_NFS4: numfields = 6; break; default: return (ARCHIVE_FATAL); } ret = ARCHIVE_OK; types = 0; while (text != NULL && *text != '\0') { /* * Parse the fields out of the next entry, * advance 'text' to start of next entry. */ fields = 0; do { const char *start, *end; next_field(&text, &start, &end, &sep); if (fields < numfields) { field[fields].start = start; field[fields].end = end; } ++fields; } while (sep == ':'); /* Set remaining fields to blank. */ for (n = fields; n < numfields; ++n) field[n].start = field[n].end = NULL; if (field[0].start != NULL && *(field[0].start) == '#') { /* Comment, skip entry */ continue; } n = 0; sol = 0; id = -1; permset = 0; name.start = name.end = NULL; if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { /* POSIX.1e ACLs */ /* * Default keyword "default:user::rwx" * if found, we have one more field * * We also support old Solaris extension: * "defaultuser::rwx" is the default ACL corresponding * to "user::rwx", etc. valid only for first field */ s = field[0].start; len = field[0].end - field[0].start; if (*s == 'd' && (len == 1 || (len >= 7 && memcmp((s + 1), "efault", 6) == 0))) { type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; if (len > 7) field[0].start += 7; else n = 1; } else type = want_type; /* Check for a numeric ID in field n+1 or n+3. */ isint(field[n + 1].start, field[n + 1].end, &id); /* Field n+3 is optional. */ if (id == -1 && fields > (n + 3)) isint(field[n + 3].start, field[n + 3].end, &id); tag = 0; s = field[n].start; st = field[n].start + 1; len = field[n].end - field[n].start; switch (*s) { case 'u': if (len == 1 || (len == 4 && memcmp(st, "ser", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; break; case 'g': if (len == 1 || (len == 5 && memcmp(st, "roup", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 'o': if (len == 1 || (len == 5 && memcmp(st, "ther", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_OTHER; break; case 'm': if (len == 1 || (len == 4 && memcmp(st, "ask", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_MASK; break; default: break; } switch (tag) { case ARCHIVE_ENTRY_ACL_OTHER: case ARCHIVE_ENTRY_ACL_MASK: if (fields == (n + 2) && field[n + 1].start < field[n + 1].end && ismode(field[n + 1].start, field[n + 1].end, &permset)) { /* This is Solaris-style "other:rwx" */ sol = 1; } else if (fields == (n + 3) && field[n + 1].start < field[n + 1].end) { /* Invalid mask or other field */ ret = ARCHIVE_WARN; continue; } break; case ARCHIVE_ENTRY_ACL_USER_OBJ: case ARCHIVE_ENTRY_ACL_GROUP_OBJ: if (id != -1 || field[n + 1].start < field[n + 1].end) { name = field[n + 1]; if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) tag = ARCHIVE_ENTRY_ACL_USER; else tag = ARCHIVE_ENTRY_ACL_GROUP; } break; default: /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } /* * Without "default:" we expect mode in field 3 * Exception: Solaris other and mask fields */ if (permset == 0 && !ismode(field[n + 2 - sol].start, field[n + 2 - sol].end, &permset)) { /* Invalid mode, skip entry */ ret = ARCHIVE_WARN; continue; } } else { /* NFS4 ACLs */ s = field[0].start; len = field[0].end - field[0].start; tag = 0; switch (len) { case 4: if (memcmp(s, "user", 4) == 0) tag = ARCHIVE_ENTRY_ACL_USER; break; case 5: if (memcmp(s, "group", 5) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP; break; case 6: if (memcmp(s, "owner@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; else if (memcmp(s, "group@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 9: if (memcmp(s, "everyone@", 9) == 0) tag = ARCHIVE_ENTRY_ACL_EVERYONE; break; default: break; } if (tag == 0) { /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { n = 1; name = field[1]; isint(name.start, name.end, &id); } else n = 0; if (!is_nfs4_perms(field[1 + n].start, field[1 + n].end, &permset)) { /* Invalid NFSv4 perms, skip entry */ ret = ARCHIVE_WARN; continue; } if (!is_nfs4_flags(field[2 + n].start, field[2 + n].end, &permset)) { /* Invalid NFSv4 flags, skip entry */ ret = ARCHIVE_WARN; continue; } s = field[3 + n].start; len = field[3 + n].end - field[3 + n].start; type = 0; if (len == 4) { if (memcmp(s, "deny", 4) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_DENY; } else if (len == 5) { if (memcmp(s, "allow", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; else if (memcmp(s, "audit", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; else if (memcmp(s, "alarm", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; } if (type == 0) { /* Invalid entry type, skip entry */ ret = ARCHIVE_WARN; continue; } isint(field[4 + n].start, field[4 + n].end, &id); } /* Add entry to the internal list. */ r = archive_acl_add_entry_len_l(acl, type, permset, tag, id, name.start, name.end - name.start, sc); if (r < ARCHIVE_WARN) return (r); if (r != ARCHIVE_OK) ret = ARCHIVE_WARN; types |= type; } /* Reset ACL */ archive_acl_reset(acl, types); return (ret); } Commit Message: Skip 0-length ACL fields Currently, it is possible to create an archive that crashes bsdtar with a malformed ACL: Program received signal SIGSEGV, Segmentation fault. archive_acl_from_text_l (acl=<optimised out>, text=0x7e2e92 "", want_type=<optimised out>, sc=<optimised out>) at libarchive/archive_acl.c:1726 1726 switch (*s) { (gdb) p n $1 = 1 (gdb) p field[n] $2 = {start = 0x0, end = 0x0} Stop this by checking that the length is not zero before beginning the switch statement. I am pretty sure this is the bug mentioned in the qsym paper [1], and I was able to replicate it with a qsym + AFL + afl-rb setup. [1] https://www.usenix.org/conference/usenixsecurity18/presentation/yun CWE ID: CWE-476 Target: 1 Example 2: Code: cifs_d_revalidate(struct dentry *direntry, struct nameidata *nd) { if (nd && (nd->flags & LOOKUP_RCU)) return -ECHILD; if (direntry->d_inode) { if (cifs_revalidate_dentry(direntry)) return 0; else { /* * Forcibly invalidate automounting directory inodes * (remote DFS directories) so to have them * instantiated again for automount */ if (IS_AUTOMOUNT(direntry->d_inode)) return 0; return 1; } } /* * This may be nfsd (or something), anyway, we can't see the * intent of this. So, since this can be for creation, drop it. */ if (!nd) return 0; /* * Drop the negative dentry, in order to make sure to use the * case sensitive name which is specified by user if this is * for creation. */ if (nd->flags & (LOOKUP_CREATE | LOOKUP_RENAME_TARGET)) return 0; if (time_after(jiffies, direntry->d_time + HZ) || !lookupCacheEnabled) return 0; return 1; } Commit Message: cifs: fix dentry refcount leak when opening a FIFO on lookup commit 5bccda0ebc7c0331b81ac47d39e4b920b198b2cd upstream. The cifs code will attempt to open files on lookup under certain circumstances. What happens though if we find that the file we opened was actually a FIFO or other special file? Currently, the open filehandle just ends up being leaked leading to a dentry refcount mismatch and oops on umount. Fix this by having the code close the filehandle on the server if it turns out not to be a regular file. While we're at it, change this spaghetti if statement into a switch too. Reported-by: CAI Qian <[email protected]> Tested-by: CAI Qian <[email protected]> Reviewed-by: Shirish Pargaonkar <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: OxideQQuickWebView::OxideQQuickWebView(QQuickItem* parent) : QQuickItem(parent), d_ptr(new OxideQQuickWebViewPrivate(this)) { oxide::qquick::EnsureChromiumStarted(); Q_D(OxideQQuickWebView); setFlags(QQuickItem::ItemClipsChildrenToShape | QQuickItem::ItemHasContents | QQuickItem::ItemIsFocusScope | QQuickItem::ItemAcceptsDrops); setAcceptedMouseButtons(Qt::AllButtons); setAcceptHoverEvents(true); } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cib_send_tls(gnutls_session * session, xmlNode * msg) { char *xml_text = NULL; # if 0 const char *name = crm_element_name(msg); if (safe_str_neq(name, "cib_command")) { xmlNodeSetName(msg, "cib_result"); } # endif xml_text = dump_xml_unformatted(msg); if (xml_text != NULL) { char *unsent = xml_text; int len = strlen(xml_text); int rc = 0; len++; /* null char */ crm_trace("Message size: %d", len); while (TRUE) { rc = gnutls_record_send(*session, unsent, len); crm_debug("Sent %d bytes", rc); if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) { crm_debug("Retry"); } else if (rc < 0) { crm_debug("Connection terminated"); break; } else if (rc < len) { crm_debug("Only sent %d of %d bytes", rc, len); len -= rc; unsent += rc; } else { break; } } } free(xml_text); return NULL; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399 Target: 1 Example 2: Code: static __init int net_defaults_init(void) { if (register_pernet_subsys(&net_defaults_ops)) panic("Cannot initialize net default settings"); return 0; } Commit Message: net: Fix double free and memory corruption in get_net_ns_by_id() (I can trivially verify that that idr_remove in cleanup_net happens after the network namespace count has dropped to zero --EWB) Function get_net_ns_by_id() does not check for net::count after it has found a peer in netns_ids idr. It may dereference a peer, after its count has already been finaly decremented. This leads to double free and memory corruption: put_net(peer) rtnl_lock() atomic_dec_and_test(&peer->count) [count=0] ... __put_net(peer) get_net_ns_by_id(net, id) spin_lock(&cleanup_list_lock) list_add(&net->cleanup_list, &cleanup_list) spin_unlock(&cleanup_list_lock) queue_work() peer = idr_find(&net->netns_ids, id) | get_net(peer) [count=1] | ... | (use after final put) v ... cleanup_net() ... spin_lock(&cleanup_list_lock) ... list_replace_init(&cleanup_list, ..) ... spin_unlock(&cleanup_list_lock) ... ... ... ... put_net(peer) ... atomic_dec_and_test(&peer->count) [count=0] ... spin_lock(&cleanup_list_lock) ... list_add(&net->cleanup_list, &cleanup_list) ... spin_unlock(&cleanup_list_lock) ... queue_work() ... rtnl_unlock() rtnl_lock() ... for_each_net(tmp) { ... id = __peernet2id(tmp, peer) ... spin_lock_irq(&tmp->nsid_lock) ... idr_remove(&tmp->netns_ids, id) ... ... ... net_drop_ns() ... net_free(peer) ... } ... | v cleanup_net() ... (Second free of peer) Also, put_net() on the right cpu may reorder with left's cpu list_replace_init(&cleanup_list, ..), and then cleanup_list will be corrupted. Since cleanup_net() is executed in worker thread, while put_net(peer) can happen everywhere, there should be enough time for concurrent get_net_ns_by_id() to pick the peer up, and the race does not seem to be unlikely. The patch fixes the problem in standard way. (Also, there is possible problem in peernet2id_alloc(), which requires check for net::count under nsid_lock and maybe_get_net(peer), but in current stable kernel it's used under rtnl_lock() and it has to be safe. Openswitch begun to use peernet2id_alloc(), and possibly it should be fixed too. While this is not in stable kernel yet, so I'll send a separate message to netdev@ later). Cc: Nicolas Dichtel <[email protected]> Signed-off-by: Kirill Tkhai <[email protected]> Fixes: 0c7aecd4bde4 "netns: add rtnl cmd to add and get peer netns ids" Reviewed-by: Andrey Ryabinin <[email protected]> Reviewed-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Eric W. Biederman <[email protected]> Reviewed-by: Eric Dumazet <[email protected]> Acked-by: Nicolas Dichtel <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static PassRefPtr<Range> characterSubrange(CharacterIterator& it, int offset, int length) { it.advance(offset); RefPtr<Range> start = it.range(); if (length > 1) it.advance(length - 1); RefPtr<Range> end = it.range(); return Range::create(start->startContainer()->document(), start->startContainer(), start->startOffset(), end->endContainer(), end->endOffset()); } Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure. BUG=156930,177197 [email protected] Review URL: https://codereview.chromium.org/15057010 git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: JSRetainPtr<JSStringRef> AccessibilityUIElement::stringValue() { return JSStringCreateWithCharacters(0, 0); } Commit Message: [GTK][WTR] Implement AccessibilityUIElement::stringValue https://bugs.webkit.org/show_bug.cgi?id=102951 Reviewed by Martin Robinson. Implement AccessibilityUIElement::stringValue in the ATK backend in the same manner it is implemented in DumpRenderTree. * WebKitTestRunner/InjectedBundle/atk/AccessibilityUIElementAtk.cpp: (WTR::replaceCharactersForResults): (WTR): (WTR::AccessibilityUIElement::stringValue): git-svn-id: svn://svn.chromium.org/blink/trunk@135485 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name); struct sk_buff *skb; struct net_device *dev; __be16 proto; unsigned char *addr; int err, reserve = 0; struct sockcm_cookie sockc; struct virtio_net_hdr vnet_hdr = { 0 }; int offset = 0; struct packet_sock *po = pkt_sk(sk); int hlen, tlen, linear; int extra_len = 0; /* * Get and verify the address. */ if (likely(saddr == NULL)) { dev = packet_cached_dev_get(po); proto = po->num; addr = NULL; } else { err = -EINVAL; if (msg->msg_namelen < sizeof(struct sockaddr_ll)) goto out; if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr))) goto out; proto = saddr->sll_protocol; addr = saddr->sll_addr; dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex); } err = -ENXIO; if (unlikely(dev == NULL)) goto out_unlock; err = -ENETDOWN; if (unlikely(!(dev->flags & IFF_UP))) goto out_unlock; sockc.tsflags = sk->sk_tsflags; sockc.mark = sk->sk_mark; if (msg->msg_controllen) { err = sock_cmsg_send(sk, msg, &sockc); if (unlikely(err)) goto out_unlock; } if (sock->type == SOCK_RAW) reserve = dev->hard_header_len; if (po->has_vnet_hdr) { err = packet_snd_vnet_parse(msg, &len, &vnet_hdr); if (err) goto out_unlock; } if (unlikely(sock_flag(sk, SOCK_NOFCS))) { if (!netif_supports_nofcs(dev)) { err = -EPROTONOSUPPORT; goto out_unlock; } extra_len = 4; /* We're doing our own CRC */ } err = -EMSGSIZE; if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + VLAN_HLEN + extra_len)) goto out_unlock; err = -ENOBUFS; hlen = LL_RESERVED_SPACE(dev); tlen = dev->needed_tailroom; linear = __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len); linear = max(linear, min_t(int, len, dev->hard_header_len)); skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, linear, msg->msg_flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out_unlock; skb_set_network_header(skb, reserve); err = -EINVAL; if (sock->type == SOCK_DGRAM) { offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len); if (unlikely(offset < 0)) goto out_free; } /* Returns -EFAULT on error */ err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len); if (err) goto out_free; if (sock->type == SOCK_RAW && !dev_validate_header(dev, skb->data, len)) { err = -EINVAL; goto out_free; } sock_tx_timestamp(sk, sockc.tsflags, &skb_shinfo(skb)->tx_flags); if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + extra_len) && !packet_extra_vlan_len_allowed(dev, skb)) { err = -EMSGSIZE; goto out_free; } skb->protocol = proto; skb->dev = dev; skb->priority = sk->sk_priority; skb->mark = sockc.mark; packet_pick_tx_queue(dev, skb); if (po->has_vnet_hdr) { err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le()); if (err) goto out_free; len += sizeof(vnet_hdr); } skb_probe_transport_header(skb, reserve); if (unlikely(extra_len == 4)) skb->no_fcs = 1; err = po->xmit(skb); if (err > 0 && (err = net_xmit_errno(err)) != 0) goto out_unlock; dev_put(dev); return len; out_free: kfree_skb(skb); out_unlock: if (dev) dev_put(dev); out: return err; } Commit Message: packet: fix races in fanout_add() Multiple threads can call fanout_add() at the same time. We need to grab fanout_mutex earlier to avoid races that could lead to one thread freeing po->rollover that was set by another thread. Do the same in fanout_release(), for peace of mind, and to help us finding lockdep issues earlier. Fixes: dc99f600698d ("packet: Add fanout support.") Fixes: 0648ab70afe6 ("packet: rollover prepare: per-socket state") Signed-off-by: Eric Dumazet <[email protected]> Cc: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ObjectBackedNativeHandler::RouteFunction( const std::string& name, const std::string& feature_name, const HandlerFunction& handler_function) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context_->v8_context()); v8::Local<v8::Object> data = v8::Object::New(isolate); SetPrivate(data, kHandlerFunction, v8::External::New(isolate, new HandlerFunction(handler_function))); SetPrivate(data, kFeatureName, v8_helpers::ToV8StringUnsafe(isolate, feature_name)); v8::Local<v8::FunctionTemplate> function_template = v8::FunctionTemplate::New(isolate, Router, data); v8::Local<v8::ObjectTemplate>::New(isolate, object_template_) ->Set(isolate, name.c_str(), function_template); router_data_.Append(data); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ZSTD_buildCTable(void* dst, size_t dstCapacity, FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type, U32* count, U32 max, const BYTE* codeTable, size_t nbSeq, const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax, const FSE_CTable* prevCTable, size_t prevCTableSize, void* workspace, size_t workspaceSize) { BYTE* op = (BYTE*)dst; const BYTE* const oend = op + dstCapacity; switch (type) { case set_rle: *op = codeTable[0]; CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max)); return 1; case set_repeat: memcpy(nextCTable, prevCTable, prevCTableSize); return 0; case set_basic: CHECK_F(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */ return 0; case set_compressed: { S16 norm[MaxSeq + 1]; size_t nbSeq_1 = nbSeq; const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max); if (count[codeTable[nbSeq-1]] > 1) { count[codeTable[nbSeq-1]]--; nbSeq_1--; } assert(nbSeq_1 > 1); CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max)); { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */ if (FSE_isError(NCountSize)) return NCountSize; CHECK_F(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize)); return NCountSize; } } default: return assert(0), ERROR(GENERIC); } } Commit Message: fixed T36302429 CWE ID: CWE-362 Target: 1 Example 2: Code: PeriodicWave* BaseAudioContext::createPeriodicWave( const Vector<float>& real, const Vector<float>& imag, const PeriodicWaveConstraints& options, ExceptionState& exception_state) { DCHECK(IsMainThread()); bool disable = options.disableNormalization(); return PeriodicWave::Create(*this, real, imag, disable, exception_state); } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int perf_swevent_add(struct perf_event *event, int flags) { struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); struct hw_perf_event *hwc = &event->hw; struct hlist_head *head; if (is_sampling_event(event)) { hwc->last_period = hwc->sample_period; perf_swevent_set_period(event); } hwc->state = !(flags & PERF_EF_START); head = find_swevent_head(swhash, event); if (!head) { /* * We can race with cpu hotplug code. Do not * WARN if the cpu just got unplugged. */ WARN_ON_ONCE(swhash->online); return -EINVAL; } hlist_add_head_rcu(&event->hlist_entry, head); perf_event_update_userpage(event); return 0; } Commit Message: perf: Fix race in swevent hash There's a race on CPU unplug where we free the swevent hash array while it can still have events on. This will result in a use-after-free which is BAD. Simply do not free the hash array on unplug. This leaves the thing around and no use-after-free takes place. When the last swevent dies, we do a for_each_possible_cpu() iteration anyway to clean these up, at which time we'll free it, so no leakage will occur. Reported-by: Sasha Levin <[email protected]> Tested-by: Sasha Levin <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0, int r1, int c1) { int i; if (mat0->data_) { if (!(mat0->flags_ & JAS_MATRIX_REF)) { jas_free(mat0->data_); } mat0->data_ = 0; mat0->datasize_ = 0; } if (mat0->rows_) { jas_free(mat0->rows_); mat0->rows_ = 0; } mat0->flags_ |= JAS_MATRIX_REF; mat0->numrows_ = r1 - r0 + 1; mat0->numcols_ = c1 - c0 + 1; mat0->maxrows_ = mat0->numrows_; if (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) { /* There is no way to indicate failure to the caller. So, we have no choice but to abort. Ideally, this function should have a non-void return type. In practice, a non-void return type probably would not help much anyways as the caller would just have to terminate anyways. */ abort(); } for (i = 0; i < mat0->numrows_; ++i) { mat0->rows_[i] = mat1->rows_[r0 + i] + c0; } mat0->xstart_ = mat1->xstart_ + c0; mat0->ystart_ = mat1->ystart_ + r0; mat0->xend_ = mat0->xstart_ + mat0->numcols_; mat0->yend_ = mat0->ystart_ + mat0->numrows_; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 1 Example 2: Code: bool NaClProcessHost::Launch( ChromeRenderMessageFilter* chrome_render_message_filter, int socket_count, IPC::Message* reply_msg) { #ifdef DISABLE_NACL NOTIMPLEMENTED() << "Native Client disabled at build time"; return false; #else if (socket_count > 8) { return false; } for (int i = 0; i < socket_count; i++) { nacl::Handle pair[2]; if (nacl::SocketPair(pair) == -1) return false; internal_->sockets_for_renderer.push_back(pair[0]); internal_->sockets_for_sel_ldr.push_back(pair[1]); SetCloseOnExec(pair[0]); SetCloseOnExec(pair[1]); } if (!LaunchSelLdr()) { return false; } chrome_render_message_filter_ = chrome_render_message_filter; reply_msg_ = reply_msg; return true; #endif // DISABLE_NACL } Commit Message: Fix a small leak in FileUtilProxy BUG=none TEST=green mem bots Review URL: http://codereview.chromium.org/7669046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root) { if (!trans || !trans->transaction) { struct inode *btree_inode; btree_inode = root->fs_info->btree_inode; return filemap_write_and_wait(btree_inode->i_mapping); } return btrfs_write_and_wait_marked_extents(root, &trans->transaction->dirty_pages, EXTENT_DIRTY); } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void vmxnet3_activate_device(VMXNET3State *s) { int i; VMW_CFPRN("MTU is %u", s->mtu); s->max_rx_frags = VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG); if (s->max_rx_frags == 0) { s->max_rx_frags = 1; } VMW_CFPRN("Max RX fragments is %u", s->max_rx_frags); s->event_int_idx = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx); assert(vmxnet3_verify_intx(s, s->event_int_idx)); VMW_CFPRN("Events interrupt line is %u", s->event_int_idx); s->auto_int_masking = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask); VMW_CFPRN("Automatic interrupt masking is %d", (int)s->auto_int_masking); s->txq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues); s->rxq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num); assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES); qdescr_table_pa = VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); VMW_CFPRN("TX queues descriptors table is at 0x%" PRIx64, qdescr_table_pa); /* * Worst-case scenario is a packet that holds all TX rings space so * we calculate total size of all TX rings for max TX fragments number */ s->max_tx_frags = 0; /* TX queues */ for (i = 0; i < s->txq_num; i++) { VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num); assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES); qdescr_table_pa = VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); VMW_CFPRN("TX Queue %d interrupt: %d", i, s->txq_descr[i].intr_idx); /* Read rings memory locations for TX queues */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize); vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size, sizeof(struct Vmxnet3_TxDesc), false); VMXNET3_RING_DUMP(VMW_CFPRN, "TX", i, &s->txq_descr[i].tx_ring); s->max_tx_frags += size; /* TXC ring */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize); vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_TxCompDesc), true); VMXNET3_RING_DUMP(VMW_CFPRN, "TXC", i, &s->txq_descr[i].comp_ring); s->txq_descr[i].tx_stats_pa = qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats); memset(&s->txq_descr[i].txq_stats, 0, sizeof(s->txq_descr[i].txq_stats)); /* Fill device-managed parameters for queues */ VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa, ctrl.txThreshold, VMXNET3_DEF_TX_THRESHOLD); } /* Preallocate TX packet wrapper */ VMW_CFPRN("Max TX fragments is %u", s->max_tx_frags); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); /* Read rings memory locations for RX queues */ for (i = 0; i < s->rxq_num; i++) { int j; hwaddr qd_pa = qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) + i * sizeof(struct Vmxnet3_RxQueueDesc); /* Read interrupt number for this RX queue */ s->rxq_descr[i].intr_idx = VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx); assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx)); VMW_CFPRN("RX Queue %d interrupt: %d", i, s->rxq_descr[i].intr_idx); /* Read rings memory locations */ for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) { /* RX rings */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]); vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size, sizeof(struct Vmxnet3_RxDesc), false); VMW_CFPRN("RX queue %d:%d: Base: %" PRIx64 ", Size: %d", i, j, pa, size); } /* RXC ring */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize); vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_RxCompDesc), true); VMW_CFPRN("RXC queue %d: Base: %" PRIx64 ", Size: %d", i, pa, size); s->rxq_descr[i].rx_stats_pa = qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats); memset(&s->rxq_descr[i].rxq_stats, 0, sizeof(s->rxq_descr[i].rxq_stats)); } vmxnet3_validate_interrupts(s); /* Make sure everything is in place before device activation */ smp_wmb(); vmxnet3_reset_mac(s); s->device_active = true; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: BOOLEAN btif_hl_find_mdl_idx_using_handle(tBTA_HL_MDL_HANDLE mdl_handle, UINT8 *p_app_idx,UINT8 *p_mcl_idx, UINT8 *p_mdl_idx){ btif_hl_app_cb_t *p_acb; btif_hl_mcl_cb_t *p_mcb; btif_hl_mdl_cb_t *p_dcb; BOOLEAN found=FALSE; UINT8 i,j,k; *p_app_idx = 0; *p_mcl_idx =0; *p_mdl_idx = 0; for (i=0; i < BTA_HL_NUM_APPS ; i ++) { p_acb =BTIF_HL_GET_APP_CB_PTR(i); for (j=0; j< BTA_HL_NUM_MCLS; j++) { p_mcb =BTIF_HL_GET_MCL_CB_PTR(i,j); for (k=0; k< BTA_HL_NUM_MDLS_PER_MCL; k++) { p_dcb =BTIF_HL_GET_MDL_CB_PTR(i,j,k); if (p_acb->in_use && p_mcb->in_use && p_dcb->in_use && (p_dcb->mdl_handle == mdl_handle)) { found = TRUE; *p_app_idx = i; *p_mcl_idx =j; *p_mdl_idx = k; break; } } } } BTIF_TRACE_EVENT("%s found=%d app_idx=%d mcl_idx=%d mdl_idx=%d ", __FUNCTION__,found,i,j,k ); return found; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: chunk_new_with_alloc_size(size_t alloc) { chunk_t *ch; ch = tor_malloc(alloc); ch->next = NULL; ch->datalen = 0; #ifdef DEBUG_CHUNK_ALLOC ch->DBG_alloc = alloc; #endif ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc); total_bytes_allocated_in_chunks += alloc; ch->data = &ch->mem[0]; return ch; } Commit Message: Add a one-word sentinel value of 0x0 at the end of each buf_t chunk This helps protect against bugs where any part of a buf_t's memory is passed to a function that expects a NUL-terminated input. It also closes TROVE-2016-10-001 (aka bug 20384). CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __init big_key_crypto_init(void) { int ret = -EINVAL; /* init RNG */ big_key_rng = crypto_alloc_rng(big_key_rng_name, 0, 0); if (IS_ERR(big_key_rng)) { big_key_rng = NULL; return -EFAULT; } /* seed RNG */ ret = crypto_rng_reset(big_key_rng, NULL, crypto_rng_seedsize(big_key_rng)); if (ret) goto error; /* init block cipher */ big_key_skcipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(big_key_skcipher)) { big_key_skcipher = NULL; ret = -EFAULT; goto error; } return 0; error: crypto_free_rng(big_key_rng); big_key_rng = NULL; return ret; } Commit Message: KEYS: Sort out big_key initialisation big_key has two separate initialisation functions, one that registers the key type and one that registers the crypto. If the key type fails to register, there's no problem if the crypto registers successfully because there's no way to reach the crypto except through the key type. However, if the key type registers successfully but the crypto does not, big_key_rng and big_key_blkcipher may end up set to NULL - but the code neither checks for this nor unregisters the big key key type. Furthermore, since the key type is registered before the crypto, it is theoretically possible for the kernel to try adding a big_key before the crypto is set up, leading to the same effect. Fix this by merging big_key_crypto_init() and big_key_init() and calling the resulting function late. If they're going to be encrypted, we shouldn't be creating big_keys before we have the facilities to do the encryption available. The key type registration is also moved after the crypto initialisation. The fix also includes message printing on failure. If the big_key type isn't correctly set up, simply doing: dd if=/dev/zero bs=4096 count=1 | keyctl padd big_key a @s ought to cause an oops. Fixes: 13100a72f40f5748a04017e0ab3df4cf27c809ef ('Security: Keys: Big keys stored encrypted') Signed-off-by: David Howells <[email protected]> cc: Peter Hlavaty <[email protected]> cc: Kirill Marinushkin <[email protected]> cc: Artem Savkov <[email protected]> cc: [email protected] Signed-off-by: James Morris <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: nfsd4_encode_layout_types(struct xdr_stream *xdr, u32 layout_types) { __be32 *p; unsigned long i = hweight_long(layout_types); p = xdr_reserve_space(xdr, 4 + 4 * i); if (!p) return nfserr_resource; *p++ = cpu_to_be32(i); for (i = LAYOUT_NFSV4_1_FILES; i < LAYOUT_TYPE_MAX; ++i) if (layout_types & (1 << i)) *p++ = cpu_to_be32(i); 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual const ImePropertyList& current_ime_properties() const { return current_ime_properties_; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _bdf_parse_glyphs( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { int c, mask_index; char* s; unsigned char* bp; unsigned long i, slen, nibbles; _bdf_parse_t* p; bdf_glyph_t* glyph; bdf_font_t* font; FT_Memory memory; FT_Error error = BDF_Err_Ok; FT_UNUSED( call_data ); FT_UNUSED( lineno ); /* only used in debug mode */ p = (_bdf_parse_t *)client_data; font = p->font; memory = font->memory; /* Check for a comment. */ if ( ft_memcmp( line, "COMMENT", 7 ) == 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); goto Exit; } /* The very first thing expected is the number of glyphs. */ if ( !( p->flags & _BDF_GLYPHS ) ) { if ( ft_memcmp( line, "CHARS", 5 ) != 0 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" )); error = BDF_Err_Missing_Chars_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); /* Make sure the number of glyphs is non-zero. */ if ( p->cnt == 0 ) font->glyphs_size = 64; /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ /* number of code points available in Unicode). */ if ( p->cnt >= 0x110000UL ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" )); error = BDF_Err_Invalid_Argument; goto Exit; } if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) goto Exit; p->flags |= _BDF_GLYPHS; goto Exit; } /* Check for the ENDFONT field. */ if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 ) { /* Sort the glyphs by encoding. */ ft_qsort( (char *)font->glyphs, font->glyphs_used, sizeof ( bdf_glyph_t ), by_encoding ); p->flags &= ~_BDF_START; goto Exit; } /* Check for the ENDCHAR field. */ if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 ) { p->glyph_enc = 0; p->flags &= ~_BDF_GLYPH_BITS; goto Exit; } /* Check whether a glyph is being scanned but should be */ /* ignored because it is an unencoded glyph. */ if ( ( p->flags & _BDF_GLYPH ) && p->glyph_enc == -1 && p->opts->keep_unencoded == 0 ) goto Exit; /* Check for the STARTCHAR field. */ if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 ) { /* Set the character name in the parse info first until the */ /* encoding can be checked for an unencoded character. */ FT_FREE( p->glyph_name ); error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" )); error = BDF_Err_Invalid_File_Format; goto Exit; } if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->glyph_name, s, slen + 1 ); p->flags |= _BDF_GLYPH; FT_TRACE4(( DBGMSG1, lineno, s )); goto Exit; } /* Check for the ENCODING field. */ if ( ft_memcmp( line, "ENCODING", 8 ) == 0 ) { if ( !( p->flags & _BDF_GLYPH ) ) { /* Missing STARTCHAR field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" )); error = BDF_Err_Missing_Startchar_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); /* Normalize negative encoding values. The specification only */ /* allows -1, but we can be more generous here. */ if ( p->glyph_enc < -1 ) p->glyph_enc = -1; /* Check for alternative encoding format. */ if ( p->glyph_enc == -1 && p->list.used > 2 ) p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); FT_TRACE4(( DBGMSG2, p->glyph_enc )); /* Check that the encoding is in the Unicode range because */ /* otherwise p->have (a bitmap with static size) overflows. */ if ( p->glyph_enc > 0 && (size_t)p->glyph_enc >= sizeof ( p->have ) * 8 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" )); error = BDF_Err_Invalid_File_Format; } /* Check whether this encoding has already been encountered. */ /* If it has then change it to unencoded so it gets added if */ /* indicated. */ if ( p->glyph_enc >= 0 ) { if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) { /* Emit a message saying a glyph has been moved to the */ /* unencoded area. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12, p->glyph_enc, p->glyph_name )); p->glyph_enc = -1; font->modified = 1; } else _bdf_set_glyph_modified( p->have, p->glyph_enc ); } if ( p->glyph_enc >= 0 ) { /* Make sure there are enough glyphs allocated in case the */ /* number of characters happen to be wrong. */ if ( font->glyphs_used == font->glyphs_size ) { if ( FT_RENEW_ARRAY( font->glyphs, font->glyphs_size, font->glyphs_size + 64 ) ) goto Exit; font->glyphs_size += 64; } glyph = font->glyphs + font->glyphs_used++; glyph->name = p->glyph_name; glyph->encoding = p->glyph_enc; /* Reset the initial glyph info. */ p->glyph_name = 0; } else { /* Unencoded glyph. Check whether it should */ /* be added or not. */ if ( p->opts->keep_unencoded != 0 ) { /* Allocate the next unencoded glyph. */ if ( font->unencoded_used == font->unencoded_size ) { if ( FT_RENEW_ARRAY( font->unencoded , font->unencoded_size, font->unencoded_size + 4 ) ) goto Exit; font->unencoded_size += 4; } glyph = font->unencoded + font->unencoded_used; glyph->name = p->glyph_name; glyph->encoding = font->unencoded_used++; } else /* Free up the glyph name if the unencoded shouldn't be */ /* kept. */ FT_FREE( p->glyph_name ); p->glyph_name = 0; } /* Clear the flags that might be added when width and height are */ /* checked for consistency. */ p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); p->flags |= _BDF_ENCODING; goto Exit; } /* Point at the glyph being constructed. */ if ( p->glyph_enc == -1 ) glyph = font->unencoded + ( font->unencoded_used - 1 ); else glyph = font->glyphs + ( font->glyphs_used - 1 ); /* Check whether a bitmap is being constructed. */ if ( p->flags & _BDF_BITMAP ) { /* If there are more rows than are specified in the glyph metrics, */ /* ignore the remaining lines. */ if ( p->row >= (unsigned long)glyph->bbx.height ) { if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding )); p->flags |= _BDF_GLYPH_HEIGHT_CHECK; font->modified = 1; } goto Exit; } /* Only collect the number of nibbles indicated by the glyph */ /* metrics. If there are more columns, they are simply ignored. */ nibbles = glyph->bpr << 1; bp = glyph->bitmap + p->row * glyph->bpr; for ( i = 0; i < nibbles; i++ ) { c = line[i]; if ( !sbitset( hdigits, c ) ) break; *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); if ( i + 1 < nibbles && ( i & 1 ) ) *++bp = 0; } /* If any line has not enough columns, */ /* indicate they have been padded with zero bits. */ if ( i < nibbles && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } /* Remove possible garbage at the right. */ mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; if ( glyph->bbx.width ) *bp &= nibble_mask[mask_index]; /* If any line has extra columns, indicate they have been removed. */ if ( i == nibbles && sbitset( hdigits, line[nibbles] ) && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } p->row++; goto Exit; } /* Expect the SWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); p->flags |= _BDF_SWIDTH; goto Exit; } /* Expect the DWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); if ( !( p->flags & _BDF_SWIDTH ) ) { /* Missing SWIDTH field. Emit an auto correction message and set */ /* the scalable width from the device width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno )); glyph->swidth = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); } p->flags |= _BDF_DWIDTH; goto Exit; } /* Expect the BBX field next. */ if ( ft_memcmp( line, "BBX", 3 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); /* Generate the ascent and descent of the character. */ glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); /* Determine the overall font bounding box as the characters are */ /* loaded so corrections can be done later if indicated. */ p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); if ( !( p->flags & _BDF_DWIDTH ) ) { /* Missing DWIDTH field. Emit an auto correction message and set */ /* the device width to the glyph width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno )); glyph->dwidth = glyph->bbx.width; } /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ /* value if necessary. */ if ( p->opts->correct_metrics != 0 ) { /* Determine the point size of the glyph. */ unsigned short sw = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); if ( sw != glyph->swidth ) { glyph->swidth = sw; if ( p->glyph_enc == -1 ) _bdf_set_glyph_modified( font->umod, font->unencoded_used - 1 ); else _bdf_set_glyph_modified( font->nmod, glyph->encoding ); p->flags |= _BDF_SWIDTH_ADJ; font->modified = 1; } } p->flags |= _BDF_BBX; goto Exit; } /* And finally, gather up the bitmap. */ if ( ft_memcmp( line, "BITMAP", 6 ) == 0 ) { unsigned long bitmap_size; if ( !( p->flags & _BDF_BBX ) ) { /* Missing BBX field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" )); error = BDF_Err_Missing_Bbx_Field; goto Exit; } /* Allocate enough space for the bitmap. */ glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; bitmap_size = glyph->bpr * glyph->bbx.height; if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno )); error = BDF_Err_Bbx_Too_Big; goto Exit; } else glyph->bytes = (unsigned short)bitmap_size; if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) goto Exit; p->row = 0; p->flags |= _BDF_BITMAP; goto Exit; } FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno )); error = BDF_Err_Invalid_File_Format; goto Exit; Missing_Encoding: /* Missing ENCODING field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" )); error = BDF_Err_Missing_Encoding_Field; Exit: if ( error && ( p->flags & _BDF_GLYPH ) ) FT_FREE( p->glyph_name ); return error; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: void ParamTraits<unsigned long>::Log(const param_type& p, std::string* l) { l->append(base::Uint64ToString(static_cast<uint64>(p))); } Commit Message: Validate that paths don't contain embedded NULLs at deserialization. BUG=166867 Review URL: https://chromiumcodereview.appspot.com/11743009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174935 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->64 */ coerce_reg_to_32(dst_reg); coerce_reg_to_32(&src_reg); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } Commit Message: bpf: fix incorrect tracking of register size truncation Properly handle register truncation to a smaller size. The old code first mirrors the clearing of the high 32 bits in the bitwise tristate representation, which is correct. But then, it computes the new arithmetic bounds as the intersection between the old arithmetic bounds and the bounds resulting from the bitwise tristate representation. Therefore, when coerce_reg_to_32() is called on a number with bounds [0xffff'fff8, 0x1'0000'0007], the verifier computes [0xffff'fff8, 0xffff'ffff] as bounds of the truncated number. This is incorrect: The truncated number could also be in the range [0, 7], and no meaningful arithmetic bounds can be computed in that case apart from the obvious [0, 0xffff'ffff]. Starting with v4.14, this is exploitable by unprivileged users as long as the unprivileged_bpf_disabled sysctl isn't set. Debian assigned CVE-2017-16996 for this issue. v2: - flip the mask during arithmetic bounds calculation (Ben Hutchings) v3: - add CVE number (Ben Hutchings) Fixes: b03c9f9fdc37 ("bpf/verifier: track signed and unsigned min/max values") Signed-off-by: Jann Horn <[email protected]> Acked-by: Edward Cree <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) { unsigned short length; unsigned short type; unsigned short size; unsigned char *data = *p; int tlsext_servername = 0; int renegotiate_seen = 0; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif s->tlsext_ticket_expected = 0; if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif if (data >= (d + n - 2)) goto ri_check; n2s(data, length); if (data + length != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } while (data <= (d + n - 4)) { n2s(data, type); n2s(data, size); if (data + size > (d + n)) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { s->session->tlsext_ecpointformatlist_length = 0; if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist "); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if ((SSL_get_options(s) & SSL_OP_NO_TICKET) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->server_opaque_prf_input_len); if (s->s3->server_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->server_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->server_opaque_prf_input); } if (s->s3->server_opaque_prf_input_len == 0) { /* dummy byte just to get non-NULL */ s->s3->server_opaque_prf_input = OPENSSL_malloc(1); } else { s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len); } if (s->s3->server_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_status_request) { /* * MUST be empty and only sent if we've requested a status * request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(data, size)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s-> ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (!s->next_proto_negotiated) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) { unsigned len; /* We must have requested it. */ if (!s->cert->alpn_sent) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } if (size < 4) { *al = TLS1_AD_DECODE_ERROR; return 0; } /*- * The extension data consists of: * uint16 list_length * uint8 proto_length; * uint8 proto[proto_length]; */ len = data[0]; len <<= 8; len |= data[1]; if (len != (unsigned)size - 2) { *al = TLS1_AD_DECODE_ERROR; return 0; } len = data[2]; if (len != (unsigned)size - 3) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->s3->alpn_selected) OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_malloc(len); if (!s->s3->alpn_selected) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->s3->alpn_selected, data + 3, len); s->s3->alpn_selected_len = len; } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al)) return 0; } # endif /* * If this extension type was not otherwise handled, but matches a * custom_cli_ext_record, then send it to the c callback */ else if (custom_ext_parse(s, 0, type, data, size, al) <= 0) return 0; data += size; } if (data != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } *p = data; ri_check: /* * Determine if we need to see RI. Strictly speaking if we want to avoid * an attack we should *always* see RI even on initial server hello * because the client doesn't see any renegotiation during an attack. * However this would mean we could not connect to any server which * doesn't support RI so for the immediate future tolerate RI absence on * initial connect only. */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; } Commit Message: CWE ID: CWE-190 Target: 1 Example 2: Code: static unsigned int sas_ata_qc_issue(struct ata_queued_cmd *qc) { unsigned long flags; struct sas_task *task; struct scatterlist *sg; int ret = AC_ERR_SYSTEM; unsigned int si, xfer = 0; struct ata_port *ap = qc->ap; struct domain_device *dev = ap->private_data; struct sas_ha_struct *sas_ha = dev->port->ha; struct Scsi_Host *host = sas_ha->core.shost; struct sas_internal *i = to_sas_internal(host->transportt); /* TODO: audit callers to ensure they are ready for qc_issue to * unconditionally re-enable interrupts */ local_irq_save(flags); spin_unlock(ap->lock); /* If the device fell off, no sense in issuing commands */ if (test_bit(SAS_DEV_GONE, &dev->state)) goto out; task = sas_alloc_task(GFP_ATOMIC); if (!task) goto out; task->dev = dev; task->task_proto = SAS_PROTOCOL_STP; task->task_done = sas_ata_task_done; if (qc->tf.command == ATA_CMD_FPDMA_WRITE || qc->tf.command == ATA_CMD_FPDMA_READ || qc->tf.command == ATA_CMD_FPDMA_RECV || qc->tf.command == ATA_CMD_FPDMA_SEND || qc->tf.command == ATA_CMD_NCQ_NON_DATA) { /* Need to zero out the tag libata assigned us */ qc->tf.nsect = 0; } ata_tf_to_fis(&qc->tf, qc->dev->link->pmp, 1, (u8 *)&task->ata_task.fis); task->uldd_task = qc; if (ata_is_atapi(qc->tf.protocol)) { memcpy(task->ata_task.atapi_packet, qc->cdb, qc->dev->cdb_len); task->total_xfer_len = qc->nbytes; task->num_scatter = qc->n_elem; } else { for_each_sg(qc->sg, sg, qc->n_elem, si) xfer += sg_dma_len(sg); task->total_xfer_len = xfer; task->num_scatter = si; } task->data_dir = qc->dma_dir; task->scatter = qc->sg; task->ata_task.retry_count = 1; task->task_state_flags = SAS_TASK_STATE_PENDING; qc->lldd_task = task; task->ata_task.use_ncq = ata_is_ncq(qc->tf.protocol); task->ata_task.dma_xfer = ata_is_dma(qc->tf.protocol); if (qc->scsicmd) ASSIGN_SAS_TASK(qc->scsicmd, task); ret = i->dft->lldd_execute_task(task, GFP_ATOMIC); if (ret) { SAS_DPRINTK("lldd_execute_task returned: %d\n", ret); if (qc->scsicmd) ASSIGN_SAS_TASK(qc->scsicmd, NULL); sas_free_task(task); qc->lldd_task = NULL; ret = AC_ERR_SYSTEM; } out: spin_lock(ap->lock); local_irq_restore(flags); return ret; } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AXObject::ancestorExposesActiveDescendant() const { updateCachedAttributeValuesIfNeeded(); return m_cachedAncestorExposesActiveDescendant; } 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: vrrp_tfile_end_handler(void) { vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); struct stat statb; FILE *tf; int ret; if (!tfile->file_path) { report_config_error(CONFIG_GENERAL_ERROR, "No file set for track_file %s - removing", tfile->fname); free_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail); return; } if (track_file_init == TRACK_FILE_NO_INIT) return; ret = stat(tfile->file_path, &statb); if (!ret) { if (track_file_init == TRACK_FILE_CREATE) { /* The file exists */ return; } if ((statb.st_mode & S_IFMT) != S_IFREG) { /* It is not a regular file */ report_config_error(CONFIG_GENERAL_ERROR, "Cannot initialise track file %s - it is not a regular file", tfile->fname); return; } /* Don't overwrite a file on reload */ if (reload) return; } if (!__test_bit(CONFIG_TEST_BIT, &debug)) { /* Write the value to the file */ if ((tf = fopen(tfile->file_path, "w"))) { fprintf(tf, "%d\n", track_file_init_value); fclose(tf); } else report_config_error(CONFIG_GENERAL_ERROR, "Unable to initialise track file %s", tfile->fname); } } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 Target: 1 Example 2: Code: static int descriptors_changed(struct usb_device *udev, struct usb_device_descriptor *old_device_descriptor, struct usb_host_bos *old_bos) { int changed = 0; unsigned index; unsigned serial_len = 0; unsigned len; unsigned old_length; int length; char *buf; if (memcmp(&udev->descriptor, old_device_descriptor, sizeof(*old_device_descriptor)) != 0) return 1; if ((old_bos && !udev->bos) || (!old_bos && udev->bos)) return 1; if (udev->bos) { len = le16_to_cpu(udev->bos->desc->wTotalLength); if (len != le16_to_cpu(old_bos->desc->wTotalLength)) return 1; if (memcmp(udev->bos->desc, old_bos->desc, len)) return 1; } /* Since the idVendor, idProduct, and bcdDevice values in the * device descriptor haven't changed, we will assume the * Manufacturer and Product strings haven't changed either. * But the SerialNumber string could be different (e.g., a * different flash card of the same brand). */ if (udev->serial) serial_len = strlen(udev->serial) + 1; len = serial_len; for (index = 0; index < udev->descriptor.bNumConfigurations; index++) { old_length = le16_to_cpu(udev->config[index].desc.wTotalLength); len = max(len, old_length); } buf = kmalloc(len, GFP_NOIO); if (buf == NULL) { dev_err(&udev->dev, "no mem to re-read configs after reset\n"); /* assume the worst */ return 1; } for (index = 0; index < udev->descriptor.bNumConfigurations; index++) { old_length = le16_to_cpu(udev->config[index].desc.wTotalLength); length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf, old_length); if (length != old_length) { dev_dbg(&udev->dev, "config index %d, error %d\n", index, length); changed = 1; break; } if (memcmp(buf, udev->rawdescriptors[index], old_length) != 0) { dev_dbg(&udev->dev, "config index %d changed (#%d)\n", index, ((struct usb_config_descriptor *) buf)-> bConfigurationValue); changed = 1; break; } } if (!changed && serial_len) { length = usb_string(udev, udev->descriptor.iSerialNumber, buf, serial_len); if (length + 1 != serial_len) { dev_dbg(&udev->dev, "serial string error %d\n", length); changed = 1; } else if (memcmp(buf, udev->serial, length) != 0) { dev_dbg(&udev->dev, "serial string changed\n"); changed = 1; } } kfree(buf); return changed; } Commit Message: USB: fix invalid memory access in hub_activate() Commit 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") changed the hub_activate() routine to make part of it run in a workqueue. However, the commit failed to take a reference to the usb_hub structure or to lock the hub interface while doing so. As a result, if a hub is plugged in and quickly unplugged before the work routine can run, the routine will try to access memory that has been deallocated. Or, if the hub is unplugged while the routine is running, the memory may be deallocated while it is in active use. This patch fixes the problem by taking a reference to the usb_hub at the start of hub_activate() and releasing it at the end (when the work is finished), and by locking the hub interface while the work routine is running. It also adds a check at the start of the routine to see if the hub has already been disconnected, in which nothing should be done. Signed-off-by: Alan Stern <[email protected]> Reported-by: Alexandru Cornea <[email protected]> Tested-by: Alexandru Cornea <[email protected]> Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") CC: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DrawingBuffer::RestoreAllState() { client_->DrawingBufferClientRestoreScissorTest(); client_->DrawingBufferClientRestoreMaskAndClearValues(); client_->DrawingBufferClientRestorePixelPackAlignment(); client_->DrawingBufferClientRestoreTexture2DBinding(); client_->DrawingBufferClientRestoreRenderbufferBinding(); client_->DrawingBufferClientRestoreFramebufferBinding(); client_->DrawingBufferClientRestorePixelUnpackBufferBinding(); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: FileManagerPrivateCustomBindings::FileManagerPrivateCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetFileSystem", base::Bind(&FileManagerPrivateCustomBindings::GetFileSystem, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID: Target: 1 Example 2: Code: void WebContentsImpl::MoveCaret(const gfx::Point& extent) { RenderFrameHostImpl* focused_frame = GetFocusedFrame(); if (!focused_frame) return; focused_frame->GetFrameInputHandler()->MoveCaret(extent); } Commit Message: Prevent renderer initiated back navigation to cancel a browser one. Renderer initiated back/forward navigations must not be able to cancel ongoing browser initiated navigation if they are not user initiated. Note: 'normal' renderer initiated navigation uses the FrameHost::BeginNavigation() path. A code similar to this patch is done in NavigatorImpl::OnBeginNavigation(). Test: ----- Added: NavigationBrowserTest. * HistoryBackInBeforeUnload * HistoryBackInBeforeUnloadAfterSetTimeout * HistoryBackCancelPendingNavigationNoUserGesture * HistoryBackCancelPendingNavigationUserGesture Fixed: * (WPT) .../the-history-interface/traverse_the_history_2.html * (WPT) .../the-history-interface/traverse_the_history_3.html * (WPT) .../the-history-interface/traverse_the_history_4.html * (WPT) .../the-history-interface/traverse_the_history_5.html Bug: 879965 Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c Reviewed-on: https://chromium-review.googlesource.com/1209744 Commit-Queue: Arthur Sonzogni <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Mustaq Ahmed <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#592823} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ExtensionsGuestViewMessageFilter::FrameNavigationHelper::GetGuestView() const { return MimeHandlerViewGuest::From( parent_site_instance_->GetProcess()->GetID(), guest_instance_id_) ->As<MimeHandlerViewGuest>(); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __ptrace_may_access(struct task_struct *task, unsigned int mode) { const struct cred *cred = current_cred(), *tcred; /* May we inspect the given task? * This check is used both for attaching with ptrace * and for allowing access to sensitive information in /proc. * * ptrace_attach denies several cases that /proc allows * because setting up the necessary parent/child relationship * or halting the specified task is impossible. */ int dumpable = 0; /* Don't let security modules deny introspection */ if (same_thread_group(task, current)) return 0; rcu_read_lock(); tcred = __task_cred(task); if (uid_eq(cred->uid, tcred->euid) && uid_eq(cred->uid, tcred->suid) && uid_eq(cred->uid, tcred->uid) && gid_eq(cred->gid, tcred->egid) && gid_eq(cred->gid, tcred->sgid) && gid_eq(cred->gid, tcred->gid)) goto ok; if (ptrace_has_cap(tcred->user_ns, mode)) goto ok; rcu_read_unlock(); return -EPERM; ok: rcu_read_unlock(); smp_rmb(); if (task->mm) dumpable = get_dumpable(task->mm); rcu_read_lock(); if (!dumpable && !ptrace_has_cap(__task_cred(task)->user_ns, mode)) { rcu_read_unlock(); return -EPERM; } rcu_read_unlock(); return security_ptrace_access_check(task, mode); } Commit Message: exec/ptrace: fix get_dumpable() incorrect tests The get_dumpable() return value is not boolean. Most users of the function actually want to be testing for non-SUID_DUMP_USER(1) rather than SUID_DUMP_DISABLE(0). The SUID_DUMP_ROOT(2) is also considered a protected state. Almost all places did this correctly, excepting the two places fixed in this patch. Wrong logic: if (dumpable == SUID_DUMP_DISABLE) { /* be protective */ } or if (dumpable == 0) { /* be protective */ } or if (!dumpable) { /* be protective */ } Correct logic: if (dumpable != SUID_DUMP_USER) { /* be protective */ } or if (dumpable != 1) { /* be protective */ } Without this patch, if the system had set the sysctl fs/suid_dumpable=2, a user was able to ptrace attach to processes that had dropped privileges to that user. (This may have been partially mitigated if Yama was enabled.) The macros have been moved into the file that declares get/set_dumpable(), which means things like the ia64 code can see them too. CVE-2013-2929 Reported-by: Vasily Kulikov <[email protected]> Signed-off-by: Kees Cook <[email protected]> Cc: "Luck, Tony" <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static inline int bt_index_inc(int index) { return (index + 1) & (BT_WAIT_QUEUES - 1); } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } Commit Message: Slightly different fix for #714 CWE ID: CWE-834 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ExtensionsGuestViewMessageFilter::FrameNavigationHelper::FrameNavigationHelper( RenderFrameHost* plugin_rfh, int32_t guest_instance_id, int32_t element_instance_id, bool is_full_page_plugin, ExtensionsGuestViewMessageFilter* filter) : content::WebContentsObserver( content::WebContents::FromRenderFrameHost(plugin_rfh)), frame_tree_node_id_(plugin_rfh->GetFrameTreeNodeId()), guest_instance_id_(guest_instance_id), element_instance_id_(element_instance_id), is_full_page_plugin_(is_full_page_plugin), filter_(filter), parent_site_instance_(plugin_rfh->GetParent()->GetSiteInstance()), weak_factory_(this) { DCHECK(GetGuestView()); NavigateToAboutBlank(); base::PostDelayedTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ExtensionsGuestViewMessageFilter::FrameNavigationHelper:: CancelPendingTask, weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(kAttachFailureDelayMS)); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362 Target: 1 Example 2: Code: static int ucma_set_option_ib(struct ucma_context *ctx, int optname, void *optval, size_t optlen) { int ret; switch (optname) { case RDMA_OPTION_IB_PATH: ret = ucma_set_ib_path(ctx, optval, optlen); break; default: ret = -ENOSYS; } return ret; } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void kvmppc_set_vsr_dword_dump(struct kvm_vcpu *vcpu, u64 gpr) { union kvmppc_one_reg val; int index = vcpu->arch.io_gpr & KVM_MMIO_REG_MASK; if (vcpu->arch.mmio_vsx_tx_sx_enabled) { val.vval = VCPU_VSX_VR(vcpu, index); val.vsxval[0] = gpr; val.vsxval[1] = gpr; VCPU_VSX_VR(vcpu, index) = val.vval; } else { VCPU_VSX_FPR(vcpu, index, 0) = gpr; VCPU_VSX_FPR(vcpu, index, 1) = gpr; } } Commit Message: KVM: PPC: Fix oops when checking KVM_CAP_PPC_HTM The following program causes a kernel oops: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/kvm.h> main() { int fd = open("/dev/kvm", O_RDWR); ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_PPC_HTM); } This happens because when using the global KVM fd with KVM_CHECK_EXTENSION, kvm_vm_ioctl_check_extension() gets called with a NULL kvm argument, which gets dereferenced in is_kvmppc_hv_enabled(). Spotted while reading the code. Let's use the hv_enabled fallback variable, like everywhere else in this function. Fixes: 23528bb21ee2 ("KVM: PPC: Introduce KVM_CAP_PPC_HTM") Cc: [email protected] # v4.7+ Signed-off-by: Greg Kurz <[email protected]> Reviewed-by: David Gibson <[email protected]> Reviewed-by: Thomas Huth <[email protected]> Signed-off-by: Paul Mackerras <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ buflen = MIN(buflen, buf_size); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T)) { return IV_FAIL; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Initialize first_pb_nal_in_pic for error slices first_pb_nal_in_pic was uninitialized for error clips Bug: 29023649 Change-Id: Ie4e0a94059c5f675bf619e31534846e2c2ca58ae CWE ID: CWE-172 Target: 1 Example 2: Code: connect_socket(struct mg_context *ctx /* may be NULL */, const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, SOCKET *sock /* output: socket, must not be NULL */, union usa *sa /* output: socket address, must not be NULL */ ) { int ip_ver = 0; int conn_ret = -1; *sock = INVALID_SOCKET; memset(sa, 0, sizeof(*sa)); if (ebuf_len > 0) { *ebuf = 0; } if (host == NULL) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "NULL host"); return 0; } if ((port <= 0) || !is_valid_port((unsigned)port)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "invalid port"); return 0; } #if !defined(NO_SSL) #if !defined(NO_SSL_DL) #if defined(OPENSSL_API_1_1) if (use_ssl && (TLS_client_method == NULL)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "SSL is not initialized"); return 0; } #else if (use_ssl && (SSLv23_client_method == NULL)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "SSL is not initialized"); return 0; } #endif /* OPENSSL_API_1_1 */ #else (void)use_ssl; #endif /* NO_SSL_DL */ #else (void)use_ssl; #endif /* !defined(NO_SSL) */ if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) { sa->sin.sin_family = AF_INET; sa->sin.sin_port = htons((uint16_t)port); ip_ver = 4; #if defined(USE_IPV6) } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) { sa->sin6.sin6_family = AF_INET6; sa->sin6.sin6_port = htons((uint16_t)port); ip_ver = 6; } else if (host[0] == '[') { /* While getaddrinfo on Windows will work with [::1], * getaddrinfo on Linux only works with ::1 (without []). */ size_t l = strlen(host + 1); char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL; if (h) { h[l - 1] = 0; if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) { sa->sin6.sin6_family = AF_INET6; sa->sin6.sin6_port = htons((uint16_t)port); ip_ver = 6; } mg_free(h); } #endif } if (ip_ver == 0) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "host not found"); return 0; } if (ip_ver == 4) { *sock = socket(PF_INET, SOCK_STREAM, 0); } #if defined(USE_IPV6) else if (ip_ver == 6) { *sock = socket(PF_INET6, SOCK_STREAM, 0); } #endif if (*sock == INVALID_SOCKET) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "socket(): %s", strerror(ERRNO)); return 0; } if (0 != set_non_blocking_mode(*sock)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "Cannot set socket to non-blocking: %s", strerror(ERRNO)); closesocket(*sock); *sock = INVALID_SOCKET; return 0; } set_close_on_exec(*sock, fc(ctx)); if (ip_ver == 4) { /* connected with IPv4 */ conn_ret = connect(*sock, (struct sockaddr *)((void *)&sa->sin), sizeof(sa->sin)); } #if defined(USE_IPV6) else if (ip_ver == 6) { /* connected with IPv6 */ conn_ret = connect(*sock, (struct sockaddr *)((void *)&sa->sin6), sizeof(sa->sin6)); } #endif #if defined(_WIN32) if (conn_ret != 0) { DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */ conn_ret = (int)err; #if !defined(EINPROGRESS) #define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */ #endif /* if !defined(EINPROGRESS) */ } #endif if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) { /* Data for getsockopt */ int sockerr = -1; void *psockerr = &sockerr; #if defined(_WIN32) int len = (int)sizeof(sockerr); #else socklen_t len = (socklen_t)sizeof(sockerr); #endif /* Data for poll */ struct pollfd pfd[1]; int pollres; int ms_wait = 10000; /* 10 second timeout */ /* For a non-blocking socket, the connect sequence is: * 1) call connect (will not block) * 2) wait until the socket is ready for writing (select or poll) * 3) check connection state with getsockopt */ pfd[0].fd = *sock; pfd[0].events = POLLOUT; pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag)); if (pollres != 1) { /* Not connected */ mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "connect(%s:%d): timeout", host, port); closesocket(*sock); *sock = INVALID_SOCKET; return 0; } #if defined(_WIN32) getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len); #else getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len); #endif if (sockerr != 0) { /* Not connected */ mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "connect(%s:%d): error %s", host, port, strerror(sockerr)); closesocket(*sock); *sock = INVALID_SOCKET; return 0; } } return 1; } Commit Message: Check length of memcmp CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: image_transform_png_set_palette_to_rgb_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_palette_to_rgb(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin( Profile* profile, const url::Origin& origin) { SiteCharacteristicsDataStore* data_store = LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile); EXPECT_TRUE(data_store); std::unique_ptr<SiteCharacteristicsDataReader> reader = data_store->GetReaderForOrigin(origin); internal::LocalSiteCharacteristicsDataImpl* impl = static_cast<LocalSiteCharacteristicsDataReader*>(reader.get()) ->impl_for_testing() .get(); while (!impl->site_characteristics_for_testing().IsInitialized()) base::RunLoop().RunUntilIdle(); return reader; } 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 <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Target: 1 Example 2: Code: void DocumentLoader::ResumeParser() { parser_blocked_count_--; DCHECK_GE(parser_blocked_count_, 0); if (parser_blocked_count_ != 0) return; if (committed_data_buffer_ && !committed_data_buffer_->IsEmpty()) { base::AutoReset<bool> reentrancy_protector(&in_data_received_, true); const char* segment; size_t pos = 0; while (size_t length = committed_data_buffer_->GetSomeData(segment, pos)) { parser_->AppendBytes(segment, length); pos += length; } committed_data_buffer_->Clear(); ProcessDataBuffer(); } if (finished_loading_) { finished_loading_ = false; parser_->Finish(); parser_.Clear(); } } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ipv6_select_ident(struct frag_hdr *fhdr, struct rt6_info *rt) { static u32 ip6_idents_hashrnd __read_mostly; u32 hash, id; net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); hash = __ipv6_addr_jhash(&rt->rt6i_dst.addr, ip6_idents_hashrnd); hash = __ipv6_addr_jhash(&rt->rt6i_src.addr, hash); id = ip_idents_reserve(hash, 1); fhdr->identification = htonl(id); } Commit Message: inet: update the IP ID generation algorithm to higher standards. Commit 355b98553789 ("netns: provide pure entropy for net_hash_mix()") makes net_hash_mix() return a true 32 bits of entropy. When used in the IP ID generation algorithm, this has the effect of extending the IP ID generation key from 32 bits to 64 bits. However, net_hash_mix() is only used for IP ID generation starting with kernel version 4.1. Therefore, earlier kernels remain with 32-bit key no matter what the net_hash_mix() return value is. This change addresses the issue by explicitly extending the key to 64 bits for kernels older than 4.1. Signed-off-by: Amit Klein <[email protected]> Cc: Ben Hutchings <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { int result = -1; if (!a || !b || a->type != b->type) return -1; switch (a->type) { case V_ASN1_OBJECT: result = OBJ_cmp(a->value.object, b->value.object); break; case V_ASN1_BOOLEAN: result = a->value.boolean - b->value.boolean; break; case V_ASN1_NULL: result = 0; /* They do not have content. */ break; case V_ASN1_INTEGER: case V_ASN1_NEG_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_NEG_ENUMERATED: case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: default: result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr, (ASN1_STRING *)b->value.ptr); break; } return result; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: const Extension* ExtensionService::GetExtensionByIdInternal( const std::string& id, bool include_enabled, bool include_disabled, bool include_terminated) const { std::string lowercase_id = StringToLowerASCII(id); if (include_enabled) { for (ExtensionList::const_iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { if ((*iter)->id() == lowercase_id) return *iter; } } if (include_disabled) { for (ExtensionList::const_iterator iter = disabled_extensions_.begin(); iter != disabled_extensions_.end(); ++iter) { if ((*iter)->id() == lowercase_id) return *iter; } } if (include_terminated) { for (ExtensionList::const_iterator iter = terminated_extensions_.begin(); iter != terminated_extensions_.end(); ++iter) { if ((*iter)->id() == lowercase_id) return *iter; } } return NULL; } Commit Message: Limit extent of webstore app to just chrome.google.com/webstore. BUG=93497 TEST=Try installing extensions and apps from the webstore, starting both being initially logged in, and not. Review URL: http://codereview.chromium.org/7719003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ft_glyphslot_alloc_bitmap( FT_GlyphSlot slot, FT_ULong size ) { FT_Memory memory = FT_FACE_MEMORY( slot->face ); FT_Error error; if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP ) FT_FREE( slot->bitmap.buffer ); else slot->internal->flags |= FT_GLYPH_OWN_BITMAP; (void)FT_ALLOC( slot->bitmap.buffer, size ); return error; } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GaiaOAuthClient::Core::FetchUserInfoAndInvokeCallback() { request_.reset(new UrlFetcher( GURL(provider_info_.user_info_url), UrlFetcher::GET)); request_->SetRequestContext(request_context_getter_); request_->SetHeader("Authorization", "Bearer " + access_token_); request_->Start( base::Bind(&GaiaOAuthClient::Core::OnUserInfoFetchComplete, this)); } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: int jfs_fsync(struct file *file, loff_t start, loff_t end, int datasync) { struct inode *inode = file->f_mapping->host; int rc = 0; rc = filemap_write_and_wait_range(inode->i_mapping, start, end); if (rc) return rc; mutex_lock(&inode->i_mutex); if (!(inode->i_state & I_DIRTY) || (datasync && !(inode->i_state & I_DIRTY_DATASYNC))) { /* Make sure committed changes hit the disk */ jfs_flush_journal(JFS_SBI(inode->i_sb)->log, 1); mutex_unlock(&inode->i_mutex); return rc; } rc |= jfs_commit_inode(inode, 1); mutex_unlock(&inode->i_mutex); return rc ? -EIO : 0; } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WebContentsImpl::WasDiscarded() { return GetFrameTree()->root()->was_discarded(); } Commit Message: Prevent renderer initiated back navigation to cancel a browser one. Renderer initiated back/forward navigations must not be able to cancel ongoing browser initiated navigation if they are not user initiated. Note: 'normal' renderer initiated navigation uses the FrameHost::BeginNavigation() path. A code similar to this patch is done in NavigatorImpl::OnBeginNavigation(). Test: ----- Added: NavigationBrowserTest. * HistoryBackInBeforeUnload * HistoryBackInBeforeUnloadAfterSetTimeout * HistoryBackCancelPendingNavigationNoUserGesture * HistoryBackCancelPendingNavigationUserGesture Fixed: * (WPT) .../the-history-interface/traverse_the_history_2.html * (WPT) .../the-history-interface/traverse_the_history_3.html * (WPT) .../the-history-interface/traverse_the_history_4.html * (WPT) .../the-history-interface/traverse_the_history_5.html Bug: 879965 Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c Reviewed-on: https://chromium-review.googlesource.com/1209744 Commit-Queue: Arthur Sonzogni <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Mustaq Ahmed <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#592823} CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: log2vis_encoded_string (PyObject * string, const char *encoding, FriBidiParType base_direction, int clean, int reordernsm) { PyObject *logical = NULL; /* logical unicode object */ PyObject *result = NULL; /* output string object */ /* Always needed for the string length */ logical = PyUnicode_Decode (PyString_AS_STRING (string), PyString_GET_SIZE (string), encoding, "strict"); if (logical == NULL) return NULL; if (strcmp (encoding, "utf-8") == 0) /* Shortcut for utf8 strings (little faster) */ result = log2vis_utf8 (string, PyUnicode_GET_SIZE (logical), base_direction, clean, reordernsm); else { /* Invoke log2vis_unicode and encode back to encoding */ PyObject *visual = log2vis_unicode (logical, base_direction, clean, reordernsm); if (visual) { result = PyUnicode_Encode (PyUnicode_AS_UNICODE (visual), PyUnicode_GET_SIZE (visual), encoding, "strict"); Py_DECREF (visual); } } Py_DECREF (logical); return result; } Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed. CWE ID: CWE-119 Target: 1 Example 2: Code: bool IsRequestScanOptionsInvalid( const blink::mojom::WebBluetoothRequestLEScanOptionsPtr& options) { if (options->accept_all_advertisements) return options->filters.has_value(); return HasEmptyOrInvalidFilter(options->filters); } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg) { rwpng_png_image *mainprog_ptr; /* This function, aside from the extra step of retrieving the "error * pointer" (below) and the fact that it exists within the application * rather than within libpng, is essentially identical to libpng's * default error handler. The second point is critical: since both * setjmp() and longjmp() are called from the same code, they are * guaranteed to have compatible notions of how big a jmp_buf is, * regardless of whether _BSD_SOURCE or anything else has (or has not) * been defined. */ fprintf(stderr, " error: %s (libpng failed)\n", msg); fflush(stderr); mainprog_ptr = png_get_error_ptr(png_ptr); if (mainprog_ptr == NULL) abort(); longjmp(mainprog_ptr->jmpbuf, 1); } Commit Message: Fix integer overflow in rwpng.h (CVE-2016-5735) Reported by Choi Jaeseung Found with Sparrow (http://ropas.snu.ac.kr/sparrow) CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BrowserViewRenderer::ScrollTo(gfx::Vector2d scroll_offset) { gfx::Vector2d max_offset = max_scroll_offset(); gfx::Vector2dF scroll_offset_dip; if (max_offset.x()) { scroll_offset_dip.set_x((scroll_offset.x() * max_scroll_offset_dip_.x()) / max_offset.x()); } if (max_offset.y()) { scroll_offset_dip.set_y((scroll_offset.y() * max_scroll_offset_dip_.y()) / max_offset.y()); } DCHECK_LE(0.f, scroll_offset_dip.x()); DCHECK_LE(0.f, scroll_offset_dip.y()); DCHECK(scroll_offset_dip.x() < max_scroll_offset_dip_.x() || scroll_offset_dip.x() - max_scroll_offset_dip_.x() < kEpsilon) << scroll_offset_dip.x() << " " << max_scroll_offset_dip_.x(); DCHECK(scroll_offset_dip.y() < max_scroll_offset_dip_.y() || scroll_offset_dip.y() - max_scroll_offset_dip_.y() < kEpsilon) << scroll_offset_dip.y() << " " << max_scroll_offset_dip_.y(); if (scroll_offset_dip_ == scroll_offset_dip) return; scroll_offset_dip_ = scroll_offset_dip; TRACE_EVENT_INSTANT2("android_webview", "BrowserViewRenderer::ScrollTo", TRACE_EVENT_SCOPE_THREAD, "x", scroll_offset_dip.x(), "y", scroll_offset_dip.y()); if (compositor_) { compositor_->DidChangeRootLayerScrollOffset( gfx::ScrollOffset(scroll_offset_dip_)); } } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399 Target: 1 Example 2: Code: void ResourceDispatcherHostImpl::NotifyOnUI(int type, int render_process_id, int render_view_id, T* detail) { RenderViewHostImpl* rvh = RenderViewHostImpl::FromID(render_process_id, render_view_id); if (rvh) { RenderViewHostDelegate* rvhd = rvh->GetDelegate(); NotificationService::current()->Notify( type, Source<WebContents>(rvhd->GetAsWebContents()), Details<T>(detail)); } delete detail; } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GLenum GLES2DecoderImpl::DoCheckFramebufferStatus(GLenum target) { Framebuffer* framebuffer = GetFramebufferInfoForTarget(target); if (!framebuffer) { return GL_FRAMEBUFFER_COMPLETE; } GLenum completeness = framebuffer->IsPossiblyComplete(feature_info_.get()); if (completeness != GL_FRAMEBUFFER_COMPLETE) { return completeness; } return framebuffer->GetStatus(texture_manager(), target); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PrefService* DataReductionProxySettings::GetOriginalProfilePrefs() { DCHECK(thread_checker_.CalledOnValidThread()); return prefs_; } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119 Target: 1 Example 2: Code: concat_gen_fifos( void *first, void *second ) { gen_fifo *pf1; gen_fifo *pf2; pf1 = first; pf2 = second; if (NULL == pf1) return pf2; else if (NULL == pf2) return pf1; CONCAT_FIFO(*pf1, *pf2, link); free(pf2); return pf1; } Commit Message: [Bug 1773] openssl not detected during ./configure. [Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL. CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static size_t php_stream_temp_read(php_stream *stream, char *buf, size_t count TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; size_t got; assert(ts != NULL); if (!ts->innerstream) { return -1; } got = php_stream_read(ts->innerstream, buf, count); stream->eof = ts->innerstream->eof; return got; } Commit Message: CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() { DCHECK(main_message_loop_proxy_->BelongsToCurrentThread()); RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399 Target: 1 Example 2: Code: std::string TestURLLoader::GetReachableCrossOriginURL( const std::string& file_name) { std::string url = GetReachableAbsoluteURL(file_name); std::string host("127.0.0.1"); size_t index = url.find(host); ASSERT_NE(index, std::string::npos); url.replace(index, host.length(), "localhost"); return url; } Commit Message: Fix one implicit 64-bit -> 32-bit implicit conversion in a PPAPI test. ../../ppapi/tests/test_url_loader.cc:877:11: warning: implicit conversion loses integer precision: 'int64_t' (aka 'long long') to 'int32_t' (aka 'int') [-Wshorten-64-to-32] total_bytes_to_be_received); ^~~~~~~~~~~~~~~~~~~~~~~~~~ BUG=879657 Change-Id: I152f456368131fe7a2891ff0c97bf83f26ef0906 Reviewed-on: https://chromium-review.googlesource.com/c/1220173 Commit-Queue: Raymes Khoury <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#600182} CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: OMX_ERRORTYPE SoftAVC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { return internalSetBitrateParams( (const OMX_VIDEO_PARAM_BITRATETYPE *)params); } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params; if (avcType->nPortIndex != 1) { return OMX_ErrorUndefined; } mEntropyMode = 0; if (OMX_TRUE == avcType->bEntropyCodingCABAC) mEntropyMode = 1; if ((avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) && avcType->nPFrames) { mBframes = avcType->nBFrames / avcType->nPFrames; } mIInterval = avcType->nPFrames + avcType->nBFrames; if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode) mDisableDeblkLevel = 4; if (avcType->nRefFrames != 1 || avcType->bUseHadamard != OMX_TRUE || avcType->nRefIdx10ActiveMinus1 != 0 || avcType->nRefIdx11ActiveMinus1 != 0 || avcType->bWeightedPPrediction != OMX_FALSE || avcType->bconstIpred != OMX_FALSE || avcType->bDirect8x8Inference != OMX_FALSE || avcType->bDirectSpatialTemporal != OMX_FALSE || avcType->nCabacInitIdc != 0) { return OMX_ErrorUndefined; } if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LoginHtmlDialog::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type.value == NotificationType::LOAD_COMPLETED_MAIN_FRAME); if (bubble_frame_view_) bubble_frame_view_->StopThrobber(); } Commit Message: cros: The next 100 clang plugin errors. BUG=none TEST=none TBR=dpolukhin Review URL: http://codereview.chromium.org/7022008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85418 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: uint32_t GetLiveVars(PP_Var live_vars[], uint32_t array_size) { std::vector<PP_Var> vars = PpapiGlobals::Get()->GetVarTracker()->GetLiveVars(); for (size_t i = 0u; i < std::min(static_cast<size_t>(array_size), vars.size()); ++i) live_vars[i] = vars[i]; return vars.size(); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: uint32_t GPMF_Key(GPMF_stream *ms) { if (ms) { uint32_t key = ms->buffer[ms->pos]; return key; } return 0; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int encode_msg(struct sip_msg *msg,char *payload,int len) { int i,j,k,u,request; unsigned short int h; struct hdr_field* hf; struct msg_start* ms; struct sip_uri miuri; char *myerror=NULL; ptrdiff_t diff; if(len < MAX_ENCODED_MSG + MAX_MESSAGE_LEN) return -1; if(parse_headers(msg,HDR_EOH_F,0)<0){ myerror="in parse_headers"; goto error; } memset(payload,0,len); ms=&msg->first_line; if(ms->type == SIP_REQUEST) request=1; else if(ms->type == SIP_REPLY) request=0; else{ myerror="message is neither request nor response"; goto error; } if(request) { for(h=0;h<32;j=(0x01<<h),h++) if(j & ms->u.request.method_value) break; } else { h=(unsigned short)(ms->u.reply.statuscode); } if(h==32){/*statuscode wont be 32...*/ myerror="unknown message type\n"; goto error; } h=htons(h); /*first goes the message code type*/ memcpy(payload,&h,2); h=htons((unsigned short int)msg->len); /*then goes the message start idx, but we'll put it later*/ /*then goes the message length (we hope it to be less than 65535 bytes...)*/ memcpy(&payload[MSG_LEN_IDX],&h,2); /*then goes the content start index (starting from SIP MSG START)*/ if(0>(diff=(get_body(msg)-(msg->buf)))){ myerror="body starts before the message (uh ?)"; goto error; }else h=htons((unsigned short int)diff); memcpy(payload+CONTENT_IDX,&h,2); payload[METHOD_CODE_IDX]=(unsigned char)(request? (ms->u.request.method.s-msg->buf): (ms->u.reply.status.s-msg->buf)); payload[METHOD_CODE_IDX+1]=(unsigned char)(request? (ms->u.request.method.len): (ms->u.reply.status.len)); payload[URI_REASON_IDX]=(unsigned char)(request? (ms->u.request.uri.s-msg->buf): (ms->u.reply.reason.s-msg->buf)); payload[URI_REASON_IDX+1]=(unsigned char)(request? (ms->u.request.uri.len): (ms->u.reply.reason.len)); payload[VERSION_IDX]=(unsigned char)(request? (ms->u.request.version.s-msg->buf): (ms->u.reply.version.s-msg->buf)); if(request){ if (parse_uri(ms->u.request.uri.s,ms->u.request.uri.len, &miuri)<0){ LM_ERR("<%.*s>\n",ms->u.request.uri.len,ms->u.request.uri.s); myerror="while parsing the R-URI"; goto error; } if(0>(j=encode_uri2(msg->buf, ms->u.request.method.s-msg->buf+ms->len, ms->u.request.uri,&miuri, (unsigned char*)&payload[REQUEST_URI_IDX+1]))) { myerror="ENCODE_MSG: ERROR while encoding the R-URI"; goto error; } payload[REQUEST_URI_IDX]=(unsigned char)j; k=REQUEST_URI_IDX+1+j; }else k=REQUEST_URI_IDX; u=k; k++; for(i=0,hf=msg->headers;hf;hf=hf->next,i++); i++;/*we do as if there was an extra header, that marks the end of the previous header in the headers hashtable(read below)*/ j=k+3*i; for(i=0,hf=msg->headers;hf;hf=hf->next,k+=3){ payload[k]=(unsigned char)(hf->type & 0xFF); h=htons(j); /*now goes a payload-based-ptr to where the header-code starts*/ memcpy(&payload[k+1],&h,2); /*TODO fix this... fixed with k-=3?*/ if(0>(i=encode_header(msg,hf,(unsigned char*)(payload+j),MAX_ENCODED_MSG+MAX_MESSAGE_LEN-j))){ LM_ERR("encoding header %.*s\n",hf->name.len,hf->name.s); goto error; k-=3; continue; } j+=(unsigned short int)i; } /*now goes the number of headers that have been found, right after the meta-msg-section*/ payload[u]=(unsigned char)((k-u-1)/3); j=htons(j); /*now copy the number of bytes that the headers-meta-section has occupied,right afther * headers-meta-section(the array with ['v',[2:where],'r',[2:where],'R',[2:where],...] * this is to know where the LAST header ends, since the length of each header-struct * is calculated substracting the nextHeaderStart - presentHeaderStart * the k+1 is because payload[k] is usually the letter*/ memcpy(&payload[k+1],&j,2); k+=3; j=ntohs(j); /*now we copy the headers-meta-section after the msg-headers-meta-section*/ /*memcpy(&payload[k],payload2,j);*/ /*j+=k;*/ /*pkg_free(payload2);*/ /*now we copy the actual message after the headers-meta-section*/ memcpy(&payload[j],msg->buf,msg->len); LM_DBG("msglen = %d,msg starts at %d\n",msg->len,j); j=htons(j); /*now we copy at the beginning, the index to where the actual message starts*/ memcpy(&payload[MSG_START_IDX],&j,2); return GET_PAY_SIZE( payload ); error: LM_ERR("%s\n",myerror); return -1; } Commit Message: seas: safety check for target buffer size before copying message in encode_msg() - avoid buffer overflow for large SIP messages - reported by Stelios Tsampas CWE ID: CWE-119 Target: 1 Example 2: Code: void CairoOutputDev::setCairo(cairo_t *cairo) { if (this->cairo != NULL) { cairo_status_t status = cairo_status (this->cairo); if (status) { warning("cairo context error: %s\n", cairo_status_to_string(status)); } cairo_destroy (this->cairo); assert(!cairo_shape); } if (cairo != NULL) { this->cairo = cairo_reference (cairo); /* save the initial matrix so that we can use it for type3 fonts. */ cairo_get_matrix(cairo, &orig_matrix); } else { this->cairo = NULL; this->cairo_shape = NULL; } } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PageSerializer::serializeFrame(Frame* frame) { Document* document = frame->document(); KURL url = document->url(); if (!url.isValid() || url.isBlankURL()) { url = urlForBlankFrame(frame); } if (m_resourceURLs.contains(url)) { return; } if (document->isImageDocument()) { ImageDocument* imageDocument = toImageDocument(document); addImageToResources(imageDocument->cachedImage(), imageDocument->imageElement()->renderer(), url); return; } Vector<Node*> nodes; OwnPtr<SerializerMarkupAccumulator> accumulator; if (m_URLs) accumulator = adoptPtr(new LinkChangeSerializerMarkupAccumulator(this, document, &nodes, m_URLs, m_directory)); else accumulator = adoptPtr(new SerializerMarkupAccumulator(this, document, &nodes)); String text = accumulator->serializeNodes(document, IncludeNode); WTF::TextEncoding textEncoding(document->charset()); CString frameHTML = textEncoding.normalizeAndEncode(text, WTF::EntitiesForUnencodables); m_resources->append(SerializedResource(url, document->suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length()))); m_resourceURLs.add(url); for (Vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) { Node* node = *iter; if (!node->isElementNode()) continue; Element* element = toElement(node); if (element->isStyledElement()) { retrieveResourcesForProperties(element->inlineStyle(), document); retrieveResourcesForProperties(element->presentationAttributeStyle(), document); } if (element->hasTagName(HTMLNames::imgTag)) { HTMLImageElement* imageElement = toHTMLImageElement(element); KURL url = document->completeURL(imageElement->getAttribute(HTMLNames::srcAttr)); ImageResource* cachedImage = imageElement->cachedImage(); addImageToResources(cachedImage, imageElement->renderer(), url); } else if (element->hasTagName(HTMLNames::inputTag)) { HTMLInputElement* inputElement = toHTMLInputElement(element); if (inputElement->isImageButton() && inputElement->hasImageLoader()) { KURL url = inputElement->src(); ImageResource* cachedImage = inputElement->imageLoader()->image(); addImageToResources(cachedImage, inputElement->renderer(), url); } } else if (element->hasTagName(HTMLNames::linkTag)) { HTMLLinkElement* linkElement = toHTMLLinkElement(element); if (CSSStyleSheet* sheet = linkElement->sheet()) { KURL url = document->completeURL(linkElement->getAttribute(HTMLNames::hrefAttr)); serializeCSSStyleSheet(sheet, url); ASSERT(m_resourceURLs.contains(url)); } } else if (element->hasTagName(HTMLNames::styleTag)) { HTMLStyleElement* styleElement = toHTMLStyleElement(element); if (CSSStyleSheet* sheet = styleElement->sheet()) serializeCSSStyleSheet(sheet, KURL()); } } for (Frame* childFrame = frame->tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling()) serializeFrame(childFrame); } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static NavigationPolicy NavigationPolicyForRequest( const FrameLoadRequest& request) { NavigationPolicy policy = kNavigationPolicyCurrentTab; Event* event = request.TriggeringEvent(); if (!event) return policy; if (request.Form() && event->UnderlyingEvent()) event = event->UnderlyingEvent(); if (event->IsMouseEvent()) { MouseEvent* mouse_event = ToMouseEvent(event); NavigationPolicyFromMouseEvent( mouse_event->button(), mouse_event->ctrlKey(), mouse_event->shiftKey(), mouse_event->altKey(), mouse_event->metaKey(), &policy); } else if (event->IsKeyboardEvent()) { KeyboardEvent* key_event = ToKeyboardEvent(event); NavigationPolicyFromMouseEvent(0, key_event->ctrlKey(), key_event->shiftKey(), key_event->altKey(), key_event->metaKey(), &policy); } else if (event->IsGestureEvent()) { GestureEvent* gesture_event = ToGestureEvent(event); NavigationPolicyFromMouseEvent( 0, gesture_event->ctrlKey(), gesture_event->shiftKey(), gesture_event->altKey(), gesture_event->metaKey(), &policy); } return policy; } Commit Message: Only allow downloading in response to real keyboard modifiers BUG=848531 Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf Reviewed-on: https://chromium-review.googlesource.com/1082216 Reviewed-by: Mike West <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#564051} CWE ID: Target: 1 Example 2: Code: static void print_ls(int mode, const unsigned char *sha1, const char *path) { static struct strbuf line = STRBUF_INIT; /* See show_tree(). */ const char *type = S_ISGITLINK(mode) ? commit_type : S_ISDIR(mode) ? tree_type : blob_type; if (!mode) { /* missing SP path LF */ strbuf_reset(&line); strbuf_addstr(&line, "missing "); quote_c_style(path, &line, NULL, 0); strbuf_addch(&line, '\n'); } else { /* mode SP type SP object_name TAB path LF */ strbuf_reset(&line); strbuf_addf(&line, "%06o %s %s\t", mode & ~NO_DELTA, type, sha1_to_hex(sha1)); quote_c_style(path, &line, NULL, 0); strbuf_addch(&line, '\n'); } cat_blob_write(line.buf, line.len); } Commit Message: prefer memcpy to strcpy When we already know the length of a string (e.g., because we just malloc'd to fit it), it's nicer to use memcpy than strcpy, as it makes it more obvious that we are not going to overflow the buffer (because the size we pass matches the size in the allocation). This also eliminates calls to strcpy, which make auditing the code base harder. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static __inline__ void isdn_net_device_stop_queue(isdn_net_local *lp) { if (lp->master) netif_stop_queue(lp->master); else netif_stop_queue(lp->netdev->dev); } 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 <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void scsi_read_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->sector_count == (uint32_t)-1) { DPRINTF("Read buf_len=%zd\n", r->iov.iov_len); r->sector_count = 0; scsi_req_data(&r->req, r->iov.iov_len); return; } DPRINTF("Read sector_count=%d\n", r->sector_count); if (r->sector_count == 0) { /* This also clears the sense buffer for REQUEST SENSE. */ scsi_req_complete(&r->req, GOOD); return; } /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_read_complete(r, -EINVAL); return; } n = r->sector_count; if (n > SCSI_DMA_BUF_SIZE / 512) n = SCSI_DMA_BUF_SIZE / 512; if (s->tray_open) { scsi_read_complete(r, -ENOMEDIUM); } r->iov.iov_len = n * 512; qemu_iovec_init_external(&r->qiov, &r->iov, 1); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n, scsi_read_complete, r); if (r->req.aiocb == NULL) { scsi_read_complete(r, -EIO); } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: gboolean TabStripGtk::OnExpose(GtkWidget* widget, GdkEventExpose* event) { TRACE_EVENT0("ui::gtk", "TabStripGtk::OnExpose"); if (gdk_region_empty(event->region)) return TRUE; GdkRectangle* rects; gint num_rects; gdk_region_get_rectangles(event->region, &rects, &num_rects); qsort(rects, num_rects, sizeof(GdkRectangle), CompareGdkRectangles); std::vector<int> tabs_to_repaint; if (!IsDragSessionActive() && CanPaintOnlyFavicons(rects, num_rects, &tabs_to_repaint)) { PaintOnlyFavicons(event, tabs_to_repaint); g_free(rects); return TRUE; } g_free(rects); if (active_animation_.get() || drag_controller_.get()) { event->area.width = bounds_.width(); } else { event->area.width += event->area.x; } event->area.x = 0; event->area.y = 0; event->area.height = bounds_.height(); gdk_region_union_with_rect(event->region, &event->area); gtk_container_propagate_expose(GTK_CONTAINER(tabstrip_.get()), newtab_button_->widget(), event); TabGtk* selected_tab = NULL; int tab_count = GetTabCount(); for (int i = tab_count - 1; i >= 0; --i) { TabGtk* tab = GetTabAt(i); if (!tab->IsActive()) { gtk_container_propagate_expose(GTK_CONTAINER(tabstrip_.get()), tab->widget(), event); } else { selected_tab = tab; } } if (selected_tab) { gtk_container_propagate_expose(GTK_CONTAINER(tabstrip_.get()), selected_tab->widget(), event); } return TRUE; } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: main(void) { fprintf(stderr, "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n", PNG_ZLIB_VERNUM); return 77; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc) { uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; horDiff16(tif, cp0, cc); TIFFSwabArrayOfShort(wp, wc); } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119 Target: 1 Example 2: Code: void jpc_ns_invlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride, int parity) { jpc_fix_t *lptr; jpc_fix_t *hptr; register jpc_fix_t *lptr2; register jpc_fix_t *hptr2; register int n; register int i; int llen; llen = (numrows + 1 - parity) >> 1; if (numrows > 1) { /* Apply the scaling step. */ #if defined(WT_DOSCALE) lptr = &a[0]; n = llen; while (n-- > 0) { lptr2 = lptr; for (i = 0; i < numcols; ++i) { lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN)); ++lptr2; } lptr += stride; } hptr = &a[llen * stride]; n = numrows - llen; while (n-- > 0) { hptr2 = hptr; for (i = 0; i < numcols; ++i) { hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN)); ++hptr2; } hptr += stride; } #endif /* Apply the first lifting step. */ lptr = &a[0]; hptr = &a[llen * stride]; if (!parity) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA), hptr2[0])); ++lptr2; ++hptr2; } lptr += stride; } n = llen - (!parity) - (parity != (numrows & 1)); while (n-- > 0) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA), jpc_fix_add(hptr2[0], hptr2[stride]))); ++lptr2; ++hptr2; } lptr += stride; hptr += stride; } if (parity != (numrows & 1)) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA), hptr2[0])); ++lptr2; ++hptr2; } } /* Apply the second lifting step. */ lptr = &a[0]; hptr = &a[llen * stride]; if (parity) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA), lptr2[0])); ++hptr2; ++lptr2; } hptr += stride; } n = numrows - llen - parity - (parity == (numrows & 1)); while (n-- > 0) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA), jpc_fix_add(lptr2[0], lptr2[stride]))); ++lptr2; ++hptr2; } hptr += stride; lptr += stride; } if (parity == (numrows & 1)) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA), lptr2[0])); ++lptr2; ++hptr2; } } /* Apply the third lifting step. */ lptr = &a[0]; hptr = &a[llen * stride]; if (!parity) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA), hptr2[0])); ++lptr2; ++hptr2; } lptr += stride; } n = llen - (!parity) - (parity != (numrows & 1)); while (n-- > 0) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA), jpc_fix_add(hptr2[0], hptr2[stride]))); ++lptr2; ++hptr2; } lptr += stride; hptr += stride; } if (parity != (numrows & 1)) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA), hptr2[0])); ++lptr2; ++hptr2; } } /* Apply the fourth lifting step. */ lptr = &a[0]; hptr = &a[llen * stride]; if (parity) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA), lptr2[0])); ++hptr2; ++lptr2; } hptr += stride; } n = numrows - llen - parity - (parity == (numrows & 1)); while (n-- > 0) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA), jpc_fix_add(lptr2[0], lptr2[stride]))); ++lptr2; ++hptr2; } hptr += stride; lptr += stride; } if (parity == (numrows & 1)) { lptr2 = lptr; hptr2 = hptr; for (i = 0; i < numcols; ++i) { jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA), lptr2[0])); ++lptr2; ++hptr2; } } } else { #if defined(WT_LENONE) if (parity) { lptr2 = &a[0]; for (i = 0; i < numcols; ++i) { lptr2[0] = jpc_fix_asr(lptr2[0], 1); ++lptr2; } } #endif } } Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec that was caused by a buffer being allocated with a size that was too small in some cases. Added a new regression test case. CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool TypedUrlModelAssociator::AssociateModels() { VLOG(1) << "Associating TypedUrl Models"; DCHECK(expected_loop_ == MessageLoop::current()); std::vector<history::URLRow> typed_urls; if (!history_backend_->GetAllTypedURLs(&typed_urls)) { LOG(ERROR) << "Could not get the typed_url entries."; return false; } std::map<history::URLID, history::VisitVector> visit_vectors; for (std::vector<history::URLRow>::iterator ix = typed_urls.begin(); ix != typed_urls.end(); ++ix) { if (!history_backend_->GetVisitsForURL(ix->id(), &(visit_vectors[ix->id()]))) { LOG(ERROR) << "Could not get the url's visits."; return false; } if (visit_vectors[ix->id()].empty()) { history::VisitRow visit( ix->id(), ix->last_visit(), 0, PageTransition::TYPED, 0); visit_vectors[ix->id()].push_back(visit); } } TypedUrlTitleVector titles; TypedUrlVector new_urls; TypedUrlVisitVector new_visits; TypedUrlUpdateVector updated_urls; { sync_api::WriteTransaction trans(sync_service_->GetUserShare()); sync_api::ReadNode typed_url_root(&trans); if (!typed_url_root.InitByTagLookup(kTypedUrlTag)) { LOG(ERROR) << "Server did not create the top-level typed_url node. We " << "might be running against an out-of-date server."; return false; } std::set<std::string> current_urls; for (std::vector<history::URLRow>::iterator ix = typed_urls.begin(); ix != typed_urls.end(); ++ix) { std::string tag = ix->url().spec(); history::VisitVector& visits = visit_vectors[ix->id()]; sync_api::ReadNode node(&trans); if (node.InitByClientTagLookup(syncable::TYPED_URLS, tag)) { const sync_pb::TypedUrlSpecifics& typed_url( node.GetTypedUrlSpecifics()); DCHECK_EQ(tag, typed_url.url()); history::URLRow new_url(*ix); std::vector<history::VisitInfo> added_visits; int difference = MergeUrls(typed_url, *ix, &visits, &new_url, &added_visits); if (difference & DIFF_UPDATE_NODE) { sync_api::WriteNode write_node(&trans); if (!write_node.InitByClientTagLookup(syncable::TYPED_URLS, tag)) { LOG(ERROR) << "Failed to edit typed_url sync node."; return false; } if (typed_url.visits_size() > 0) { base::Time earliest_visit = base::Time::FromInternalValue(typed_url.visits(0)); for (history::VisitVector::iterator it = visits.begin(); it != visits.end() && it->visit_time < earliest_visit; ) { it = visits.erase(it); } DCHECK(visits.size() > 0); } else { NOTREACHED() << "Syncing typed URL with no visits: " << typed_url.url(); } WriteToSyncNode(new_url, visits, &write_node); } if (difference & DIFF_LOCAL_TITLE_CHANGED) { titles.push_back(std::pair<GURL, string16>(new_url.url(), new_url.title())); } if (difference & DIFF_LOCAL_ROW_CHANGED) { updated_urls.push_back( std::pair<history::URLID, history::URLRow>(ix->id(), new_url)); } if (difference & DIFF_LOCAL_VISITS_ADDED) { new_visits.push_back( std::pair<GURL, std::vector<history::VisitInfo> >(ix->url(), added_visits)); } Associate(&tag, node.GetId()); } else { sync_api::WriteNode node(&trans); if (!node.InitUniqueByCreation(syncable::TYPED_URLS, typed_url_root, tag)) { LOG(ERROR) << "Failed to create typed_url sync node."; return false; } node.SetTitle(UTF8ToWide(tag)); WriteToSyncNode(*ix, visits, &node); Associate(&tag, node.GetId()); } current_urls.insert(tag); } int64 sync_child_id = typed_url_root.GetFirstChildId(); while (sync_child_id != sync_api::kInvalidId) { sync_api::ReadNode sync_child_node(&trans); if (!sync_child_node.InitByIdLookup(sync_child_id)) { LOG(ERROR) << "Failed to fetch child node."; return false; } const sync_pb::TypedUrlSpecifics& typed_url( sync_child_node.GetTypedUrlSpecifics()); if (current_urls.find(typed_url.url()) == current_urls.end()) { new_visits.push_back( std::pair<GURL, std::vector<history::VisitInfo> >( GURL(typed_url.url()), std::vector<history::VisitInfo>())); std::vector<history::VisitInfo>& visits = new_visits.back().second; history::URLRow new_url(GURL(typed_url.url())); TypedUrlModelAssociator::UpdateURLRowFromTypedUrlSpecifics( typed_url, &new_url); for (int c = 0; c < typed_url.visits_size(); ++c) { DCHECK(c == 0 || typed_url.visits(c) > typed_url.visits(c - 1)); DCHECK_LE(typed_url.visit_transitions(c), static_cast<int>(PageTransition::LAST_CORE)); visits.push_back(history::VisitInfo( base::Time::FromInternalValue(typed_url.visits(c)), static_cast<PageTransition::Type>( typed_url.visit_transitions(c)))); } Associate(&typed_url.url(), sync_child_node.GetId()); new_urls.push_back(new_url); } sync_child_id = sync_child_node.GetSuccessorId(); } } return WriteToHistoryBackend(&titles, &new_urls, &updated_urls, &new_visits, NULL); } Commit Message: Now ignores obsolete sync nodes without visit transitions. Also removed assertion that was erroneously triggered by obsolete sync nodes. BUG=none TEST=run chrome against a database that contains obsolete typed url sync nodes. Review URL: http://codereview.chromium.org/7129069 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88846 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DirectoryEntrySync* DirectoryEntrySync::getDirectory(const String& path, const Dictionary& options, ExceptionState& exceptionState) { FileSystemFlags flags(options); RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create(); m_fileSystem->getDirectory(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return static_cast<DirectoryEntrySync*>(helper->getResult(exceptionState)); } 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 Target: 1 Example 2: Code: void TabLifecycleUnitSource::TabLifecycleUnit::DidStartLoading() { if (IsDiscardedOrPendingDiscard(GetState())) SetState(LifecycleUnitState::ACTIVE, StateChangeReason::BROWSER_INITIATED); } 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 <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx) { BN_CTX *new_ctx = NULL; const EC_POINT *generator = NULL; EC_POINT *tmp = NULL; size_t totalnum; size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */ size_t pre_points_per_block = 0; size_t i, j; int k; int r_is_inverted = 0; int r_is_at_infinity = 1; size_t *wsize = NULL; /* individual window sizes */ signed char **wNAF = NULL; /* individual wNAFs */ size_t *wNAF_len = NULL; size_t max_len = 0; size_t num_val; EC_POINT **val = NULL; /* precomputation */ EC_POINT **v; EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or * 'pre_comp->points' */ const EC_PRE_COMP *pre_comp = NULL; int num_scalar = 0; /* flag: will be set to 1 if 'scalar' must be * treated like other scalars, i.e. * precomputation is not available */ int ret = 0; if (!ec_point_is_compat(r, group)) { ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS); return 0; } if ((scalar == NULL) && (num == 0)) { return EC_POINT_set_to_infinity(group, r); } if (!BN_is_zero(group->order) && !BN_is_zero(group->cofactor)) { /*- * Handle the common cases where the scalar is secret, enforcing a constant * time scalar multiplication algorithm. */ if ((scalar != NULL) && (num == 0)) { /*- * In this case we want to compute scalar * GeneratorPoint: this * codepath is reached most prominently by (ephemeral) key generation * of EC cryptosystems (i.e. ECDSA keygen and sign setup, ECDH * keygen/first half), where the scalar is always secret. This is why * we ignore if BN_FLG_CONSTTIME is actually set and we always call the * constant time version. */ return ec_mul_consttime(group, r, scalar, NULL, ctx); } if ((scalar == NULL) && (num == 1)) { /*- * In this case we want to compute scalar * GenericPoint: this codepath * is reached most prominently by the second half of ECDH, where the * secret scalar is multiplied by the peer's public point. To protect * the secret scalar, we ignore if BN_FLG_CONSTTIME is actually set and * we always call the constant time version. */ return ec_mul_consttime(group, r, scalars[0], points[0], ctx); } } for (i = 0; i < num; i++) { if (!ec_point_is_compat(points[i], group)) { ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS); return 0; } } if (ctx == NULL) { ctx = new_ctx = BN_CTX_new(); if (ctx == NULL) goto err; } if (scalar != NULL) { generator = EC_GROUP_get0_generator(group); if (generator == NULL) { ECerr(EC_F_EC_WNAF_MUL, EC_R_UNDEFINED_GENERATOR); goto err; } /* look if we can use precomputed multiples of generator */ pre_comp = group->pre_comp.ec; if (pre_comp && pre_comp->numblocks && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) == 0)) { blocksize = pre_comp->blocksize; /* * determine maximum number of blocks that wNAF splitting may * yield (NB: maximum wNAF length is bit length plus one) */ numblocks = (BN_num_bits(scalar) / blocksize) + 1; /* * we cannot use more blocks than we have precomputation for */ if (numblocks > pre_comp->numblocks) numblocks = pre_comp->numblocks; pre_points_per_block = (size_t)1 << (pre_comp->w - 1); /* check that pre_comp looks sane */ if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR); goto err; } } else { /* can't use precomputation */ pre_comp = NULL; numblocks = 1; num_scalar = 1; /* treat 'scalar' like 'num'-th element of * 'scalars' */ } } totalnum = num + numblocks; wsize = OPENSSL_malloc(totalnum * sizeof(wsize[0])); wNAF_len = OPENSSL_malloc(totalnum * sizeof(wNAF_len[0])); /* include space for pivot */ wNAF = OPENSSL_malloc((totalnum + 1) * sizeof(wNAF[0])); val_sub = OPENSSL_malloc(totalnum * sizeof(val_sub[0])); /* Ensure wNAF is initialised in case we end up going to err */ if (wNAF != NULL) wNAF[0] = NULL; /* preliminary pivot */ if (wsize == NULL || wNAF_len == NULL || wNAF == NULL || val_sub == NULL) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE); goto err; } /* * num_val will be the total number of temporarily precomputed points */ num_val = 0; for (i = 0; i < num + num_scalar; i++) { size_t bits; bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar); wsize[i] = EC_window_bits_for_scalar_size(bits); num_val += (size_t)1 << (wsize[i] - 1); wNAF[i + 1] = NULL; /* make sure we always have a pivot */ wNAF[i] = bn_compute_wNAF((i < num ? scalars[i] : scalar), wsize[i], &wNAF_len[i]); if (wNAF[i] == NULL) goto err; if (wNAF_len[i] > max_len) max_len = wNAF_len[i]; } if (numblocks) { /* we go here iff scalar != NULL */ if (pre_comp == NULL) { if (num_scalar != 1) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR); goto err; } /* we have already generated a wNAF for 'scalar' */ } else { signed char *tmp_wNAF = NULL; size_t tmp_len = 0; if (num_scalar != 0) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR); goto err; } /* * use the window size for which we have precomputation */ wsize[num] = pre_comp->w; tmp_wNAF = bn_compute_wNAF(scalar, wsize[num], &tmp_len); if (!tmp_wNAF) goto err; if (tmp_len <= max_len) { /* * One of the other wNAFs is at least as long as the wNAF * belonging to the generator, so wNAF splitting will not buy * us anything. */ numblocks = 1; totalnum = num + 1; /* don't use wNAF splitting */ wNAF[num] = tmp_wNAF; wNAF[num + 1] = NULL; wNAF_len[num] = tmp_len; /* * pre_comp->points starts with the points that we need here: */ val_sub[num] = pre_comp->points; } else { /* * don't include tmp_wNAF directly into wNAF array - use wNAF * splitting and include the blocks */ signed char *pp; EC_POINT **tmp_points; if (tmp_len < numblocks * blocksize) { /* * possibly we can do with fewer blocks than estimated */ numblocks = (tmp_len + blocksize - 1) / blocksize; if (numblocks > pre_comp->numblocks) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR); OPENSSL_free(tmp_wNAF); goto err; } totalnum = num + numblocks; } /* split wNAF in 'numblocks' parts */ pp = tmp_wNAF; tmp_points = pre_comp->points; for (i = num; i < totalnum; i++) { if (i < totalnum - 1) { wNAF_len[i] = blocksize; if (tmp_len < blocksize) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR); OPENSSL_free(tmp_wNAF); goto err; } tmp_len -= blocksize; } else /* * last block gets whatever is left (this could be * more or less than 'blocksize'!) */ wNAF_len[i] = tmp_len; wNAF[i + 1] = NULL; wNAF[i] = OPENSSL_malloc(wNAF_len[i]); if (wNAF[i] == NULL) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE); OPENSSL_free(tmp_wNAF); goto err; } memcpy(wNAF[i], pp, wNAF_len[i]); if (wNAF_len[i] > max_len) max_len = wNAF_len[i]; if (*tmp_points == NULL) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR); OPENSSL_free(tmp_wNAF); goto err; } val_sub[i] = tmp_points; tmp_points += pre_points_per_block; pp += blocksize; } OPENSSL_free(tmp_wNAF); } } } /* * All points we precompute now go into a single array 'val'. * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a * subarray of 'pre_comp->points' if we already have precomputation. */ val = OPENSSL_malloc((num_val + 1) * sizeof(val[0])); if (val == NULL) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE); goto err; } val[num_val] = NULL; /* pivot element */ /* allocate points for precomputation */ v = val; for (i = 0; i < num + num_scalar; i++) { val_sub[i] = v; for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) { *v = EC_POINT_new(group); if (*v == NULL) goto err; v++; } } if (!(v == val + num_val)) { ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR); goto err; } if ((tmp = EC_POINT_new(group)) == NULL) goto err; /*- * prepare precomputed values: * val_sub[i][0] := points[i] * val_sub[i][1] := 3 * points[i] * val_sub[i][2] := 5 * points[i] * ... */ for (i = 0; i < num + num_scalar; i++) { if (i < num) { if (!EC_POINT_copy(val_sub[i][0], points[i])) goto err; } else { if (!EC_POINT_copy(val_sub[i][0], generator)) goto err; } if (wsize[i] > 1) { if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx)) goto err; for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) { if (!EC_POINT_add (group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx)) goto err; } } } if (!EC_POINTs_make_affine(group, num_val, val, ctx)) goto err; r_is_at_infinity = 1; for (k = max_len - 1; k >= 0; k--) { if (!r_is_at_infinity) { if (!EC_POINT_dbl(group, r, r, ctx)) goto err; } for (i = 0; i < totalnum; i++) { if (wNAF_len[i] > (size_t)k) { int digit = wNAF[i][k]; int is_neg; if (digit) { is_neg = digit < 0; if (is_neg) digit = -digit; if (is_neg != r_is_inverted) { if (!r_is_at_infinity) { if (!EC_POINT_invert(group, r, ctx)) goto err; } r_is_inverted = !r_is_inverted; } /* digit > 0 */ if (r_is_at_infinity) { if (!EC_POINT_copy(r, val_sub[i][digit >> 1])) goto err; r_is_at_infinity = 0; } else { if (!EC_POINT_add (group, r, r, val_sub[i][digit >> 1], ctx)) goto err; } } } } } if (r_is_at_infinity) { if (!EC_POINT_set_to_infinity(group, r)) goto err; } else { if (r_is_inverted) if (!EC_POINT_invert(group, r, ctx)) goto err; } ret = 1; err: BN_CTX_free(new_ctx); EC_POINT_free(tmp); OPENSSL_free(wsize); OPENSSL_free(wNAF_len); if (wNAF != NULL) { signed char **w; for (w = wNAF; *w != NULL; w++) OPENSSL_free(*w); OPENSSL_free(wNAF); } if (val != NULL) { for (v = val; *v != NULL; v++) EC_POINT_clear_free(*v); OPENSSL_free(val); } OPENSSL_free(val_sub); return ret; } Commit Message: CWE ID: CWE-320 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: yyparse (void *yyscanner, YR_COMPILER* compiler) { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, yyscanner, compiler); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 8: #line 230 "grammar.y" /* yacc.c:1646 */ { int result = yr_parser_reduce_import(yyscanner, (yyvsp[0].sized_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF(result != ERROR_SUCCESS); } #line 1661 "grammar.c" /* yacc.c:1646 */ break; case 9: #line 242 "grammar.y" /* yacc.c:1646 */ { YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1( yyscanner, (int32_t) (yyvsp[-2].integer), (yyvsp[0].c_string)); ERROR_IF(rule == NULL); (yyval.rule) = rule; } #line 1674 "grammar.c" /* yacc.c:1646 */ break; case 10: #line 251 "grammar.y" /* yacc.c:1646 */ { YR_RULE* rule = (yyvsp[-4].rule); // rule created in phase 1 rule->tags = (yyvsp[-3].c_string); rule->metas = (yyvsp[-1].meta); rule->strings = (yyvsp[0].string); } #line 1686 "grammar.c" /* yacc.c:1646 */ break; case 11: #line 259 "grammar.y" /* yacc.c:1646 */ { YR_RULE* rule = (yyvsp[-7].rule); // rule created in phase 1 compiler->last_result = yr_parser_reduce_rule_declaration_phase_2( yyscanner, rule); yr_free((yyvsp[-8].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1701 "grammar.c" /* yacc.c:1646 */ break; case 12: #line 274 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = NULL; } #line 1709 "grammar.c" /* yacc.c:1646 */ break; case 13: #line 278 "grammar.y" /* yacc.c:1646 */ { YR_META null_meta; memset(&null_meta, 0xFF, sizeof(YR_META)); null_meta.type = META_TYPE_NULL; compiler->last_result = yr_arena_write_data( compiler->metas_arena, &null_meta, sizeof(YR_META), NULL); (yyval.meta) = (yyvsp[0].meta); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1736 "grammar.c" /* yacc.c:1646 */ break; case 14: #line 305 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = NULL; } #line 1744 "grammar.c" /* yacc.c:1646 */ break; case 15: #line 309 "grammar.y" /* yacc.c:1646 */ { YR_STRING null_string; memset(&null_string, 0xFF, sizeof(YR_STRING)); null_string.g_flags = STRING_GFLAGS_NULL; compiler->last_result = yr_arena_write_data( compiler->strings_arena, &null_string, sizeof(YR_STRING), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.string) = (yyvsp[0].string); } #line 1771 "grammar.c" /* yacc.c:1646 */ break; case 17: #line 340 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = 0; } #line 1777 "grammar.c" /* yacc.c:1646 */ break; case 18: #line 341 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 1783 "grammar.c" /* yacc.c:1646 */ break; case 19: #line 346 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = RULE_GFLAGS_PRIVATE; } #line 1789 "grammar.c" /* yacc.c:1646 */ break; case 20: #line 347 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = RULE_GFLAGS_GLOBAL; } #line 1795 "grammar.c" /* yacc.c:1646 */ break; case 21: #line 353 "grammar.y" /* yacc.c:1646 */ { (yyval.c_string) = NULL; } #line 1803 "grammar.c" /* yacc.c:1646 */ break; case 22: #line 357 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, "", NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[0].c_string); } #line 1821 "grammar.c" /* yacc.c:1646 */ break; case 23: #line 375 "grammar.y" /* yacc.c:1646 */ { char* identifier; compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), &identifier); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = identifier; } #line 1838 "grammar.c" /* yacc.c:1646 */ break; case 24: #line 388 "grammar.y" /* yacc.c:1646 */ { char* tag_name = (yyvsp[-1].c_string); size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0; while (tag_length > 0) { if (strcmp(tag_name, (yyvsp[0].c_string)) == 0) { yr_compiler_set_error_extra_info(compiler, tag_name); compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER; break; } tag_name = (char*) yr_arena_next_address( yyget_extra(yyscanner)->sz_arena, tag_name, tag_length + 1); tag_length = tag_name != NULL ? strlen(tag_name) : 0; } if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), NULL); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-1].c_string); } #line 1874 "grammar.c" /* yacc.c:1646 */ break; case 25: #line 424 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = (yyvsp[0].meta); } #line 1880 "grammar.c" /* yacc.c:1646 */ break; case 26: #line 425 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = (yyvsp[-1].meta); } #line 1886 "grammar.c" /* yacc.c:1646 */ break; case 27: #line 431 "grammar.y" /* yacc.c:1646 */ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_STRING, (yyvsp[-2].c_string), sized_string->c_string, 0); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.meta) == NULL); } #line 1906 "grammar.c" /* yacc.c:1646 */ break; case 28: #line 447 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-2].c_string), NULL, (yyvsp[0].integer)); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1923 "grammar.c" /* yacc.c:1646 */ break; case 29: #line 460 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-3].c_string), NULL, -(yyvsp[0].integer)); yr_free((yyvsp[-3].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1940 "grammar.c" /* yacc.c:1646 */ break; case 30: #line 473 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, TRUE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1957 "grammar.c" /* yacc.c:1646 */ break; case 31: #line 486 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, FALSE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1974 "grammar.c" /* yacc.c:1646 */ break; case 32: #line 502 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = (yyvsp[0].string); } #line 1980 "grammar.c" /* yacc.c:1646 */ break; case 33: #line 503 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = (yyvsp[-1].string); } #line 1986 "grammar.c" /* yacc.c:1646 */ break; case 34: #line 509 "grammar.y" /* yacc.c:1646 */ { compiler->error_line = yyget_lineno(yyscanner); } #line 1994 "grammar.c" /* yacc.c:1646 */ break; case 35: #line 513 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer), (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2009 "grammar.c" /* yacc.c:1646 */ break; case 36: #line 524 "grammar.y" /* yacc.c:1646 */ { compiler->error_line = yyget_lineno(yyscanner); } #line 2017 "grammar.c" /* yacc.c:1646 */ break; case 37: #line 528 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer) | STRING_GFLAGS_REGEXP, (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2033 "grammar.c" /* yacc.c:1646 */ break; case 38: #line 540 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, STRING_GFLAGS_HEXADECIMAL, (yyvsp[-2].c_string), (yyvsp[0].sized_string)); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.string) == NULL); } #line 2047 "grammar.c" /* yacc.c:1646 */ break; case 39: #line 553 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = 0; } #line 2053 "grammar.c" /* yacc.c:1646 */ break; case 40: #line 554 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 2059 "grammar.c" /* yacc.c:1646 */ break; case 41: #line 559 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = STRING_GFLAGS_WIDE; } #line 2065 "grammar.c" /* yacc.c:1646 */ break; case 42: #line 560 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = STRING_GFLAGS_ASCII; } #line 2071 "grammar.c" /* yacc.c:1646 */ break; case 43: #line 561 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = STRING_GFLAGS_NO_CASE; } #line 2077 "grammar.c" /* yacc.c:1646 */ break; case 44: #line 562 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = STRING_GFLAGS_FULL_WORD; } #line 2083 "grammar.c" /* yacc.c:1646 */ break; case 45: #line 568 "grammar.y" /* yacc.c:1646 */ { int var_index = yr_parser_lookup_loop_variable(yyscanner, (yyvsp[0].c_string)); if (var_index >= 0) { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, LOOP_LOCAL_VARS * var_index, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = compiler->loop_identifier[var_index]; } else { YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), NULL); if (object == NULL) { char* ns = compiler->current_namespace->name; object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), ns); } if (object != NULL) { char* id; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &id); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_LOAD, id, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = object; (yyval.expression).identifier = object->identifier; } else { YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup( compiler->rules_table, (yyvsp[0].c_string), compiler->current_namespace->name); if (rule != NULL) { compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH_RULE, rule, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = rule->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_UNDEFINED_IDENTIFIER; } } } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2172 "grammar.c" /* yacc.c:1646 */ break; case 46: #line 653 "grammar.y" /* yacc.c:1646 */ { YR_OBJECT* field = NULL; if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-2].expression).value.object->type == OBJECT_TYPE_STRUCTURE) { field = yr_object_lookup_field((yyvsp[-2].expression).value.object, (yyvsp[0].c_string)); if (field != NULL) { char* ident; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &ident); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_FIELD, ident, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = field; (yyval.expression).identifier = field->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_INVALID_FIELD_NAME; } } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-2].expression).identifier); compiler->last_result = ERROR_NOT_A_STRUCTURE; } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2222 "grammar.c" /* yacc.c:1646 */ break; case 47: #line 699 "grammar.y" /* yacc.c:1646 */ { YR_OBJECT_ARRAY* array; YR_OBJECT_DICTIONARY* dict; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_ARRAY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "array indexes must be of integer type"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_INDEX_ARRAY, NULL); array = (YR_OBJECT_ARRAY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = array->prototype_item; (yyval.expression).identifier = array->identifier; } else if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_DICTIONARY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_STRING) { yr_compiler_set_error_extra_info( compiler, "dictionary keys must be of string type"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_LOOKUP_DICT, NULL); dict = (YR_OBJECT_DICTIONARY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = dict->prototype_item; (yyval.expression).identifier = dict->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_INDEXABLE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2283 "grammar.c" /* yacc.c:1646 */ break; case 48: #line 757 "grammar.y" /* yacc.c:1646 */ { YR_OBJECT_FUNCTION* function; char* args_fmt; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_FUNCTION) { compiler->last_result = yr_parser_check_types( compiler, (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object, (yyvsp[-1].c_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[-1].c_string), &args_fmt); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_CALL, args_fmt, NULL, NULL); function = (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = function->return_obj; (yyval.expression).identifier = function->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_A_FUNCTION; } yr_free((yyvsp[-1].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2328 "grammar.c" /* yacc.c:1646 */ break; case 49: #line 801 "grammar.y" /* yacc.c:1646 */ { (yyval.c_string) = yr_strdup(""); } #line 2334 "grammar.c" /* yacc.c:1646 */ break; case 50: #line 802 "grammar.y" /* yacc.c:1646 */ { (yyval.c_string) = (yyvsp[0].c_string); } #line 2340 "grammar.c" /* yacc.c:1646 */ break; case 51: #line 807 "grammar.y" /* yacc.c:1646 */ { (yyval.c_string) = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1); switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcpy((yyval.c_string), "i", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcpy((yyval.c_string), "f", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcpy((yyval.c_string), "b", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcpy((yyval.c_string), "s", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcpy((yyval.c_string), "r", MAX_FUNCTION_ARGS); break; } ERROR_IF((yyval.c_string) == NULL); } #line 2369 "grammar.c" /* yacc.c:1646 */ break; case 52: #line 832 "grammar.y" /* yacc.c:1646 */ { if (strlen((yyvsp[-2].c_string)) == MAX_FUNCTION_ARGS) { compiler->last_result = ERROR_TOO_MANY_ARGUMENTS; } else { switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcat((yyvsp[-2].c_string), "i", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcat((yyvsp[-2].c_string), "f", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcat((yyvsp[-2].c_string), "b", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcat((yyvsp[-2].c_string), "s", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcat((yyvsp[-2].c_string), "r", MAX_FUNCTION_ARGS); break; } } ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-2].c_string); } #line 2405 "grammar.c" /* yacc.c:1646 */ break; case 53: #line 868 "grammar.y" /* yacc.c:1646 */ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); RE* re; RE_ERROR error; int re_flags = 0; if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE) re_flags |= RE_FLAGS_NO_CASE; if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL) re_flags |= RE_FLAGS_DOT_ALL; compiler->last_result = yr_re_compile( sized_string->c_string, re_flags, compiler->re_code_arena, &re, &error); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION) yr_compiler_set_error_extra_info(compiler, error.message); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, re->root_node->forward_code, NULL, NULL); yr_re_destroy(re); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_REGEXP; } #line 2451 "grammar.c" /* yacc.c:1646 */ break; case 54: #line 914 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_STRING) { if ((yyvsp[0].expression).value.sized_string != NULL) { yywarning(yyscanner, "Using literal string \"%s\" in a boolean operation.", (yyvsp[0].expression).value.sized_string->c_string); } compiler->last_result = yr_parser_emit( yyscanner, OP_STR_TO_BOOL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2474 "grammar.c" /* yacc.c:1646 */ break; case 55: #line 936 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2487 "grammar.c" /* yacc.c:1646 */ break; case 56: #line 945 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 0, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2500 "grammar.c" /* yacc.c:1646 */ break; case 57: #line 954 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, "matches"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_REGEXP, "matches"); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit( yyscanner, OP_MATCHES, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2519 "grammar.c" /* yacc.c:1646 */ break; case 58: #line 969 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, "contains"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_STRING, "contains"); compiler->last_result = yr_parser_emit( yyscanner, OP_CONTAINS, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2535 "grammar.c" /* yacc.c:1646 */ break; case 59: #line 981 "grammar.y" /* yacc.c:1646 */ { int result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_FOUND, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2553 "grammar.c" /* yacc.c:1646 */ break; case 60: #line 995 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "at"); compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_AT, (yyvsp[0].expression).value.integer); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2570 "grammar.c" /* yacc.c:1646 */ break; case 61: #line 1008 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_IN, UNDEFINED); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result!= ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2585 "grammar.c" /* yacc.c:1646 */ break; case 62: #line 1019 "grammar.y" /* yacc.c:1646 */ { int var_index; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; ERROR_IF(compiler->last_result != ERROR_SUCCESS); var_index = yr_parser_lookup_loop_variable( yyscanner, (yyvsp[-1].c_string)); if (var_index >= 0) { yr_compiler_set_error_extra_info( compiler, (yyvsp[-1].c_string)); compiler->last_result = \ ERROR_DUPLICATED_LOOP_IDENTIFIER; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2619 "grammar.c" /* yacc.c:1646 */ break; case 63: #line 1049 "grammar.y" /* yacc.c:1646 */ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-1].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); } else // INTEGER_SET_RANGE { yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL); yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, NULL, NULL); } compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = (yyvsp[-4].c_string); compiler->loop_depth++; } #line 2658 "grammar.c" /* yacc.c:1646 */ break; case 64: #line 1084 "grammar.y" /* yacc.c:1646 */ { int mem_offset; compiler->loop_depth--; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-5].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); } else // INTEGER_SET_RANGE { yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL); yr_parser_emit_with_arg_reloc( yyscanner, OP_JLE, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); } yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); compiler->loop_identifier[compiler->loop_depth] = NULL; yr_free((yyvsp[-8].c_string)); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2741 "grammar.c" /* yacc.c:1646 */ break; case 65: #line 1163 "grammar.y" /* yacc.c:1646 */ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; if (compiler->loop_for_of_mem_offset != -1) compiler->last_result = \ ERROR_NESTED_FOR_OF_LOOP; ERROR_IF(compiler->last_result != ERROR_SUCCESS); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); compiler->loop_for_of_mem_offset = mem_offset; compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = NULL; compiler->loop_depth++; } #line 2775 "grammar.c" /* yacc.c:1646 */ break; case 66: #line 1193 "grammar.y" /* yacc.c:1646 */ { int mem_offset; compiler->loop_depth--; compiler->loop_for_of_mem_offset = -1; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2828 "grammar.c" /* yacc.c:1646 */ break; case 67: #line 1242 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit(yyscanner, OP_OF, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2838 "grammar.c" /* yacc.c:1646 */ break; case 68: #line 1248 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit(yyscanner, OP_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2848 "grammar.c" /* yacc.c:1646 */ break; case 69: #line 1254 "grammar.y" /* yacc.c:1646 */ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JFALSE, 0, // still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2878 "grammar.c" /* yacc.c:1646 */ break; case 70: #line 1280 "grammar.y" /* yacc.c:1646 */ { YR_FIXUP* fixup; uint8_t* and_addr; compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = compiler->fixup_stack_head; *(void**)(fixup->address) = (void*)(and_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2918 "grammar.c" /* yacc.c:1646 */ break; case 71: #line 1316 "grammar.y" /* yacc.c:1646 */ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JTRUE, 0, // still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2947 "grammar.c" /* yacc.c:1646 */ break; case 72: #line 1341 "grammar.y" /* yacc.c:1646 */ { YR_FIXUP* fixup; uint8_t* or_addr; compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = compiler->fixup_stack_head; *(void**)(fixup->address) = (void*)(or_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2987 "grammar.c" /* yacc.c:1646 */ break; case 73: #line 1377 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "<", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3000 "grammar.c" /* yacc.c:1646 */ break; case 74: #line 1386 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, ">", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3013 "grammar.c" /* yacc.c:1646 */ break; case 75: #line 1395 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "<=", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3026 "grammar.c" /* yacc.c:1646 */ break; case 76: #line 1404 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, ">=", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3039 "grammar.c" /* yacc.c:1646 */ break; case 77: #line 1413 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "==", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3052 "grammar.c" /* yacc.c:1646 */ break; case 78: #line 1422 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "!=", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3065 "grammar.c" /* yacc.c:1646 */ break; case 79: #line 1431 "grammar.y" /* yacc.c:1646 */ { (yyval.expression) = (yyvsp[0].expression); } #line 3073 "grammar.c" /* yacc.c:1646 */ break; case 80: #line 1435 "grammar.y" /* yacc.c:1646 */ { (yyval.expression) = (yyvsp[-1].expression); } #line 3081 "grammar.c" /* yacc.c:1646 */ break; case 81: #line 1442 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = INTEGER_SET_ENUMERATION; } #line 3087 "grammar.c" /* yacc.c:1646 */ break; case 82: #line 1443 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = INTEGER_SET_RANGE; } #line 3093 "grammar.c" /* yacc.c:1646 */ break; case 83: #line 1449 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[-3].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "wrong type for range's lower bound"); compiler->last_result = ERROR_WRONG_TYPE; } if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "wrong type for range's upper bound"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3115 "grammar.c" /* yacc.c:1646 */ break; case 84: #line 1471 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "wrong type for enumeration item"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3131 "grammar.c" /* yacc.c:1646 */ break; case 85: #line 1483 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "wrong type for enumeration item"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3146 "grammar.c" /* yacc.c:1646 */ break; case 86: #line 1498 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3155 "grammar.c" /* yacc.c:1646 */ break; case 88: #line 1504 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); yr_parser_emit_pushes_for_strings(yyscanner, "$*"); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3166 "grammar.c" /* yacc.c:1646 */ break; case 91: #line 1521 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3177 "grammar.c" /* yacc.c:1646 */ break; case 92: #line 1528 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3188 "grammar.c" /* yacc.c:1646 */ break; case 94: #line 1540 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3196 "grammar.c" /* yacc.c:1646 */ break; case 95: #line 1544 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL); } #line 3204 "grammar.c" /* yacc.c:1646 */ break; case 96: #line 1552 "grammar.y" /* yacc.c:1646 */ { (yyval.expression) = (yyvsp[-1].expression); } #line 3212 "grammar.c" /* yacc.c:1646 */ break; case 97: #line 1556 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit( yyscanner, OP_FILESIZE, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3226 "grammar.c" /* yacc.c:1646 */ break; case 98: #line 1566 "grammar.y" /* yacc.c:1646 */ { yywarning(yyscanner, "Using deprecated \"entrypoint\" keyword. Use the \"entry_point\" " "function from PE module instead."); compiler->last_result = yr_parser_emit( yyscanner, OP_ENTRYPOINT, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3244 "grammar.c" /* yacc.c:1646 */ break; case 99: #line 1580 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-1].expression), EXPRESSION_TYPE_INTEGER, "intXXXX or uintXXXX"); compiler->last_result = yr_parser_emit( yyscanner, (uint8_t) (OP_READ_INT + (yyvsp[-3].integer)), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3264 "grammar.c" /* yacc.c:1646 */ break; case 100: #line 1596 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, (yyvsp[0].integer), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = (yyvsp[0].integer); } #line 3278 "grammar.c" /* yacc.c:1646 */ break; case 101: #line 1606 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg_double( yyscanner, OP_PUSH, (yyvsp[0].double_), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } #line 3291 "grammar.c" /* yacc.c:1646 */ break; case 102: #line 1615 "grammar.y" /* yacc.c:1646 */ { SIZED_STRING* sized_string; compiler->last_result = yr_arena_write_data( compiler->sz_arena, (yyvsp[0].sized_string), (yyvsp[0].sized_string)->length + sizeof(SIZED_STRING), (void**) &sized_string); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, sized_string, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = sized_string; } #line 3320 "grammar.c" /* yacc.c:1646 */ break; case 103: #line 1640 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_COUNT, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3336 "grammar.c" /* yacc.c:1646 */ break; case 104: #line 1652 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3352 "grammar.c" /* yacc.c:1646 */ break; case 105: #line 1664 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3372 "grammar.c" /* yacc.c:1646 */ break; case 106: #line 1680 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3388 "grammar.c" /* yacc.c:1646 */ break; case 107: #line 1692 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3408 "grammar.c" /* yacc.c:1646 */ break; case 108: #line 1708 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) // loop identifier { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_BOOLEAN) // rule identifier { (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_OBJECT) { compiler->last_result = yr_parser_emit( yyscanner, OP_OBJ_VALUE, NULL); switch((yyvsp[0].expression).value.object->type) { case OBJECT_TYPE_INTEGER: (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; break; case OBJECT_TYPE_FLOAT: (yyval.expression).type = EXPRESSION_TYPE_FLOAT; break; case OBJECT_TYPE_STRING: (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = NULL; break; default: yr_compiler_set_error_extra_info_fmt( compiler, "wrong usage of identifier \"%s\"", (yyvsp[0].expression).identifier); compiler->last_result = ERROR_WRONG_TYPE; } } else { assert(FALSE); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3457 "grammar.c" /* yacc.c:1646 */ break; case 109: #line 1753 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, "-"); if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : -((yyvsp[0].expression).value.integer); compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL); } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_FLOAT) { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3480 "grammar.c" /* yacc.c:1646 */ break; case 110: #line 1772 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "+", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(+, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3502 "grammar.c" /* yacc.c:1646 */ break; case 111: #line 1790 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "-", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(-, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3524 "grammar.c" /* yacc.c:1646 */ break; case 112: #line 1808 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "*", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(*, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3546 "grammar.c" /* yacc.c:1646 */ break; case 113: #line 1826 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "\\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(/, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3576 "grammar.c" /* yacc.c:1646 */ break; case 114: #line 1852 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "%"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "%"); yr_parser_emit(yyscanner, OP_MOD, NULL); if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(%, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } #line 3598 "grammar.c" /* yacc.c:1646 */ break; case 115: #line 1870 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "^"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "^"); yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(^, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3612 "grammar.c" /* yacc.c:1646 */ break; case 116: #line 1880 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "^"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "^"); yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(&, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3626 "grammar.c" /* yacc.c:1646 */ break; case 117: #line 1890 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "|"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "|"); yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(|, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3640 "grammar.c" /* yacc.c:1646 */ break; case 118: #line 1900 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "~"); yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : ~((yyvsp[0].expression).value.integer); } #line 3654 "grammar.c" /* yacc.c:1646 */ break; case 119: #line 1910 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "<<"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "<<"); yr_parser_emit(yyscanner, OP_SHL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(<<, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3668 "grammar.c" /* yacc.c:1646 */ break; case 120: #line 1920 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, ">>"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, ">>"); yr_parser_emit(yyscanner, OP_SHR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(>>, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3682 "grammar.c" /* yacc.c:1646 */ break; case 121: #line 1930 "grammar.y" /* yacc.c:1646 */ { (yyval.expression) = (yyvsp[0].expression); } #line 3690 "grammar.c" /* yacc.c:1646 */ break; #line 3694 "grammar.c" /* yacc.c:1646 */ default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (yyscanner, compiler, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yyscanner, compiler, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, yyscanner, compiler); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, yyscanner, compiler); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (yyscanner, compiler, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, yyscanner, compiler); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yyscanner, compiler); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } Commit Message: Fix issue #575 CWE ID: CWE-416 Target: 1 Example 2: Code: static void network_init_buffer (void) { memset (send_buffer, 0, network_config_packet_size); send_buffer_ptr = send_buffer; send_buffer_fill = 0; memset (&send_buffer_vl, 0, sizeof (send_buffer_vl)); } /* int network_init_buffer */ Commit Message: network plugin: Fix heap overflow in parse_packet(). Emilien Gaspar has identified a heap overflow in parse_packet(), the function used by the network plugin to parse incoming network packets. This is a vulnerability in collectd, though the scope is not clear at this point. At the very least specially crafted network packets can be used to crash the daemon. We can't rule out a potential remote code execution though. Fixes: CVE-2016-6254 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void cp2112_gpio_set(struct gpio_chip *chip, unsigned offset, int value) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; unsigned long flags; int ret; spin_lock_irqsave(&dev->lock, flags); buf[0] = CP2112_GPIO_SET; buf[1] = value ? 0xff : 0; buf[2] = 1 << offset; ret = hid_hw_raw_request(hdev, CP2112_GPIO_SET, buf, CP2112_GPIO_SET_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) hid_err(hdev, "error setting GPIO values: %d\n", ret); spin_unlock_irqrestore(&dev->lock, flags); } Commit Message: HID: cp2112: fix sleep-while-atomic A recent commit fixing DMA-buffers on stack added a shared transfer buffer protected by a spinlock. This is broken as the USB HID request callbacks can sleep. Fix this up by replacing the spinlock with a mutex. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <[email protected]> # 4.9 Signed-off-by: Johan Hovold <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-404 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WebSocketJob::Wakeup() { if (!waiting_) return; waiting_ = false; DCHECK(callback_); MessageLoopForIO::current()->PostTask( FROM_HERE, NewRunnableMethod(this, &WebSocketJob::RetryPendingIO)); } Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob Don't post SendPending if it is already posted. BUG=89795 TEST=none Review URL: http://codereview.chromium.org/7488007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: static int read_uint64(BlockDriverState *bs, int64_t offset, uint64_t *result) { uint64_t buffer; int ret; ret = bdrv_pread(bs->file, offset, &buffer, 8); if (ret < 0) { return ret; } *result = be64_to_cpu(buffer); return 0; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int Tar::ReadHeaders( void ) { FILE *in; TarHeader lHeader; TarRecord lRecord; unsigned int iBegData = 0; char buf_header[512]; in = fopen(mFilePath.fn_str(), "rb"); if(in == NULL) { wxLogFatalError(_("Error: File '%s' not found! Cannot read data."), mFilePath.c_str()); return 1; } wxString lDmodDizPath; mmDmodDescription = _T(""); mInstalledDmodDirectory = _T(""); int total_read = 0; while (true) { memset(&lHeader, 0, sizeof(TarHeader)); memset(&lRecord, 0, sizeof(TarRecord)); fread((char*)&lHeader.Name, 100, 1, in); fread((char*)&lHeader.Mode, 8, 1, in); fread((char*)&lHeader.Uid, 8, 1, in); fread((char*)&lHeader.Gid, 8, 1, in); fread((char*)&lHeader.Size, 12, 1, in); fread((char*)&lHeader.Mtime, 12, 1, in); fread((char*)&lHeader.Chksum, 8, 1, in); fread((char*)&lHeader.Linkflag, 1, 1, in); fread((char*)&lHeader.Linkname, 100, 1, in); fread((char*)&lHeader.Magic, 8, 1, in); fread((char*)&lHeader.Uname, 32, 1, in); fread((char*)&lHeader.Gname, 32, 1, in); fread((char*)&lHeader.Devmajor, 8, 1, in); fread((char*)&lHeader.Devminor, 8, 1, in); fread((char*)&lHeader.Padding, 167, 1, in); total_read += 512; if(!VerifyChecksum(&lHeader)) { wxLogFatalError(_("Error: This .dmod file has an invalid checksum! Cannot read file.")); return 1; } strncpy(lRecord.Name, lHeader.Name, 100); if (strcmp(lHeader.Name, "\xFF") == 0) continue; sscanf((const char*)&lHeader.Size, "%o", &lRecord.iFileSize); lRecord.iFilePosBegin = total_read; if(strcmp(lHeader.Name, "") == 0) { break; } wxString lPath(lRecord.Name, wxConvUTF8); wxString lPath(lRecord.Name, wxConvUTF8); if (mInstalledDmodDirectory.Length() == 0) { mInstalledDmodDirectory = lPath.SubString( 0, lPath.Find( '/' ) ); lDmodDizPath = mInstalledDmodDirectory + _T("dmod.diz"); lDmodDizPath.LowerCase(); } } else { int remaining = lRecord.iFileSize; char buf[BUFSIZ]; while (remaining > 0) { if (feof(in)) break; // TODO: error, unexpected end of file int nb_read = fread(buf, 1, (remaining > BUFSIZ) ? BUFSIZ : remaining, in); remaining -= nb_read; } } total_read += lRecord.iFileSize; TarRecords.push_back(lRecord); int padding_size = (512 - (total_read % 512)) % 512; fread(buf_header, 1, padding_size, in); total_read += padding_size; } Commit Message: CWE ID: CWE-22 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderViewTest::SetUp() { if (!GetContentClient()->renderer()) GetContentClient()->set_renderer(&mock_content_renderer_client_); if (!render_thread_.get()) render_thread_.reset(new MockRenderThread()); render_thread_->set_routing_id(kRouteId); render_thread_->set_surface_id(kSurfaceId); render_thread_->set_new_window_routing_id(kNewWindowRouteId); command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); params_.reset(new content::MainFunctionParams(*command_line_)); platform_.reset(new RendererMainPlatformDelegate(*params_)); platform_->PlatformInitialize(); webkit_glue::SetJavaScriptFlags(" --expose-gc"); WebKit::initialize(&webkit_platform_support_); mock_process_.reset(new MockRenderProcess); RenderViewImpl* view = RenderViewImpl::Create( 0, kOpenerId, content::RendererPreferences(), WebPreferences(), new SharedRenderViewCounter(0), kRouteId, kSurfaceId, kInvalidSessionStorageNamespaceId, string16(), 1, WebKit::WebScreenInfo(), false); view->AddRef(); view_ = view; mock_keyboard_.reset(new MockKeyboard()); } Commit Message: Use a new scheme for swapping out RenderViews. BUG=118664 TEST=none Review URL: http://codereview.chromium.org/9720004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "hvcC"); if (track->tag == MKTAG('h','v','c','1')) ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1); else ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0); return update_size(pb, pos); } Commit Message: avformat/movenc: Write version 2 of audio atom if channels is not known The version 1 needs the channel count and would divide by 0 Fixes: division by 0 Fixes: fpe_movenc.c_1108_1.ogg Fixes: fpe_movenc.c_1108_2.ogg Fixes: fpe_movenc.c_1108_3.wav Found-by: #CHEN HONGXU# <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-369 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MediaStreamDispatcherHost::~MediaStreamDispatcherHost() { DCHECK_CURRENTLY_ON(BrowserThread::IO); bindings_.CloseAllBindings(); CancelAllRequests(); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ethertype_print(netdissect_options *ndo, u_short ether_type, const u_char *p, u_int length, u_int caplen, const struct lladdr_info *src, const struct lladdr_info *dst) { switch (ether_type) { case ETHERTYPE_IP: ip_print(ndo, p, length); return (1); case ETHERTYPE_IPV6: ip6_print(ndo, p, length); return (1); case ETHERTYPE_ARP: case ETHERTYPE_REVARP: arp_print(ndo, p, length, caplen); return (1); case ETHERTYPE_DN: decnet_print(ndo, p, length, caplen); return (1); case ETHERTYPE_ATALK: if (ndo->ndo_vflag) ND_PRINT((ndo, "et1 ")); atalk_print(ndo, p, length); return (1); case ETHERTYPE_AARP: aarp_print(ndo, p, length); return (1); case ETHERTYPE_IPX: ND_PRINT((ndo, "(NOV-ETHII) ")); ipx_print(ndo, p, length); return (1); case ETHERTYPE_ISO: if (length == 0 || caplen == 0) { ND_PRINT((ndo, " [|osi]")); return (1); } isoclns_print(ndo, p + 1, length - 1, caplen - 1); return(1); case ETHERTYPE_PPPOED: case ETHERTYPE_PPPOES: case ETHERTYPE_PPPOED2: case ETHERTYPE_PPPOES2: pppoe_print(ndo, p, length); return (1); case ETHERTYPE_EAPOL: eap_print(ndo, p, length); return (1); case ETHERTYPE_RRCP: rrcp_print(ndo, p, length, src, dst); return (1); case ETHERTYPE_PPP: if (length) { ND_PRINT((ndo, ": ")); ppp_print(ndo, p, length); } return (1); case ETHERTYPE_MPCP: mpcp_print(ndo, p, length); return (1); case ETHERTYPE_SLOW: slow_print(ndo, p, length); return (1); case ETHERTYPE_CFM: case ETHERTYPE_CFM_OLD: cfm_print(ndo, p, length); return (1); case ETHERTYPE_LLDP: lldp_print(ndo, p, length); return (1); case ETHERTYPE_NSH: nsh_print(ndo, p, length); return (1); case ETHERTYPE_LOOPBACK: loopback_print(ndo, p, length); return (1); case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); return (1); case ETHERTYPE_TIPC: tipc_print(ndo, p, length, caplen); return (1); case ETHERTYPE_MS_NLB_HB: msnlb_print(ndo, p); return (1); case ETHERTYPE_GEONET_OLD: case ETHERTYPE_GEONET: geonet_print(ndo, p, length, src); return (1); case ETHERTYPE_CALM_FAST: calm_fast_print(ndo, p, length, src); return (1); case ETHERTYPE_AOE: aoe_print(ndo, p, length); return (1); case ETHERTYPE_MEDSA: medsa_print(ndo, p, length, caplen, src, dst); return (1); case ETHERTYPE_LAT: case ETHERTYPE_SCA: case ETHERTYPE_MOPRC: case ETHERTYPE_MOPDL: case ETHERTYPE_IEEE1905_1: /* default_print for now */ default: return (0); } } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: void AXObjectCacheImpl::handleInitialFocus() { postNotification(m_document, AXObjectCache::AXFocusedUIElementChanged); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int get_bitmap_file(struct mddev *mddev, void __user * arg) { mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */ char *ptr; int err; file = kmalloc(sizeof(*file), GFP_NOIO); if (!file) return -ENOMEM; err = 0; spin_lock(&mddev->lock); /* bitmap disabled, zero the first byte and copy out */ if (!mddev->bitmap_info.file) file->pathname[0] = '\0'; else if ((ptr = file_path(mddev->bitmap_info.file, file->pathname, sizeof(file->pathname))), IS_ERR(ptr)) err = PTR_ERR(ptr); else memmove(file->pathname, ptr, sizeof(file->pathname)-(ptr-file->pathname)); spin_unlock(&mddev->lock); if (err == 0 && copy_to_user(arg, file, sizeof(*file))) err = -EFAULT; kfree(file); return err; } Commit Message: md: use kzalloc() when bitmap is disabled In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a mdu_bitmap_file_t called "file". 5769 file = kmalloc(sizeof(*file), GFP_NOIO); 5770 if (!file) 5771 return -ENOMEM; This structure is copied to user space at the end of the function. 5786 if (err == 0 && 5787 copy_to_user(arg, file, sizeof(*file))) 5788 err = -EFAULT But if bitmap is disabled only the first byte of "file" is initialized with zero, so it's possible to read some bytes (up to 4095) of kernel space memory from user space. This is an information leak. 5775 /* bitmap disabled, zero the first byte and copy out */ 5776 if (!mddev->bitmap_info.file) 5777 file->pathname[0] = '\0'; Signed-off-by: Benjamin Randazzo <[email protected]> Signed-off-by: NeilBrown <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset) { __wsum csum = skb->csum; if (skb->ip_summed != CHECKSUM_COMPLETE) return; if (offset != 0) csum = csum_sub(csum, csum_partial(skb_transport_header(skb) + tlen, offset, 0)); put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); } Commit Message: ip: fix IP_CHECKSUM handling The skbs processed by ip_cmsg_recv() are not guaranteed to be linear e.g. when sending UDP packets over loopback with MSGMORE. Using csum_partial() on [potentially] the whole skb len is dangerous; instead be on the safe side and use skb_checksum(). Thanks to syzkaller team to detect the issue and provide the reproducer. v1 -> v2: - move the variable declaration in a tighter scope Fixes: ad6f939ab193 ("ip: Add offset parameter to ip_cmsg_recv") Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Paolo Abeni <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: static int set_sig_umr_wr(const struct ib_send_wr *send_wr, struct mlx5_ib_qp *qp, void **seg, int *size) { const struct ib_sig_handover_wr *wr = sig_handover_wr(send_wr); struct mlx5_ib_mr *sig_mr = to_mmr(wr->sig_mr); u32 pdn = get_pd(qp)->pdn; u32 xlt_size; int region_len, ret; if (unlikely(wr->wr.num_sge != 1) || unlikely(wr->access_flags & IB_ACCESS_REMOTE_ATOMIC) || unlikely(!sig_mr->sig) || unlikely(!qp->signature_en) || unlikely(!sig_mr->sig->sig_status_checked)) return -EINVAL; /* length of the protected region, data + protection */ region_len = wr->wr.sg_list->length; if (wr->prot && (wr->prot->lkey != wr->wr.sg_list->lkey || wr->prot->addr != wr->wr.sg_list->addr || wr->prot->length != wr->wr.sg_list->length)) region_len += wr->prot->length; /** * KLM octoword size - if protection was provided * then we use strided block format (3 octowords), * else we use single KLM (1 octoword) **/ xlt_size = wr->prot ? 0x30 : sizeof(struct mlx5_klm); set_sig_umr_segment(*seg, xlt_size); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_sig_mkey_segment(*seg, wr, xlt_size, region_len, pdn); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); ret = set_sig_data_segment(wr, qp, seg, size); if (ret) return ret; sig_mr->sig->sig_status_checked = false; return 0; } Commit Message: IB/mlx5: Fix leaking stack memory to userspace mlx5_ib_create_qp_resp was never initialized and only the first 4 bytes were written. Fixes: 41d902cb7c32 ("RDMA/mlx5: Fix definition of mlx5_ib_create_qp_resp") Cc: <[email protected]> Acked-by: Leon Romanovsky <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: v8::Local<v8::Context> V8Debugger::debuggerContext() const { DCHECK(!m_debuggerContext.IsEmpty()); return m_debuggerContext.Get(m_isolate); } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel) { if (parcel == NULL) { return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); const size_t size = p->readInt32(); const void* regionData = p->readInplace(size); if (regionData == NULL) { return NULL; } SkRegion* region = new SkRegion; region->readFromMemory(regionData, size); return reinterpret_cast<jlong>(region); } Commit Message: DO NOT MERGE: Ensure that unparcelling Region only reads the expected number of bytes bug: 20883006 Change-Id: I4f109667fb210a80fbddddf5f1bfb7ef3a02b6ce CWE ID: CWE-264 Target: 1 Example 2: Code: channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset) { FD_SET(c->sock, readset); } Commit Message: CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int tcp_disconnect(struct sock *sk, int flags) { struct inet_sock *inet = inet_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int err = 0; int old_state = sk->sk_state; if (old_state != TCP_CLOSE) tcp_set_state(sk, TCP_CLOSE); /* ABORT function of RFC793 */ if (old_state == TCP_LISTEN) { inet_csk_listen_stop(sk); } else if (unlikely(tp->repair)) { sk->sk_err = ECONNABORTED; } else if (tcp_need_reset(old_state) || (tp->snd_nxt != tp->write_seq && (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) { /* The last check adjusts for discrepancy of Linux wrt. RFC * states */ tcp_send_active_reset(sk, gfp_any()); sk->sk_err = ECONNRESET; } else if (old_state == TCP_SYN_SENT) sk->sk_err = ECONNRESET; tcp_clear_xmit_timers(sk); __skb_queue_purge(&sk->sk_receive_queue); tcp_write_queue_purge(sk); tcp_fastopen_active_disable_ofo_check(sk); skb_rbtree_purge(&tp->out_of_order_queue); inet->inet_dport = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); sk->sk_shutdown = 0; sock_reset_flag(sk, SOCK_DONE); tp->srtt_us = 0; tp->write_seq += tp->max_window + 2; if (tp->write_seq == 0) tp->write_seq = 1; icsk->icsk_backoff = 0; tp->snd_cwnd = 2; icsk->icsk_probes_out = 0; tp->packets_out = 0; tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; tp->snd_cwnd_cnt = 0; tp->window_clamp = 0; tcp_set_ca_state(sk, TCP_CA_Open); tcp_clear_retrans(tp); inet_csk_delack_init(sk); tcp_init_send_head(sk); memset(&tp->rx_opt, 0, sizeof(tp->rx_opt)); __sk_dst_reset(sk); tcp_saved_syn_free(tp); /* Clean up fastopen related fields */ tcp_free_fastopen_req(tp); inet->defer_connect = 0; WARN_ON(inet->inet_num && !icsk->icsk_bind_hash); sk->sk_error_report(sk); return err; } Commit Message: tcp: initialize rcv_mss to TCP_MIN_MSS instead of 0 When tcp_disconnect() is called, inet_csk_delack_init() sets icsk->icsk_ack.rcv_mss to 0. This could potentially cause tcp_recvmsg() => tcp_cleanup_rbuf() => __tcp_select_window() call path to have division by 0 issue. So this patch initializes rcv_mss to TCP_MIN_MSS instead of 0. Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Wei Wang <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Neal Cardwell <[email protected]> Signed-off-by: Yuchung Cheng <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-369 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: de_dotdot( char* file ) { char* cp; char* cp2; int l; /* Collapse any multiple / sequences. */ while ( ( cp = strstr( file, "//") ) != (char*) 0 ) { for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 ) continue; (void) strcpy( cp + 1, cp2 ); } /* Remove leading ./ and any /./ sequences. */ while ( strncmp( file, "./", 2 ) == 0 ) (void) memmove( file, file + 2, strlen( file ) - 1 ); while ( ( cp = strstr( file, "/./") ) != (char*) 0 ) (void) memmove( cp, cp + 2, strlen( file ) - 1 ); /* Alternate between removing leading ../ and removing xxx/../ */ for (;;) { while ( strncmp( file, "../", 3 ) == 0 ) (void) memmove( file, file + 3, strlen( file ) - 2 ); cp = strstr( file, "/../" ); if ( cp == (char*) 0 ) break; for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; (void) strcpy( cp2 + 1, cp + 4 ); } /* Also elide any xxx/.. at the end. */ while ( ( l = strlen( file ) ) > 3 && strcmp( ( cp = file + l - 3 ), "/.." ) == 0 ) { for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; if ( cp2 < file ) break; *cp2 = '\0'; } } Commit Message: Fix heap buffer overflow in de_dotdot CWE ID: CWE-119 Target: 1 Example 2: Code: int mwifiex_config_start_uap(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg) { if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_SYS_CONFIG, HostCmd_ACT_GEN_SET, UAP_BSS_PARAMS_I, bss_cfg, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to set AP configuration\n"); return -1; } if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_BSS_START, HostCmd_ACT_GEN_SET, 0, NULL, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to start the BSS\n"); return -1; } if (priv->sec_info.wep_enabled) priv->curr_pkt_filter |= HostCmd_ACT_MAC_WEP_ENABLE; else priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_WEP_ENABLE; if (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL, HostCmd_ACT_GEN_SET, 0, &priv->curr_pkt_filter, true)) return -1; return 0; } Commit Message: mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings mwifiex_update_vs_ie(),mwifiex_set_uap_rates() and mwifiex_set_wmm_params() call memcpy() without checking the destination size.Since the source is given from user-space, this may trigger a heap buffer overflow. Fix them by putting the length check before performing memcpy(). This fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816. Signed-off-by: Wen Huang <[email protected]> Acked-by: Ganapathi Bhat <[email protected]> Signed-off-by: Kalle Valo <[email protected]> CWE ID: CWE-120 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void tg3_read_vpd(struct tg3 *tp) { u8 *vpd_data; unsigned int block_end, rosize, len; u32 vpdlen; int j, i = 0; vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen); if (!vpd_data) goto out_no_vpd; i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA); if (i < 0) goto out_not_found; rosize = pci_vpd_lrdt_size(&vpd_data[i]); block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize; i += PCI_VPD_LRDT_TAG_SIZE; if (block_end > vpdlen) goto out_not_found; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_MFR_ID); if (j > 0) { len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end || len != 4 || memcmp(&vpd_data[j], "1028", 4)) goto partno; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_VENDOR0); if (j < 0) goto partno; len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end) goto partno; memcpy(tp->fw_ver, &vpd_data[j], len); strncat(tp->fw_ver, " bc ", vpdlen - len - 1); } partno: i = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_PARTNO); if (i < 0) goto out_not_found; len = pci_vpd_info_field_size(&vpd_data[i]); i += PCI_VPD_INFO_FLD_HDR_SIZE; if (len > TG3_BPN_SIZE || (len + i) > vpdlen) goto out_not_found; memcpy(tp->board_part_number, &vpd_data[i], len); out_not_found: kfree(vpd_data); if (tp->board_part_number[0]) return; out_no_vpd: if (tg3_asic_rev(tp) == ASIC_REV_5717) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C) strcpy(tp->board_part_number, "BCM5717"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718) strcpy(tp->board_part_number, "BCM5718"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57780) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780) strcpy(tp->board_part_number, "BCM57780"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760) strcpy(tp->board_part_number, "BCM57760"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790) strcpy(tp->board_part_number, "BCM57790"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788) strcpy(tp->board_part_number, "BCM57788"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57765) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761) strcpy(tp->board_part_number, "BCM57761"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765) strcpy(tp->board_part_number, "BCM57765"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781) strcpy(tp->board_part_number, "BCM57781"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785) strcpy(tp->board_part_number, "BCM57785"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791) strcpy(tp->board_part_number, "BCM57791"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795) strcpy(tp->board_part_number, "BCM57795"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57766) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762) strcpy(tp->board_part_number, "BCM57762"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766) strcpy(tp->board_part_number, "BCM57766"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782) strcpy(tp->board_part_number, "BCM57782"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786) strcpy(tp->board_part_number, "BCM57786"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_5906) { strcpy(tp->board_part_number, "BCM95906"); } else { nomatch: strcpy(tp->board_part_number, "none"); } } Commit Message: tg3: fix length overflow in VPD firmware parsing Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version when present") introduced VPD parsing that contained a potential length overflow. Limit the hardware's reported firmware string length (max 255 bytes) to stay inside the driver's firmware string length (32 bytes). On overflow, truncate the formatted firmware string instead of potentially overwriting portions of the tg3 struct. http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf Signed-off-by: Kees Cook <[email protected]> Reported-by: Oded Horovitz <[email protected]> Reported-by: Brad Spengler <[email protected]> Cc: [email protected] Cc: Matt Carlson <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **retval; char *key; uint len; long index; HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!offset) { return &EG(uninitialized_zval_ptr); } if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return &EG(error_zval_ptr);; } switch (Z_TYPE_P(offset)) { case IS_STRING: key = Z_STRVAL_P(offset); len = Z_STRLEN_P(offset) + 1; string_offest: if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined index: %s", key); case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE,"Undefined index: %s", key); case BP_VAR_W: { zval *value; ALLOC_INIT_ZVAL(value); zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval); } } } return retval; case IS_NULL: key = ""; len = 1; goto string_offest; case IS_RESOURCE: zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset)); case IS_DOUBLE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined offset: %ld", index); case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE, "Undefined offset: %ld", index); case BP_VAR_W: { zval *value; ALLOC_INIT_ZVAL(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval); } } } return retval; default: zend_error(E_WARNING, "Illegal offset type"); return (type == BP_VAR_W || type == BP_VAR_RW) ? &EG(error_zval_ptr) : &EG(uninitialized_zval_ptr); } } /* }}} */ Commit Message: Fix bug #73029 - Missing type check when unserializing SplArray CWE ID: CWE-20 Target: 1 Example 2: Code: void DevToolsAgent::OnNavigate() { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->didNavigate(); } } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; struct sctp_sock *sp = sctp_sk(sk); unsigned int mask; poll_wait(file, sk_sleep(sk), wait); /* A TCP-style listening socket becomes readable when the accept queue * is not empty. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) return (!list_empty(&sp->ep->asocs)) ? (POLLIN | POLLRDNORM) : 0; mask = 0; /* Is there any exceptional events? */ if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP | POLLIN | POLLRDNORM; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; /* Is it readable? Reconsider this code with TCP-style support. */ if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; /* The association is either gone or not ready. */ if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED)) return mask; /* Is it writable? */ if (sctp_writeable(sk)) { mask |= POLLOUT | POLLWRNORM; } else { set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); /* * Since the socket is not locked, the buffer * might be made available after the writeable check and * before the bit is set. This could cause a lost I/O * signal. tcp_poll() has a race breaker for this race * condition. Based on their implementation, we put * in the following code to cover it as well. */ if (sctp_writeable(sk)) mask |= POLLOUT | POLLWRNORM; } return mask; } Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS Building sctp may fail with: In function ‘copy_from_user’, inlined from ‘sctp_getsockopt_assoc_stats’ at net/sctp/socket.c:5656:20: arch/x86/include/asm/uaccess_32.h:211:26: error: call to ‘copy_from_user_overflow’ declared with attribute error: copy_from_user() buffer size is not provably correct if built with W=1 due to a missing parameter size validation before the call to copy_from_user. Signed-off-by: Guenter Roeck <[email protected]> Acked-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); } Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: static void tcp_process_loss(struct sock *sk, int flag, bool is_dupack) { struct tcp_sock *tp = tcp_sk(sk); bool recovered = !before(tp->snd_una, tp->high_seq); if ((flag & FLAG_SND_UNA_ADVANCED) && tcp_try_undo_loss(sk, false)) return; if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */ /* Step 3.b. A timeout is spurious if not all data are * lost, i.e., never-retransmitted data are (s)acked. */ if ((flag & FLAG_ORIG_SACK_ACKED) && tcp_try_undo_loss(sk, true)) return; if (after(tp->snd_nxt, tp->high_seq)) { if (flag & FLAG_DATA_SACKED || is_dupack) tp->frto = 0; /* Step 3.a. loss was real */ } else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) { tp->high_seq = tp->snd_nxt; __tcp_push_pending_frames(sk, tcp_current_mss(sk), TCP_NAGLE_OFF); if (after(tp->snd_nxt, tp->high_seq)) return; /* Step 2.b */ tp->frto = 0; } } if (recovered) { /* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */ tcp_try_undo_recovery(sk); return; } if (tcp_is_reno(tp)) { /* A Reno DUPACK means new data in F-RTO step 2.b above are * delivered. Lower inflight to clock out (re)tranmissions. */ if (after(tp->snd_nxt, tp->high_seq) && is_dupack) tcp_add_reno_sack(sk); else if (flag & FLAG_SND_UNA_ADVANCED) tcp_reset_reno_sack(tp); } tcp_xmit_retransmit_queue(sk); } Commit Message: tcp: fix zero cwnd in tcp_cwnd_reduction Patch 3759824da87b ("tcp: PRR uses CRB mode by default and SS mode conditionally") introduced a bug that cwnd may become 0 when both inflight and sndcnt are 0 (cwnd = inflight + sndcnt). This may lead to a div-by-zero if the connection starts another cwnd reduction phase by setting tp->prior_cwnd to the current cwnd (0) in tcp_init_cwnd_reduction(). To prevent this we skip PRR operation when nothing is acked or sacked. Then cwnd must be positive in all cases as long as ssthresh is positive: 1) The proportional reduction mode inflight > ssthresh > 0 2) The reduction bound mode a) inflight == ssthresh > 0 b) inflight < ssthresh sndcnt > 0 since newly_acked_sacked > 0 and inflight < ssthresh Therefore in all cases inflight and sndcnt can not both be 0. We check invalid tp->prior_cwnd to avoid potential div0 bugs. In reality this bug is triggered only with a sequence of less common events. For example, the connection is terminating an ECN-triggered cwnd reduction with an inflight 0, then it receives reordered/old ACKs or DSACKs from prior transmission (which acks nothing). Or the connection is in fast recovery stage that marks everything lost, but fails to retransmit due to local issues, then receives data packets from other end which acks nothing. Fixes: 3759824da87b ("tcp: PRR uses CRB mode by default and SS mode conditionally") Reported-by: Oleksandr Natalenko <[email protected]> Signed-off-by: Yuchung Cheng <[email protected]> Signed-off-by: Neal Cardwell <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool SendAutomationJSONRequest(AutomationMessageSender* sender, const DictionaryValue& request_dict, DictionaryValue* reply_dict, std::string* error_msg) { std::string request, reply; base::JSONWriter::Write(&request_dict, false, &request); bool success = false; int timeout_ms = TestTimeouts::action_max_timeout_ms(); base::Time before_sending = base::Time::Now(); if (!SendAutomationJSONRequest( sender, request, timeout_ms, &reply, &success)) { int64 elapsed_ms = (base::Time::Now() - before_sending).InMilliseconds(); std::string command; request_dict.GetString("command", &command); if (elapsed_ms >= timeout_ms) { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Request may have timed out. " "Elapsed time was %" PRId64 " ms. Request timeout was %d ms. " "Request details: (%s).", command.c_str(), elapsed_ms, timeout_ms, request.c_str()); } else { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. " "Request details: (%s).", command.c_str(), elapsed_ms, request.c_str()); } return false; } scoped_ptr<Value> value(base::JSONReader::Read(reply, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { std::string command; request_dict.GetString("command", &command); LOG(ERROR) << "JSON request did not return dict: " << command << "\n"; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); if (!success) { std::string command, error; request_dict.GetString("command", &command); dict->GetString("error", &error); *error_msg = base::StringPrintf( "Internal Chrome error during '%s': (%s). Request details: (%s).", command.c_str(), error.c_str(), request.c_str()); LOG(ERROR) << "JSON request failed: " << command << "\n" << " with error: " << error; return false; } reply_dict->MergeDictionary(dict); return true; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool LayoutSVGTransformableContainer::calculateLocalTransform() { SVGGraphicsElement* element = toSVGGraphicsElement(this->element()); ASSERT(element); SVGUseElement* useElement = nullptr; if (isSVGUseElement(*element)) { useElement = toSVGUseElement(element); } else if (isSVGGElement(*element) && toSVGGElement(element)->inUseShadowTree()) { SVGElement* correspondingElement = element->correspondingElement(); if (isSVGUseElement(correspondingElement)) useElement = toSVGUseElement(correspondingElement); } if (useElement) { SVGLengthContext lengthContext(useElement); FloatSize translation( useElement->x()->currentValue()->value(lengthContext), useElement->y()->currentValue()->value(lengthContext)); if (translation != m_additionalTranslation) m_needsTransformUpdate = true; m_additionalTranslation = translation; } if (!m_needsTransformUpdate) return false; m_localTransform = element->calculateAnimatedLocalTransform(); m_localTransform.translate(m_additionalTranslation.width(), m_additionalTranslation.height()); m_needsTransformUpdate = false; return true; } Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers Currently, SVG containers in the LayoutObject hierarchy force layout of their children if the transform changes. The main reason for this is to trigger paint invalidation of the subtree. In some cases - changes to the scale factor - there are other reasons to trigger layout, like computing a new scale factor for <text> or re-layout nodes with non-scaling stroke. Compute a "scale-factor change" in addition to the "transform change" already computed, then use this new signal to determine if layout should be forced for the subtree. Trigger paint invalidation using the LayoutObject flags instead. The downside to this is that paint invalidation will walk into "hidden" containers which rarely require repaint (since they are not technically visible). This will hopefully be rectified in a follow-up CL. For the testcase from 603850, this essentially eliminates the cost of layout (from ~350ms to ~0ms on authors machine; layout cost is related to text metrics recalculation), bumping frame rate significantly. BUG=603956,603850 Review-Url: https://codereview.chromium.org/1996543002 Cr-Commit-Position: refs/heads/master@{#400950} CWE ID: Target: 1 Example 2: Code: bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " %s", tstr)); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); } Commit Message: (for 4.9.3) CVE-2018-16300/BGP: prevent stack exhaustion Enforce a limit on how many times bgp_attr_print() can recurse. This fixes a stack exhaustion discovered by Include Security working under the Mozilla SOS program in 2018 by means of code audit. CWE ID: CWE-674 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: relay_command_to_string(uint8_t command) { switch (command) { case RELAY_COMMAND_BEGIN: return "BEGIN"; case RELAY_COMMAND_DATA: return "DATA"; case RELAY_COMMAND_END: return "END"; case RELAY_COMMAND_CONNECTED: return "CONNECTED"; case RELAY_COMMAND_SENDME: return "SENDME"; case RELAY_COMMAND_EXTEND: return "EXTEND"; case RELAY_COMMAND_EXTENDED: return "EXTENDED"; case RELAY_COMMAND_TRUNCATE: return "TRUNCATE"; case RELAY_COMMAND_TRUNCATED: return "TRUNCATED"; case RELAY_COMMAND_DROP: return "DROP"; case RELAY_COMMAND_RESOLVE: return "RESOLVE"; case RELAY_COMMAND_RESOLVED: return "RESOLVED"; case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR"; case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO"; case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS"; case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1"; case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2"; case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1"; case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2"; case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED"; case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED: return "RENDEZVOUS_ESTABLISHED"; case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK"; default: return "(unrecognized)"; } } Commit Message: TROVE-2017-005: Fix assertion failure in connection_edge_process_relay_cell On an hidden service rendezvous circuit, a BEGIN_DIR could be sent (maliciously) which would trigger a tor_assert() because connection_edge_process_relay_cell() thought that the circuit is an or_circuit_t but is an origin circuit in reality. Fixes #22494 Reported-by: Roger Dingledine <[email protected]> Signed-off-by: David Goulet <[email protected]> CWE ID: CWE-617 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CallCompositorWithSuccess(mojom::PdfCompositorPtr ptr) { auto handle = CreateMSKPInSharedMemory(); ASSERT_TRUE(handle.IsValid()); mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(handle, handle.GetSize(), true); ASSERT_TRUE(buffer_handle->is_valid()); EXPECT_CALL(*this, CallbackOnSuccess(testing::_)).Times(1); ptr->CompositePdf(std::move(buffer_handle), base::BindOnce(&PdfCompositorServiceTest::OnCallback, base::Unretained(this))); run_loop_->Run(); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 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: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 1 Example 2: Code: bool Browser::IsPopupOrPanel(const WebContents* source) const { return is_type_popup() || is_type_panel(); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ape_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { AVFrame *frame = data; const uint8_t *buf = avpkt->data; APEContext *s = avctx->priv_data; uint8_t *sample8; int16_t *sample16; int32_t *sample24; int i, ch, ret; int blockstodecode; /* this should never be negative, but bad things will happen if it is, so check it just to make sure. */ av_assert0(s->samples >= 0); if(!s->samples){ uint32_t nblocks, offset; int buf_size; if (!avpkt->size) { *got_frame_ptr = 0; return 0; } if (avpkt->size < 8) { av_log(avctx, AV_LOG_ERROR, "Packet is too small\n"); return AVERROR_INVALIDDATA; } buf_size = avpkt->size & ~3; if (buf_size != avpkt->size) { av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. " "extra bytes at the end will be skipped.\n"); } if (s->fileversion < 3950) // previous versions overread two bytes buf_size += 2; av_fast_padded_malloc(&s->data, &s->data_size, buf_size); if (!s->data) return AVERROR(ENOMEM); s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf, buf_size >> 2); memset(s->data + (buf_size & ~3), 0, buf_size & 3); s->ptr = s->data; s->data_end = s->data + buf_size; nblocks = bytestream_get_be32(&s->ptr); offset = bytestream_get_be32(&s->ptr); if (s->fileversion >= 3900) { if (offset > 3) { av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n"); s->data = NULL; return AVERROR_INVALIDDATA; } if (s->data_end - s->ptr < offset) { av_log(avctx, AV_LOG_ERROR, "Packet is too small\n"); return AVERROR_INVALIDDATA; } s->ptr += offset; } else { if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0) return ret; if (s->fileversion > 3800) skip_bits_long(&s->gb, offset * 8); else skip_bits_long(&s->gb, offset); } if (!nblocks || nblocks > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n", nblocks); return AVERROR_INVALIDDATA; } /* Initialize the frame decoder */ if (init_frame_decoder(s) < 0) { av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n"); return AVERROR_INVALIDDATA; } s->samples = nblocks; } if (!s->data) { *got_frame_ptr = 0; return avpkt->size; } blockstodecode = FFMIN(s->blocks_per_loop, s->samples); if (s->fileversion < 3930) blockstodecode = s->samples; /* reallocate decoded sample buffer if needed */ av_fast_malloc(&s->decoded_buffer, &s->decoded_size, 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer)); if (!s->decoded_buffer) return AVERROR(ENOMEM); memset(s->decoded_buffer, 0, s->decoded_size); s->decoded[0] = s->decoded_buffer; s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8); /* get output buffer */ frame->nb_samples = blockstodecode; if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; s->error=0; if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO)) ape_unpack_mono(s, blockstodecode); else ape_unpack_stereo(s, blockstodecode); emms_c(); if (s->error) { s->samples=0; av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n"); return AVERROR_INVALIDDATA; } switch (s->bps) { case 8: for (ch = 0; ch < s->channels; ch++) { sample8 = (uint8_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff; } break; case 16: for (ch = 0; ch < s->channels; ch++) { sample16 = (int16_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample16++ = s->decoded[ch][i]; } break; case 24: for (ch = 0; ch < s->channels; ch++) { sample24 = (int32_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample24++ = s->decoded[ch][i] << 8; } break; } s->samples -= blockstodecode; *got_frame_ptr = 1; return !s->samples ? avpkt->size : 0; } Commit Message: avcodec/apedec: Fix integer overflow Fixes: out of array access Fixes: PoC.ape and others Found-by: Bingchang, Liu@VARAS of IIE Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y]); } } } Commit Message: Fix seven bugs discovered and fixed by ForAllSecure: CVE-2019-13217: heap buffer overflow in start_decoder() CVE-2019-13218: stack buffer overflow in compute_codewords() CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest() CVE-2019-13220: out-of-range read in draw_line() CVE-2019-13221: issue with large 1D codebooks in lookup1_values() CVE-2019-13222: unchecked NULL returned by get_window() CVE-2019-13223: division by zero in predict_point() CWE ID: CWE-20 Target: 1 Example 2: Code: static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong(int32 value) { if ((value<-0x8000)||(value>0x7FFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } Commit Message: * libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip), instead of a logic based on the total size of data. Which is faulty is the total size of data is not sufficient to fill the whole image, and thus results in reading outside of the StripByCounts/StripOffsets arrays when using TIFFReadScanline(). Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608. * libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since the above change is a better fix that makes it unnecessary. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BrowserPolicyConnector::DeviceStopAutoRetry() { #if defined(OS_CHROMEOS) if (device_cloud_policy_subsystem_.get()) device_cloud_policy_subsystem_->StopAutoRetry(); #endif } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PPB_URLLoader_Impl::RunCallback(int32_t result) { if (!pending_callback_.get()) { CHECK(main_document_loader_); return; } TrackedCallback::ClearAndRun(&pending_callback_, result); } Commit Message: Remove possibility of stale user_buffer_ member in PPB_URLLoader_Impl when FinishedLoading() is called. BUG=137778 Review URL: https://chromiumcodereview.appspot.com/10797037 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@147914 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: xfs_da3_node_read_verify( struct xfs_buf *bp) { struct xfs_mount *mp = bp->b_target->bt_mount; struct xfs_da_blkinfo *info = bp->b_addr; switch (be16_to_cpu(info->magic)) { case XFS_DA3_NODE_MAGIC: if (!xfs_verify_cksum(bp->b_addr, BBTOB(bp->b_length), XFS_DA3_NODE_CRC_OFF)) break; /* fall through */ case XFS_DA_NODE_MAGIC: if (!xfs_da3_node_verify(bp)) break; return; case XFS_ATTR_LEAF_MAGIC: case XFS_ATTR3_LEAF_MAGIC: bp->b_ops = &xfs_attr3_leaf_buf_ops; bp->b_ops->verify_read(bp); return; case XFS_DIR2_LEAFN_MAGIC: case XFS_DIR3_LEAFN_MAGIC: bp->b_ops = &xfs_dir3_leafn_buf_ops; bp->b_ops->verify_read(bp); return; default: break; } /* corrupt block */ XFS_CORRUPTION_ERROR(__func__, XFS_ERRLEVEL_LOW, mp, bp->b_addr); xfs_buf_ioerror(bp, EFSCORRUPTED); } Commit Message: xfs: fix directory hash ordering bug Commit f5ea1100 ("xfs: add CRCs to dir2/da node blocks") introduced in 3.10 incorrectly converted the btree hash index array pointer in xfs_da3_fixhashpath(). It resulted in the the current hash always being compared against the first entry in the btree rather than the current block index into the btree block's hash entry array. As a result, it was comparing the wrong hashes, and so could misorder the entries in the btree. For most cases, this doesn't cause any problems as it requires hash collisions to expose the ordering problem. However, when there are hash collisions within a directory there is a very good probability that the entries will be ordered incorrectly and that actually matters when duplicate hashes are placed into or removed from the btree block hash entry array. This bug results in an on-disk directory corruption and that results in directory verifier functions throwing corruption warnings into the logs. While no data or directory entries are lost, access to them may be compromised, and attempts to remove entries from a directory that has suffered from this corruption may result in a filesystem shutdown. xfs_repair will fix the directory hash ordering without data loss occuring. [dchinner: wrote useful a commit message] cc: <[email protected]> Reported-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Mark Tinguely <[email protected]> Reviewed-by: Ben Myers <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK); len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE) { return -1; } qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as); if (off + len > 4096) { /* transfer crosses page border */ uint32_t len2 = off + len - 4096; uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); /* Fall through */ case USB_RET_IOERROR: case USB_RET_NODEV: /* 3.3.2: XACTERR is only allowed on IN transactions */ if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: /* no data for us, so do a zero-length transfer */ ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* OUT */ } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* IN */ } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; } } return 0; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: const char* url() const { return url_.c_str(); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: DefragTimeoutTest(void) { int i; int ret = 0; /* Setup a small numberr of trackers. */ if (ConfSet("defrag.trackers", "16") != 1) { printf("ConfSet failed: "); goto end; } DefragInit(); /* Load in 16 packets. */ for (i = 0; i < 16; i++) { Packet *p = BuildTestPacket(i, 0, 1, 'A' + i, 16); if (p == NULL) goto end; Packet *tp = Defrag(NULL, NULL, p, NULL); SCFree(p); if (tp != NULL) { SCFree(tp); goto end; } } /* Build a new packet but push the timestamp out by our timeout. * This should force our previous fragments to be timed out. */ Packet *p = BuildTestPacket(99, 0, 1, 'A' + i, 16); if (p == NULL) goto end; p->ts.tv_sec += (defrag_context->timeout + 1); Packet *tp = Defrag(NULL, NULL, p, NULL); if (tp != NULL) { SCFree(tp); goto end; } DefragTracker *tracker = DefragLookupTrackerFromHash(p); if (tracker == NULL) goto end; if (tracker->id != 99) goto end; SCFree(p); ret = 1; end: DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: StorageHandler::IndexedDBObserver* StorageHandler::GetIndexedDBObserver() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!indexed_db_observer_) { indexed_db_observer_ = std::make_unique<IndexedDBObserver>( weak_ptr_factory_.GetWeakPtr(), static_cast<IndexedDBContextImpl*>( process_->GetStoragePartition()->GetIndexedDBContext())); } return indexed_db_observer_.get(); } 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 <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 1 Example 2: Code: void ResourceFetcher::incrementRequestCount(const Resource* res) { if (res->ignoreForRequestCount()) return; ++m_requestCount; } Commit Message: Enforce SVG image security rules SVG images have unique security rules that prevent them from loading any external resources. This patch enforces these rules in ResourceFetcher::canRequest for all non-data-uri resources. This locks down our SVG resource handling and fixes two security bugs. In the case of SVG images that reference other images, we had a bug where a cached subresource would be used directly from the cache. This has been fixed because the canRequest check occurs before we use cached resources. In the case of SVG images that use CSS imports, we had a bug where imports were blindly requested. This has been fixed by stopping all non-data-uri requests in SVG images. With this patch we now match Gecko's behavior on both testcases. BUG=380885, 382296 Review URL: https://codereview.chromium.org/320763002 git-svn-id: svn://svn.chromium.org/blink/trunk@176084 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: InProcessBrowserTest::InProcessBrowserTest() : browser_(NULL), exit_when_last_browser_closes_(true), multi_desktop_test_(false) #if defined(OS_MACOSX) , autorelease_pool_(NULL) #endif // OS_MACOSX { #if defined(OS_MACOSX) base::FilePath chrome_path; CHECK(PathService::Get(base::FILE_EXE, &chrome_path)); chrome_path = chrome_path.DirName(); chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath); CHECK(PathService::Override(base::FILE_EXE, chrome_path)); #endif // defined(OS_MACOSX) CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data"))); base::FilePath src_dir; CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir)); base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data"); embedded_test_server()->ServeFilesFromDirectory(test_data_dir); CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir)); } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: kadm5_modify_principal(void *server_handle, kadm5_principal_ent_t entry, long mask) { int ret, ret2, i; kadm5_policy_ent_rec pol; krb5_boolean have_pol = FALSE; krb5_db_entry *kdb; krb5_tl_data *tl_data_orig; osa_princ_ent_rec adb; kadm5_server_handle_t handle = server_handle; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if((mask & KADM5_PRINCIPAL) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MOD_TIME) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_KEY_DATA) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if(entry == (kadm5_principal_ent_t) NULL) return EINVAL; if (mask & KADM5_TL_DATA) { tl_data_orig = entry->tl_data; while (tl_data_orig) { if (tl_data_orig->tl_data_type < 256) return KADM5_BAD_TL_TYPE; tl_data_orig = tl_data_orig->tl_data_next; } } ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); if (ret) return(ret); /* * This is pretty much the same as create ... */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &pol, &have_pol); if (ret) goto done; /* set us up to use the new policy */ adb.aux_attributes |= KADM5_POLICY; if (adb.policy) free(adb.policy); adb.policy = strdup(entry->policy); } if (have_pol) { /* set pw_max_life based on new policy */ if (pol.pw_max_life) { ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &(kdb->pw_expiration)); if (ret) goto done; kdb->pw_expiration += pol.pw_max_life; } else { kdb->pw_expiration = 0; } } if ((mask & KADM5_POLICY_CLR) && (adb.aux_attributes & KADM5_POLICY)) { free(adb.policy); adb.policy = NULL; adb.aux_attributes &= ~KADM5_POLICY; kdb->pw_expiration = 0; } if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; if (mask & KADM5_PW_EXPIRATION) kdb->pw_expiration = entry->pw_expiration; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; if((mask & KADM5_KVNO)) { for (i = 0; i < kdb->n_key_data; i++) kdb->key_data[i].key_data_kvno = entry->kvno; } if (mask & KADM5_TL_DATA) { krb5_tl_data *tl; /* may have to change the version number of the API. Updates the list with the given tl_data rather than over-writting */ for (tl = entry->tl_data; tl; tl = tl->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl); if( ret ) { goto done; } } } /* * Setting entry->fail_auth_count to 0 can be used to manually unlock * an account. It is not possible to set fail_auth_count to any other * value using kadmin. */ if (mask & KADM5_FAIL_AUTH_COUNT) { if (entry->fail_auth_count != 0) { ret = KADM5_BAD_SERVER_PARAMS; goto done; } kdb->fail_auth_count = 0; } /* let the mask propagate to the database provider */ kdb->mask = mask; ret = k5_kadm5_hook_modify(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask); if (ret) goto done; ret = kdb_put_entry(handle, kdb, &adb); if (ret) goto done; (void) k5_kadm5_hook_modify(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask); ret = KADM5_OK; done: if (have_pol) { ret2 = kadm5_free_policy_ent(handle->lhandle, &pol); ret = ret ? ret : ret2; } kdb_free_entry(handle, kdb, &adb); return ret; } Commit Message: Check for null kadm5 policy name [CVE-2015-8630] In kadm5_create_principal_3() and kadm5_modify_principal(), check for entry->policy being null when KADM5_POLICY is included in the mask. CVE-2015-8630: In MIT krb5 1.12 and later, an authenticated attacker with permission to modify a principal entry can cause kadmind to dereference a null pointer by supplying a null policy value but including KADM5_POLICY in the mask. CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8342 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: Target: 1 Example 2: Code: int user_path_at_empty(int dfd, const char __user *name, unsigned flags, struct path *path, int *empty) { return filename_lookup(dfd, getname_flags(name, flags, empty), flags, path, NULL); } Commit Message: vfs: Test for and handle paths that are unreachable from their mnt_root In rare cases a directory can be renamed out from under a bind mount. In those cases without special handling it becomes possible to walk up the directory tree to the root dentry of the filesystem and down from the root dentry to every other file or directory on the filesystem. Like division by zero .. from an unconnected path can not be given a useful semantic as there is no predicting at which path component the code will realize it is unconnected. We certainly can not match the current behavior as the current behavior is a security hole. Therefore when encounting .. when following an unconnected path return -ENOENT. - Add a function path_connected to verify path->dentry is reachable from path->mnt.mnt_root. AKA to validate that rename did not do something nasty to the bind mount. To avoid races path_connected must be called after following a path component to it's next path component. Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: chrand_principal3_2_svc(chrand3_arg *arg, struct svc_req *rqstp) { static chrand_ret ret; krb5_keyblock *k; int nkeys; char *prime_arg, *funcname; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_chrand_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_randkey_principal"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = randkey_principal_wrapper_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, &k, &nkeys); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_randkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, &k, &nkeys); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code == KADM5_OK) { ret.keys = k; ret.n_keys = nkeys; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AutofillExternalDelegate::OnSuggestionsReturned( int query_id, const std::vector<Suggestion>& input_suggestions, bool autoselect_first_suggestion, bool is_all_server_suggestions) { if (query_id != query_id_) return; std::vector<Suggestion> suggestions(input_suggestions); PossiblyRemoveAutofillWarnings(&suggestions); #if !defined(OS_ANDROID) if (!suggestions.empty() && !features::ShouldUseNativeViews()) { suggestions.push_back(Suggestion()); suggestions.back().frontend_id = POPUP_ITEM_ID_SEPARATOR; } #endif if (should_show_scan_credit_card_) { Suggestion scan_credit_card( l10n_util::GetStringUTF16(IDS_AUTOFILL_SCAN_CREDIT_CARD)); scan_credit_card.frontend_id = POPUP_ITEM_ID_SCAN_CREDIT_CARD; scan_credit_card.icon = base::ASCIIToUTF16("scanCreditCardIcon"); suggestions.push_back(scan_credit_card); } has_autofill_suggestions_ = false; for (size_t i = 0; i < suggestions.size(); ++i) { if (suggestions[i].frontend_id > 0) { has_autofill_suggestions_ = true; break; } } if (should_show_cards_from_account_option_) { suggestions.emplace_back( l10n_util::GetStringUTF16(IDS_AUTOFILL_SHOW_ACCOUNT_CARDS)); suggestions.back().frontend_id = POPUP_ITEM_ID_SHOW_ACCOUNT_CARDS; suggestions.back().icon = base::ASCIIToUTF16("google"); } if (has_autofill_suggestions_) ApplyAutofillOptions(&suggestions, is_all_server_suggestions); if (suggestions.empty() && should_show_cc_signin_promo_) { #if !defined(OS_ANDROID) if (has_autofill_suggestions_) { suggestions.push_back(Suggestion()); suggestions.back().frontend_id = POPUP_ITEM_ID_SEPARATOR; } #endif Suggestion signin_promo_suggestion( l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDIT_CARD_SIGNIN_PROMO)); signin_promo_suggestion.frontend_id = POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO; suggestions.push_back(signin_promo_suggestion); signin_metrics::RecordSigninImpressionUserActionForAccessPoint( signin_metrics::AccessPoint::ACCESS_POINT_AUTOFILL_DROPDOWN); } #if !defined(OS_ANDROID) if (!suggestions.empty() && suggestions.back().frontend_id == POPUP_ITEM_ID_SEPARATOR) { suggestions.pop_back(); } #endif InsertDataListValues(&suggestions); if (suggestions.empty()) { manager_->client()->HideAutofillPopup(); return; } if (query_field_.is_focusable) { manager_->client()->ShowAutofillPopup( element_bounds_, query_field_.text_direction, suggestions, autoselect_first_suggestion, GetWeakPtr()); } } 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 <[email protected]> Reviewed-by: Vasilii Sukhanov <[email protected]> Reviewed-by: Fabio Tirelo <[email protected]> Reviewed-by: Tommy Martino <[email protected]> Commit-Queue: Mathieu Perreault <[email protected]> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416 Target: 1 Example 2: Code: SlotAssignmentEngine& Document::GetSlotAssignmentEngine() { if (!slot_assignment_engine_) slot_assignment_engine_ = SlotAssignmentEngine::Create(); return *slot_assignment_engine_; } Commit Message: Cleanup and remove dead code in SetFocusedElement This early-out was added in: https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc Back then, we applied fragment focus in LayoutUpdated() which could cause this issue. This got cleaned up in: https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2 so that focus is no longer applied after layout. +Cleanup: Goto considered harmful Bug: 795381 Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417 Commit-Queue: David Bokan <[email protected]> Reviewed-by: Stefan Zager <[email protected]> Cr-Commit-Position: refs/heads/master@{#641101} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: HistogramType CustomHistogram::GetHistogramType() const { return CUSTOM_HISTOGRAM; } Commit Message: Convert DCHECKs to CHECKs for histogram types When a histogram is looked up by name, there is currently a DCHECK that verifies the type of the stored histogram matches the expected type. A mismatch represents a significant problem because the returned HistogramBase is cast to a Histogram in ValidateRangeChecksum, potentially causing a crash. This CL converts the DCHECK to a CHECK to prevent the possibility of type confusion in release builds. BUG=651443 [email protected] Review-Url: https://codereview.chromium.org/2381893003 Cr-Commit-Position: refs/heads/master@{#421929} CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void StorageHandler::GetUsageAndQuota( const String& origin, std::unique_ptr<GetUsageAndQuotaCallback> callback) { if (!process_) return callback->sendFailure(Response::InternalError()); GURL origin_url(origin); if (!origin_url.is_valid()) { return callback->sendFailure( Response::Error(origin + " is not a valid URL")); } storage::QuotaManager* manager = process_->GetStoragePartition()->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&GetUsageAndQuotaOnIOThread, base::RetainedRef(manager), origin_url, base::Passed(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 <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 1 Example 2: Code: void upnpevents_selectfds(fd_set *readset, fd_set *writeset, int * max_fd) { struct upnp_event_notify * obj; for(obj = notifylist.lh_first; obj != NULL; obj = obj->entries.le_next) { syslog(LOG_DEBUG, "upnpevents_selectfds: %p %d %d", obj, obj->state, obj->s); if(obj->s >= 0) { switch(obj->state) { case ECreated: upnp_event_notify_connect(obj); if(obj->state != EConnecting) break; case EConnecting: case ESending: FD_SET(obj->s, writeset); if(obj->s > *max_fd) *max_fd = obj->s; break; case EWaitingForResponse: FD_SET(obj->s, readset); if(obj->s > *max_fd) *max_fd = obj->s; break; default: ; } } } } Commit Message: upnp_event_prepare(): check the return value of snprintf() CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; } Commit Message: CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void StoreExistingGroupExistingCache() { MakeCacheAndGroup(kManifestUrl, 1, 1, true); EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]); base::Time now = base::Time::Now(); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::MASTER, 1, 100)); cache_->set_update_time(now); PushNextTask(base::BindOnce( &AppCacheStorageImplTest::Verify_StoreExistingGroupExistingCache, base::Unretained(this), now)); EXPECT_EQ(cache_.get(), group_->newest_complete_cache()); storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200 Target: 1 Example 2: Code: static void init_header(struct ctl_table_header *head, struct ctl_table_root *root, struct ctl_table_set *set, struct ctl_node *node, struct ctl_table *table) { head->ctl_table = table; head->ctl_table_arg = table; head->used = 0; head->count = 1; head->nreg = 1; head->unregistering = NULL; head->root = root; head->set = set; head->parent = NULL; head->node = node; if (node) { struct ctl_table *entry; for (entry = table; entry->procname; entry++, node++) node->header = head; } } Commit Message: sysctl: Drop reference added by grab_header in proc_sys_readdir Fixes CVE-2016-9191, proc_sys_readdir doesn't drop reference added by grab_header when return from !dir_emit_dots path. It can cause any path called unregister_sysctl_table will wait forever. The calltrace of CVE-2016-9191: [ 5535.960522] Call Trace: [ 5535.963265] [<ffffffff817cdaaf>] schedule+0x3f/0xa0 [ 5535.968817] [<ffffffff817d33fb>] schedule_timeout+0x3db/0x6f0 [ 5535.975346] [<ffffffff817cf055>] ? wait_for_completion+0x45/0x130 [ 5535.982256] [<ffffffff817cf0d3>] wait_for_completion+0xc3/0x130 [ 5535.988972] [<ffffffff810d1fd0>] ? wake_up_q+0x80/0x80 [ 5535.994804] [<ffffffff8130de64>] drop_sysctl_table+0xc4/0xe0 [ 5536.001227] [<ffffffff8130de17>] drop_sysctl_table+0x77/0xe0 [ 5536.007648] [<ffffffff8130decd>] unregister_sysctl_table+0x4d/0xa0 [ 5536.014654] [<ffffffff8130deff>] unregister_sysctl_table+0x7f/0xa0 [ 5536.021657] [<ffffffff810f57f5>] unregister_sched_domain_sysctl+0x15/0x40 [ 5536.029344] [<ffffffff810d7704>] partition_sched_domains+0x44/0x450 [ 5536.036447] [<ffffffff817d0761>] ? __mutex_unlock_slowpath+0x111/0x1f0 [ 5536.043844] [<ffffffff81167684>] rebuild_sched_domains_locked+0x64/0xb0 [ 5536.051336] [<ffffffff8116789d>] update_flag+0x11d/0x210 [ 5536.057373] [<ffffffff817cf61f>] ? mutex_lock_nested+0x2df/0x450 [ 5536.064186] [<ffffffff81167acb>] ? cpuset_css_offline+0x1b/0x60 [ 5536.070899] [<ffffffff810fce3d>] ? trace_hardirqs_on+0xd/0x10 [ 5536.077420] [<ffffffff817cf61f>] ? mutex_lock_nested+0x2df/0x450 [ 5536.084234] [<ffffffff8115a9f5>] ? css_killed_work_fn+0x25/0x220 [ 5536.091049] [<ffffffff81167ae5>] cpuset_css_offline+0x35/0x60 [ 5536.097571] [<ffffffff8115aa2c>] css_killed_work_fn+0x5c/0x220 [ 5536.104207] [<ffffffff810bc83f>] process_one_work+0x1df/0x710 [ 5536.110736] [<ffffffff810bc7c0>] ? process_one_work+0x160/0x710 [ 5536.117461] [<ffffffff810bce9b>] worker_thread+0x12b/0x4a0 [ 5536.123697] [<ffffffff810bcd70>] ? process_one_work+0x710/0x710 [ 5536.130426] [<ffffffff810c3f7e>] kthread+0xfe/0x120 [ 5536.135991] [<ffffffff817d4baf>] ret_from_fork+0x1f/0x40 [ 5536.142041] [<ffffffff810c3e80>] ? kthread_create_on_node+0x230/0x230 One cgroup maintainer mentioned that "cgroup is trying to offline a cpuset css, which takes place under cgroup_mutex. The offlining ends up trying to drain active usages of a sysctl table which apprently is not happening." The real reason is that proc_sys_readdir doesn't drop reference added by grab_header when return from !dir_emit_dots path. So this cpuset offline path will wait here forever. See here for details: http://www.openwall.com/lists/oss-security/2016/11/04/13 Fixes: f0c3b5093add ("[readdir] convert procfs") Cc: [email protected] Reported-by: CAI Qian <[email protected]> Tested-by: Yang Shukui <[email protected]> Signed-off-by: Zhou Chengming <[email protected]> Acked-by: Al Viro <[email protected]> Signed-off-by: Eric W. Biederman <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void InputMethodBase::OnInputMethodChanged() const { TextInputClient* client = GetTextInputClient(); if (client && client->GetTextInputType() != TEXT_INPUT_TYPE_NONE) client->OnInputMethodChanged(); } Commit Message: cleanup: Use IsTextInputTypeNone() in OnInputMethodChanged(). BUG=None TEST=None Review URL: http://codereview.chromium.org/8986010 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116461 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int mp4client_main(int argc, char **argv) { char c; const char *str; int ret_val = 0; u32 i, times[100], nb_times, dump_mode; u32 simulation_time_in_ms = 0; u32 initial_service_id = 0; Bool auto_exit = GF_FALSE; Bool logs_set = GF_FALSE; Bool start_fs = GF_FALSE; Bool use_rtix = GF_FALSE; Bool pause_at_first = GF_FALSE; Bool no_cfg_save = GF_FALSE; Bool is_cfg_only = GF_FALSE; Double play_from = 0; #ifdef GPAC_MEMORY_TRACKING GF_MemTrackerType mem_track = GF_MemTrackerNone; #endif Double fps = GF_IMPORT_DEFAULT_FPS; Bool fill_ar, visible, do_uncache, has_command; char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic; FILE *logfile = NULL; Float scale = 1; #ifndef WIN32 dlopen(NULL, RTLD_NOW|RTLD_GLOBAL); #endif /*by default use current dir*/ strcpy(the_url, "."); memset(&user, 0, sizeof(GF_User)); dump_mode = DUMP_NONE; fill_ar = visible = do_uncache = has_command = GF_FALSE; url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL; nb_times = 0; times[0] = 0; /*first locate config file if specified*/ for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { the_cfg = argv[i+1]; i++; } else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) { #ifdef GPAC_MEMORY_TRACKING mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple; #else fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg); #endif } else if (!strcmp(arg, "-gui")) { gui_mode = 1; } else if (!strcmp(arg, "-guid")) { gui_mode = 2; } else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) { PrintUsage(); return 0; } } #ifdef GPAC_MEMORY_TRACKING gf_sys_init(mem_track); #else gf_sys_init(GF_MemTrackerNone); #endif gf_sys_set_args(argc, (const char **) argv); cfg_file = gf_cfg_init(the_cfg, NULL); if (!cfg_file) { fprintf(stderr, "Error: Configuration File not found\n"); return 1; } /*if logs are specified, use them*/ if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) { return 1; } if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) { logs_set = GF_TRUE; } if (!gui_mode) { str = gf_cfg_get_key(cfg_file, "General", "ForceGUI"); if (str && !strcmp(str, "yes")) gui_mode = 1; } for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-rti")) { rti_file = argv[i+1]; i++; } else if (!strcmp(arg, "-rtix")) { rti_file = argv[i+1]; i++; use_rtix = GF_TRUE; } else if (!stricmp(arg, "-size")) { /*usage of %ud breaks sscanf on MSVC*/ if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) { forced_width = forced_height = 0; } i++; } else if (!strcmp(arg, "-quiet")) { be_quiet = 1; } else if (!strcmp(arg, "-strict-error")) { gf_log_set_strict_error(1); } else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) { logfile = gf_fopen(argv[i+1], "wt"); gf_log_set_callback(logfile, on_gpac_log); i++; } else if (!strcmp(arg, "-logs") ) { if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) { return 1; } logs_set = GF_TRUE; i++; } else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) { log_time_start = 1; } else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) { log_utc_time = 1; } #if defined(__DARWIN__) || defined(__APPLE__) else if (!strcmp(arg, "-thread")) threading_flags = 0; #else else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD; #endif else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD; else if (!strcmp(arg, "-no-audio")) no_audio = 1; else if (!strcmp(arg, "-no-regulation")) no_regulation = 1; else if (!strcmp(arg, "-fs")) start_fs = 1; else if (!strcmp(arg, "-opt")) { set_cfg_option(argv[i+1]); i++; } else if (!strcmp(arg, "-conf")) { set_cfg_option(argv[i+1]); is_cfg_only=GF_TRUE; i++; } else if (!strcmp(arg, "-ifce")) { gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]); i++; } else if (!stricmp(arg, "-help")) { PrintUsage(); return 1; } else if (!stricmp(arg, "-noprog")) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) { no_cfg_save=1; } else if (!stricmp(arg, "-ntp-shift")) { s32 shift = atoi(argv[i+1]); i++; gf_net_set_ntp_shift(shift); } else if (!stricmp(arg, "-run-for")) { simulation_time_in_ms = atoi(argv[i+1]) * 1000; if (!simulation_time_in_ms) simulation_time_in_ms = 1; /*1ms*/ i++; } else if (!strcmp(arg, "-out")) { out_arg = argv[i+1]; i++; } else if (!stricmp(arg, "-fps")) { fps = atof(argv[i+1]); i++; } else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) { dump_mode &= 0xFFFF0000; if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1; else dump_mode |= DUMP_AVI; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) { if (!strcmp(arg, "-avi") && (nb_times!=2) ) { fprintf(stderr, "Only one time arg found for -avi - check usage\n"); return 1; } i++; } } else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/ dump_mode |= DUMP_RGB_DEPTH_SHAPE; } else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/ dump_mode |= DUMP_RGB_DEPTH; } else if (!strcmp(arg, "-depth")) { dump_mode |= DUMP_DEPTH_ONLY; } else if (!strcmp(arg, "-bmp")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_BMP; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-png")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_PNG; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-raw")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_RAW; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!stricmp(arg, "-scale")) { sscanf(argv[i+1], "%f", &scale); i++; } else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { /* already parsed */ i++; } /*arguments only used in non-gui mode*/ if (!gui_mode) { if (arg[0] != '-') { if (url_arg) { fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg); return 1; } url_arg = arg; } else if (!strcmp(arg, "-loop")) loop_at_end = 1; else if (!strcmp(arg, "-bench")) bench_mode = 1; else if (!strcmp(arg, "-vbench")) bench_mode = 2; else if (!strcmp(arg, "-sbench")) bench_mode = 3; else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE; else if (!strcmp(arg, "-pause")) pause_at_first = 1; else if (!strcmp(arg, "-play-from")) { play_from = atof((const char *) argv[i+1]); i++; } else if (!strcmp(arg, "-speed")) { playback_speed = FLT2FIX( atof((const char *) argv[i+1]) ); if (playback_speed <= 0) playback_speed = FIX_ONE; i++; } else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS; else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT; else if (!strcmp(arg, "-align")) { if (argv[i+1][0]=='m') align_mode = 1; else if (argv[i+1][0]=='b') align_mode = 2; align_mode <<= 8; if (argv[i+1][1]=='m') align_mode |= 1; else if (argv[i+1][1]=='r') align_mode |= 2; i++; } else if (!strcmp(arg, "-fill")) { fill_ar = GF_TRUE; } else if (!strcmp(arg, "-show")) { visible = 1; } else if (!strcmp(arg, "-uncache")) { do_uncache = GF_TRUE; } else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE; else if (!stricmp(arg, "-views")) { views = argv[i+1]; i++; } else if (!stricmp(arg, "-mosaic")) { mosaic = argv[i+1]; i++; } else if (!stricmp(arg, "-com")) { has_command = GF_TRUE; i++; } else if (!stricmp(arg, "-service")) { initial_service_id = atoi(argv[i+1]); i++; } } } if (is_cfg_only) { gf_cfg_del(cfg_file); fprintf(stderr, "GPAC Config updated\n"); return 0; } if (do_uncache) { const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory"); do_flatten_cache(cache_dir); fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir); gf_cfg_del(cfg_file); return 0; } if (dump_mode && !url_arg ) { FILE *test; url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile"); test = url_arg ? gf_fopen(url_arg, "rt") : NULL; if (!test) url_arg = NULL; else gf_fclose(test); if (!url_arg) { fprintf(stderr, "Missing argument for dump\n"); PrintUsage(); if (logfile) gf_fclose(logfile); return 1; } } if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) { gui_mode=1; } #ifdef WIN32 if (gui_mode==1) { const char *opt; TCHAR buffer[1024]; DWORD res = GetCurrentDirectory(1024, buffer); buffer[res] = 0; opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory"); if (strstr(opt, buffer)) { gui_mode=1; } else { gui_mode=2; } } #endif if (gui_mode==1) { hide_shell(1); } if (gui_mode) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } if (!url_arg && simulation_time_in_ms) simulation_time_in_ms += gf_sys_clock(); #if defined(__DARWIN__) || defined(__APPLE__) carbon_init(); #endif if (dump_mode) rti_file = NULL; if (!logs_set) { gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING); } if (rti_file || logfile || log_utc_time || log_time_start) gf_log_set_callback(NULL, on_gpac_log); if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix); { GF_SystemRTInfo rti; if (gf_sys_get_rti(0, &rti, 0)) fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores); } /*setup dumping options*/ if (dump_mode) { user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION; if (!visible) user.init_flags |= GF_TERM_INIT_HIDE; gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output"); no_cfg_save=GF_TRUE; } else { init_w = forced_width; init_h = forced_height; } user.modules = gf_modules_new(NULL, cfg_file); if (user.modules) i = gf_modules_get_count(user.modules); if (!i || !user.modules) { fprintf(stderr, "Error: no modules found - exiting\n"); if (user.modules) gf_modules_del(user.modules); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Modules Found : %d \n", i); str = gf_cfg_get_key(cfg_file, "General", "GPACVersion"); if (!str || strcmp(str, GPAC_FULL_VERSION)) { gf_cfg_del_section(cfg_file, "PluginsCache"); gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION); } user.config = cfg_file; user.EventProc = GPAC_EventProc; /*dummy in this case (global vars) but MUST be non-NULL*/ user.opaque = user.modules; if (threading_flags) user.init_flags |= threading_flags; if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO; if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION; if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE; if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK; if (bench_mode) { gf_cfg_discard_changes(user.config); auto_exit = GF_TRUE; gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output"); if (bench_mode!=2) { gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output"); gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null"); gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable"); } else { gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes"); } } { char dim[50]; sprintf(dim, "%d", forced_width); gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL); sprintf(dim, "%d", forced_height); gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL); } fprintf(stderr, "Loading GPAC Terminal\n"); i = gf_sys_clock(); term = gf_term_new(&user); if (!term) { fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n"); list_modules(user.modules); gf_modules_del(user.modules); gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i); if (bench_mode) { display_rti = 2; gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1); if (bench_mode==1) bench_mode=2; } if (dump_mode) { if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); } else { /*check video output*/ str = gf_cfg_get_key(cfg_file, "Video", "DriverName"); if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n"); /*check audio output*/ str = gf_cfg_get_key(cfg_file, "Audio", "DriverName"); if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n"); str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch"); no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0; } str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled"); if (str && !strcmp(str, "yes")) { str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name"); if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str); } if (rti_file) { str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod"); if (str) { rti_update_time_ms = atoi(str); } else { gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200"); } UpdateRTInfo("At GPAC load time\n"); } Run = 1; if (dump_mode) { if (!nb_times) { times[0] = 0; nb_times++; } ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times); Run = 0; } else if (views) { } /*connect if requested*/ else if (!gui_mode && url_arg) { char *ext; if (strlen(url_arg) >= sizeof(the_url)) { fprintf(stderr, "Input url %s is too long, truncating to %d chars.\n", url_arg, (int)(sizeof(the_url) - 1)); strncpy(the_url, url_arg, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; } else { strcpy(the_url, url_arg); } ext = strrchr(the_url, '.'); if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) { GF_Err e = GF_OK; fprintf(stderr, "Opening Playlist %s\n", the_url); strcpy(pl_path, the_url); /*this is not clean, we need to have a plugin handle playlist for ourselves*/ if (!strncmp("http:", the_url, 5)) { GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e); if (sess) { e = gf_dm_sess_process(sess); if (!e) { strncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1); the_url[sizeof(the_cfg) - 1] = 0; } gf_dm_sess_del(sess); } } playlist = e ? NULL : gf_fopen(the_url, "rt"); readonly_playlist = 1; if (playlist) { request_next_playlist_item = GF_TRUE; } else { if (e) fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) ); fprintf(stderr, "Hit 'h' for help\n\n"); } } else { fprintf(stderr, "Opening URL %s\n", the_url); if (pause_at_first) fprintf(stderr, "[Status: Paused]\n"); gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first); } } else { fprintf(stderr, "Hit 'h' for help\n\n"); str = gf_cfg_get_key(cfg_file, "General", "StartupFile"); if (str) { strncpy(the_url, "MP4Client "GPAC_FULL_VERSION , sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; gf_term_connect(term, str); startup_file = 1; is_connected = 1; } } if (gui_mode==2) gui_mode=0; if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1); if (views) { char szTemp[4046]; sprintf(szTemp, "views://%s", views); gf_term_connect(term, szTemp); } if (mosaic) { char szTemp[4046]; sprintf(szTemp, "mosaic://%s", mosaic); gf_term_connect(term, szTemp); } if (bench_mode) { rti_update_time_ms = 500; bench_mode_start = gf_sys_clock(); } while (Run) { /*we don't want getchar to block*/ if ((gui_mode==1) || !gf_prompt_has_input()) { if (reload) { reload = 0; gf_term_disconnect(term); gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url); } if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) { restart = 0; gf_term_play_from_time(term, 0, 0); } if (request_next_playlist_item) { c = '\n'; request_next_playlist_item = 0; goto force_input; } if (has_command && is_connected) { has_command = GF_FALSE; for (i=0; i<(u32)argc; i++) { if (!strcmp(argv[i], "-com")) { gf_term_scene_update(term, NULL, argv[i+1]); i++; } } } if (initial_service_id && is_connected) { GF_ObjectManager *root_od = gf_term_get_root_object(term); if (root_od) { gf_term_select_service(term, root_od, initial_service_id); initial_service_id = 0; } } if (!use_rtix || display_rti) UpdateRTInfo(NULL); if (term_step) { gf_term_process_step(term); } else { gf_sleep(rti_update_time_ms); } if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) { Run = GF_FALSE; } /*sim time*/ if (simulation_time_in_ms && ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms)) ) { Run = GF_FALSE; } continue; } c = gf_prompt_get_char(); force_input: switch (c) { case 'q': { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; gf_term_send_event(term, &evt); } break; case 'X': exit(0); break; case 'Q': break; case 'o': startup_file = 0; gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read absolute URL, aborting\n"); break; } if (rti_file) init_rti_logs(rti_file, the_url, use_rtix); gf_term_connect(term, the_url); break; case 'O': gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL to the playlist\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read the absolute URL, aborting.\n"); break; } playlist = gf_fopen(the_url, "rt"); if (playlist) { if (1 > fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Cannot read any URL from playlist, aborting.\n"); gf_fclose( playlist); break; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case '\n': case 'N': if (playlist) { int res; gf_term_disconnect(term); res = fscanf(playlist, "%s", the_url); if ((res == EOF) && loop_at_end) { fseek(playlist, 0, SEEK_SET); res = fscanf(playlist, "%s", the_url); } if (res == EOF) { fprintf(stderr, "No more items - exiting\n"); Run = 0; } else if (the_url[0] == '#') { request_next_playlist_item = GF_TRUE; } else { fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect_with_path(term, the_url, pl_path); } } break; case 'P': if (playlist) { u32 count; gf_term_disconnect(term); if (1 > scanf("%u", &count)) { fprintf(stderr, "Cannot read number, aborting.\n"); break; } while (count) { if (fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Failed to read line, aborting\n"); break; } count--; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case 'r': if (is_connected) reload = 1; break; case 'D': if (is_connected) gf_term_disconnect(term); break; case 'p': if (is_connected) { Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE); fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused"); gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED); } break; case 's': if (is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case 'z': case 'T': if (!CanSeek || (Duration<=2000)) { fprintf(stderr, "scene not seekable\n"); } else { Double res; s32 seekTo; fprintf(stderr, "Duration: "); PrintTime(Duration); res = gf_term_get_time_in_ms(term); if (c=='z') { res *= 100; res /= (s64)Duration; fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res); if (scanf("%d", &seekTo) == 1) { if (seekTo > 100) seekTo = 100; res = (Double)(s64)Duration; res /= 100; res *= seekTo; gf_term_play_from_time(term, (u64) (s64) res, 0); } } else { u32 r, h, m, s; fprintf(stderr, " - Current Time: "); PrintTime((u64) res); fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n"); h = m = s = 0; r =scanf("%d:%d:%d", &h, &m, &s); if (r==2) { s = m; m = h; h = 0; } else if (r==1) { s = h; m = h = 0; } if (r && (r<=3)) { u64 time = h*3600 + m*60 + s; gf_term_play_from_time(term, time*1000, 0); } } } break; case 't': { if (is_connected) { fprintf(stderr, "Current Time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, " - Duration: "); PrintTime(Duration); fprintf(stderr, "\n"); } } break; case 'w': if (is_connected) PrintWorldInfo(term); break; case 'v': if (is_connected) PrintODList(term, NULL, 0, 0, "Root"); break; case 'i': if (is_connected) { u32 ID; fprintf(stderr, "Enter OD ID (0 for main OD): "); fflush(stderr); if (scanf("%ud", &ID) == 1) { ViewOD(term, ID, (u32)-1, NULL); } else { char str_url[GF_MAX_PATH]; if (scanf("%s", str_url) == 1) ViewOD(term, 0, (u32)-1, str_url); } } break; case 'j': if (is_connected) { u32 num; do { fprintf(stderr, "Enter OD number (0 for main OD): "); fflush(stderr); } while( 1 > scanf("%ud", &num)); ViewOD(term, (u32)-1, num, NULL); } break; case 'b': if (is_connected) ViewODs(term, 1); break; case 'm': if (is_connected) ViewODs(term, 0); break; case 'l': list_modules(user.modules); break; case 'n': if (is_connected) set_navigation(); break; case 'x': if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0); break; case 'd': if (is_connected) { GF_ObjectManager *odm = NULL; char radname[GF_MAX_PATH], *sExt; GF_Err e; u32 i, count, odid; Bool xml_dump, std_out; radname[0] = 0; do { fprintf(stderr, "Enter Inline OD ID if any or 0 : "); fflush(stderr); } while( 1 > scanf("%ud", &odid)); if (odid) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) break; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_MediaInfo info; odm = gf_term_get_object(term, root_odm, i); if (gf_term_get_object_info(term, odm, &info) == GF_OK) { if (info.od->objectDescriptorID==odid) break; } odm = NULL; } } do { fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: "); fflush(stderr); } while( 1 > scanf("%s", radname)); sExt = strrchr(radname, '.'); xml_dump = 0; if (sExt) { if (!stricmp(sExt, ".x")) xml_dump = 1; sExt[0] = 0; } std_out = strnicmp(radname, "std", 3) ? 0 : 1; e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm); fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e)); } break; case 'c': PrintGPACConfig(); break; case '3': { Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL); if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) { fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer"); } } break; case 'k': { Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE); opt = !opt; fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off"); gf_term_set_option(term, GF_OPT_STRESS_MODE, opt); } break; case '4': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case '5': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case '6': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case '7': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case 'C': switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_DISABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED); break; case GF_MEDIA_CACHE_ENABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache is running - please stop it first\n"); continue; } switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_ENABLED: fprintf(stderr, "Streaming Cache Enabled\n"); break; case GF_MEDIA_CACHE_DISABLED: fprintf(stderr, "Streaming Cache Disabled\n"); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache Running\n"); break; } break; case 'S': case 'A': if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) { gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD); fprintf(stderr, "Streaming Cache stopped\n"); } else { fprintf(stderr, "Streaming Cache not running\n"); } break; case 'R': display_rti = !display_rti; ResetCaption(); break; case 'F': if (display_rti) display_rti = 0; else display_rti = 2; ResetCaption(); break; case 'u': { GF_Err e; char szCom[8192]; fprintf(stderr, "Enter command to send:\n"); fflush(stdin); szCom[0] = 0; if (1 > scanf("%[^\t\n]", szCom)) { fprintf(stderr, "Cannot read command to send, aborting.\n"); break; } e = gf_term_scene_update(term, NULL, szCom); if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e)); } break; case 'e': { GF_Err e; char jsCode[8192]; fprintf(stderr, "Enter JavaScript code to evaluate:\n"); fflush(stdin); jsCode[0] = 0; if (1 > scanf("%[^\t\n]", jsCode)) { fprintf(stderr, "Cannot read code to evaluate, aborting.\n"); break; } e = gf_term_scene_update(term, "application/ecmascript", jsCode); if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e)); } break; case 'L': { char szLog[1024], *cur_logs; cur_logs = gf_log_get_tools_levels(); fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs); gf_free(cur_logs); if (scanf("%s", szLog) < 1) { fprintf(stderr, "Cannot read new log level, aborting.\n"); break; } gf_log_modify_tools_levels(szLog); } break; case 'g': { GF_SystemRTInfo rti; gf_sys_get_rti(rti_update_time_ms, &rti, 0); fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory); } break; case 'M': { u32 size; do { fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE)); } while (1 > scanf("%ud", &size)); gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size); } break; case 'H': { u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE); do { fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate); } while (1 > scanf("%ud", &http_bitrate)); gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate); } break; case 'E': gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1); break; case 'B': switch_bench(!bench_mode); break; case 'Y': { char szOpt[8192]; fprintf(stderr, "Enter option to set (Section:Name=Value):\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read option\n"); break; } set_cfg_option(szOpt); } break; /*extract to PNG*/ case 'Z': { char szFileName[100]; u32 nb_pass, nb_views, offscreen_view = 0; GF_VideoSurface fb; GF_Err e; nb_pass = 1; nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS); if (nb_views>1) { fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2); if (scanf("%d", &offscreen_view) != 1) { offscreen_view = 0; } if (offscreen_view==nb_views+1) { offscreen_view = 1; nb_pass = nb_views; } else if (offscreen_view==nb_views+2) { offscreen_view = 0; nb_pass = nb_views+1; } } while (nb_pass) { nb_pass--; if (offscreen_view) { sprintf(szFileName, "view%d_dump.png", offscreen_view); e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0); } else { sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() ); e = gf_term_get_screen_buffer(term, &fb); } offscreen_view++; if (e) { fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { #ifndef GPAC_DISABLE_AV_PARSERS u32 dst_size = fb.width*fb.height*4; char *dst = (char*)gf_malloc(sizeof(char)*dst_size); e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size); if (e) { fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { FILE *png = gf_fopen(szFileName, "wb"); if (!png) { fprintf(stderr, "Error writing file %s\n", szFileName); nb_pass = 0; } else { gf_fwrite(dst, dst_size, 1, png); gf_fclose(png); fprintf(stderr, "Dump to %s\n", szFileName); } } if (dst) gf_free(dst); gf_term_release_screen_buffer(term, &fb); #endif //GPAC_DISABLE_AV_PARSERS } } fprintf(stderr, "Done: %s\n", szFileName); } break; case 'G': { GF_ObjectManager *root_od, *odm; u32 index; char szOpt[8192]; fprintf(stderr, "Enter 0-based index of object to select or service ID:\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read OD ID\n"); break; } index = atoi(szOpt); odm = NULL; root_od = gf_term_get_root_object(term); if (root_od) { if ( gf_term_find_service(term, root_od, index)) { gf_term_select_service(term, root_od, index); } else { fprintf(stderr, "Cannot find service %d - trying with object index\n", index); odm = gf_term_get_object(term, root_od, index); if (odm) { gf_term_select_object(term, odm); } else { fprintf(stderr, "Cannot find object at index %d\n", index); } } } } break; case 'h': PrintHelp(); break; default: break; } } if (bench_mode) { PrintAVInfo(GF_TRUE); } /*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/ if (simulation_time_in_ms) { gf_log_set_strict_error(0); } i = gf_sys_clock(); gf_term_disconnect(term); if (rti_file) UpdateRTInfo("Disconnected\n"); fprintf(stderr, "Deleting terminal... "); if (playlist) gf_fclose(playlist); #if defined(__DARWIN__) || defined(__APPLE__) carbon_uninit(); #endif gf_term_del(term); fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock()); fprintf(stderr, "GPAC cleanup ...\n"); gf_modules_del(user.modules); if (no_cfg_save) gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (rti_logs) gf_fclose(rti_logs); if (logfile) gf_fclose(logfile); if (gui_mode) { hide_shell(2); } #ifdef GPAC_MEMORY_TRACKING if (mem_track && (gf_memory_size() || gf_file_handles_count() )) { gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO); gf_memory_print(); return 2; } #endif return ret_val; } Commit Message: add some boundary checks on gf_text_get_utf8_line (#1188) CWE ID: CWE-787 Target: 1 Example 2: Code: static char *wm_strdup (const char *str) { size_t l = strlen(str) + 5; char *d = (char *) malloc(l * sizeof(char)); if (d) { strcpy(d, str); return (d); } return (NULL); } Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input Fixes bug #178. CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int hi3660_stub_clk_set_rate(struct clk_hw *hw, unsigned long rate, unsigned long parent_rate) { struct hi3660_stub_clk *stub_clk = to_stub_clk(hw); stub_clk->msg[0] = stub_clk->cmd; stub_clk->msg[1] = rate / MHZ; dev_dbg(stub_clk_chan.cl.dev, "set rate msg[0]=0x%x msg[1]=0x%x\n", stub_clk->msg[0], stub_clk->msg[1]); mbox_send_message(stub_clk_chan.mbox, stub_clk->msg); mbox_client_txdone(stub_clk_chan.mbox, 0); stub_clk->rate = rate; return 0; } Commit Message: clk: hisilicon: hi3660:Fix potential NULL dereference in hi3660_stub_clk_probe() platform_get_resource() may return NULL, add proper check to avoid potential NULL dereferencing. This is detected by Coccinelle semantic patch. @@ expression pdev, res, n, t, e, e1, e2; @@ res = platform_get_resource(pdev, t, n); + if (!res) + return -EINVAL; ... when != res == NULL e = devm_ioremap(e1, res->start, e2); Fixes: 4f16f7ff3bc0 ("clk: hisilicon: Add support for Hi3660 stub clocks") Signed-off-by: Wei Yongjun <[email protected]> Signed-off-by: Stephen Boyd <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) { const xmlChar *ptr; xmlChar cur; xmlChar *name; xmlEntityPtr entity = NULL; if ((str == NULL) || (*str == NULL)) return(NULL); ptr = *str; cur = *ptr; if (cur != '%') return(NULL); ptr++; name = xmlParseStringName(ctxt, &ptr); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStringPEReference: no name\n"); *str = ptr; return(NULL); } cur = *ptr; if (cur != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); xmlFree(name); *str = ptr; return(NULL); } ptr++; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "%%%s; is not a parameter entity\n", name, NULL); } } ctxt->hasPErefs = 1; xmlFree(name); *str = ptr; return(entity); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void skb_warn_bad_offload(const struct sk_buff *skb) { static const netdev_features_t null_features = 0; struct net_device *dev = skb->dev; const char *name = ""; if (!net_ratelimit()) return; if (dev) { if (dev->dev.parent) name = dev_driver_string(dev->dev.parent); else name = netdev_name(dev); } WARN(1, "%s: caps=(%pNF, %pNF) len=%d data_len=%d gso_size=%d " "gso_type=%d ip_summed=%d\n", name, dev ? &dev->features : &null_features, skb->sk ? &skb->sk->sk_route_caps : &null_features, skb->len, skb->data_len, skb_shinfo(skb)->gso_size, skb_shinfo(skb)->gso_type, skb->ip_summed); } Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation. When drivers express support for TSO of encapsulated packets, they only mean that they can do it for one layer of encapsulation. Supporting additional levels would mean updating, at a minimum, more IP length fields and they are unaware of this. No encapsulation device expresses support for handling offloaded encapsulated packets, so we won't generate these types of frames in the transmit path. However, GRO doesn't have a check for multiple levels of encapsulation and will attempt to build them. UDP tunnel GRO actually does prevent this situation but it only handles multiple UDP tunnels stacked on top of each other. This generalizes that solution to prevent any kind of tunnel stacking that would cause problems. Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack") Signed-off-by: Jesse Gross <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-400 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ssl3_get_cert_verify(SSL *s) { EVP_PKEY *pkey = NULL; unsigned char *p; int al, ok, ret = 0; long n; int type = 0, i, j; X509 *peer; const EVP_MD *md = NULL; EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); n = s->method->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A, SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return ((int)n); if (s->session->peer != NULL) { peer = s->session->peer; pkey = X509_get_pubkey(peer); type = X509_certificate_type(peer, pkey); } else { peer = NULL; pkey = NULL; } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) { s->s3->tmp.reuse_message = 1; if (peer != NULL) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_MISSING_VERIFY_MESSAGE); goto f_err; } ret = 1; goto end; } if (peer == NULL) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_NO_CLIENT_CERT_RECEIVED); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } if (!(type & EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE); al = SSL_AD_ILLEGAL_PARAMETER; goto f_err; } if (s->s3->change_cipher_spec) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_CCS_RECEIVED_EARLY); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } /* we now have a signature that we need to verify */ p = (unsigned char *)s->init_msg; /* Check for broken implementations of GOST ciphersuites */ /* * If key is GOST and n is exactly 64, it is bare signature without * length field */ if (n == 64 && (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)) { i = 64; } else { if (SSL_USE_SIGALGS(s)) { int rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } else if (rv == 0) { al = SSL_AD_DECODE_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } n2s(p, i); n -= 2; if (i > n) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH); al = SSL_AD_DECODE_ERROR; goto f_err; } } j = EVP_PKEY_size(pkey); if ((i > j) || (n > j) || (n <= 0)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE); al = SSL_AD_DECODE_ERROR; goto f_err; } if (SSL_USE_SIGALGS(s)) { long hdatalen = 0; void *hdata; hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR); al = SSL_AD_INTERNAL_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n", EVP_MD_name(md)); #endif if (!EVP_VerifyInit_ex(&mctx, md, NULL) || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB); al = SSL_AD_INTERNAL_ERROR; goto f_err; } if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) { al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE); goto f_err; } } else #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md, MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i, pkey->pkey.rsa); if (i < 0) { al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { j = DSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa); if (j <= 0) { /* bad signature */ al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { j = ECDSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec); if (j <= 0) { /* bad signature */ al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else #endif if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) { unsigned char signature[64]; int idx; EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL); EVP_PKEY_verify_init(pctx); if (i != 64) { fprintf(stderr, "GOST signature length is %d", i); } for (idx = 0; idx < 64; idx++) { signature[63 - idx] = p[idx]; } j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md, 32); EVP_PKEY_CTX_free(pctx); if (j <= 0) { al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR); al = SSL_AD_UNSUPPORTED_CERTIFICATE; goto f_err; } ret = 1; if (0) { f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); } end: if (s->s3->handshake_buffer) { BIO_free(s->s3->handshake_buffer); s->s3->handshake_buffer = NULL; s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE; } EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_free(pkey); return (ret); } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int install_user_keyrings(void) { struct user_struct *user; const struct cred *cred; struct key *uid_keyring, *session_keyring; key_perm_t user_keyring_perm; char buf[20]; int ret; uid_t uid; user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL; cred = current_cred(); user = cred->user; uid = from_kuid(cred->user_ns, user->uid); kenter("%p{%u}", user, uid); if (user->uid_keyring && user->session_keyring) { kleave(" = 0 [exist]"); return 0; } mutex_lock(&key_user_keyring_mutex); ret = 0; if (!user->uid_keyring) { /* get the UID-specific keyring * - there may be one in existence already as it may have been * pinned by a session, but the user_struct pointing to it * may have been destroyed by setuid */ sprintf(buf, "_uid.%u", uid); uid_keyring = find_keyring_by_name(buf, true); if (IS_ERR(uid_keyring)) { uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID, cred, user_keyring_perm, KEY_ALLOC_IN_QUOTA, NULL, NULL); if (IS_ERR(uid_keyring)) { ret = PTR_ERR(uid_keyring); goto error; } } /* get a default session keyring (which might also exist * already) */ sprintf(buf, "_uid_ses.%u", uid); session_keyring = find_keyring_by_name(buf, true); if (IS_ERR(session_keyring)) { session_keyring = keyring_alloc(buf, user->uid, INVALID_GID, cred, user_keyring_perm, KEY_ALLOC_IN_QUOTA, NULL, NULL); if (IS_ERR(session_keyring)) { ret = PTR_ERR(session_keyring); goto error_release; } /* we install a link from the user session keyring to * the user keyring */ ret = key_link(session_keyring, uid_keyring); if (ret < 0) goto error_release_both; } /* install the keyrings */ user->uid_keyring = uid_keyring; user->session_keyring = session_keyring; } mutex_unlock(&key_user_keyring_mutex); kleave(" = 0"); return 0; error_release_both: key_put(session_keyring); error_release: key_put(uid_keyring); error: mutex_unlock(&key_user_keyring_mutex); kleave(" = %d", ret); return ret; } Commit Message: KEYS: prevent creating a different user's keyrings It was possible for an unprivileged user to create the user and user session keyrings for another user. For example: sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u keyctl add keyring _uid_ses.4000 "" @u sleep 15' & sleep 1 sudo -u '#4000' keyctl describe @u sudo -u '#4000' keyctl describe @us This is problematic because these "fake" keyrings won't have the right permissions. In particular, the user who created them first will own them and will have full access to them via the possessor permissions, which can be used to compromise the security of a user's keys: -4: alswrv-----v------------ 3000 0 keyring: _uid.4000 -5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000 Fix it by marking user and user session keyrings with a flag KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session keyring by name, skip all keyrings that don't have the flag set. Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed") Cc: <[email protected]> [v2.6.26+] Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID: Target: 1 Example 2: Code: MYSQLND_METHOD(mysqlnd_protocol, get_rset_header_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_rset_header * packet = mnd_pecalloc(1, packet_methods[PROT_RSET_HEADER_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_rset_header_packet"); if (packet) { packet->header.m = &packet_methods[PROT_RSET_HEADER_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } Commit Message: Fix bug #72293 - Heap overflow in mysqlnd related to BIT fields CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int mnt_clone_write(struct vfsmount *mnt) { /* superblock may be r/o */ if (__mnt_is_readonly(mnt)) return -EROFS; preempt_disable(); mnt_inc_writers(real_mount(mnt)); preempt_enable(); return 0; } Commit Message: vfs: Carefully propogate mounts across user namespaces As a matter of policy MNT_READONLY should not be changable if the original mounter had more privileges than creator of the mount namespace. Add the flag CL_UNPRIVILEGED to note when we are copying a mount from a mount namespace that requires more privileges to a mount namespace that requires fewer privileges. When the CL_UNPRIVILEGED flag is set cause clone_mnt to set MNT_NO_REMOUNT if any of the mnt flags that should never be changed are set. This protects both mount propagation and the initial creation of a less privileged mount namespace. Cc: [email protected] Acked-by: Serge Hallyn <[email protected]> Reported-by: Andy Lutomirski <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: poly_path(PG_FUNCTION_ARGS) { POLYGON *poly = PG_GETARG_POLYGON_P(0); PATH *path; int size; int i; size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * poly->npts; path = (PATH *) palloc(size); SET_VARSIZE(path, size); path->npts = poly->npts; path->closed = TRUE; /* prevent instability in unused pad bytes */ path->dummy = 0; for (i = 0; i < poly->npts; i++) { path->p[i].x = poly->p[i].x; path->p[i].y = poly->p[i].y; } PG_RETURN_PATH_P(path); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189 Target: 1 Example 2: Code: static int ProcRenderCreateConicalGradient (ClientPtr client) { PicturePtr pPicture; int len; int error = 0; xFixed *stops; xRenderColor *colors; REQUEST(xRenderCreateConicalGradientReq); REQUEST_AT_LEAST_SIZE(xRenderCreateConicalGradientReq); LEGAL_NEW_RESOURCE(stuff->pid, client); len = (client->req_len << 2) - sizeof(xRenderCreateConicalGradientReq); if (len != stuff->nStops*(sizeof(xFixed) + sizeof(xRenderColor))) return BadLength; stops = (xFixed *)(stuff + 1); colors = (xRenderColor *)(stops + stuff->nStops); pPicture = CreateConicalGradientPicture (stuff->pid, &stuff->center, stuff->angle, stuff->nStops, stops, colors, &error); if (!pPicture) return error; /* security creation/labeling check */ error = XaceHook(XACE_RESOURCE_ACCESS, client, stuff->pid, PictureType, pPicture, RT_NONE, NULL, DixCreateAccess); if (error != Success) return error; if (!AddResource (stuff->pid, PictureType, (pointer)pPicture)) return BadAlloc; return Success; } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret; mbedtls_mpi r, s; mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); #if defined(MBEDTLS_ECDSA_DETERMINISTIC) (void) f_rng; (void) p_rng; MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det( &ctx->grp, &r, &s, &ctx->d, hash, hlen, md_alg ) ); #else (void) md_alg; MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng ) ); #endif MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) ); cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int http_receive_data(HTTPContext *c) { HTTPContext *c1; int len, loop_run = 0; while (c->chunked_encoding && !c->chunk_size && c->buffer_end > c->buffer_ptr) { /* read chunk header, if present */ len = recv(c->fd, c->buffer_ptr, 1, 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) /* error : close connection */ goto fail; return 0; } else if (len == 0) { /* end of connection : close it */ goto fail; } else if (c->buffer_ptr - c->buffer >= 2 && !memcmp(c->buffer_ptr - 1, "\r\n", 2)) { c->chunk_size = strtol(c->buffer, 0, 16); if (c->chunk_size == 0) // end of stream goto fail; c->buffer_ptr = c->buffer; break; } else if (++loop_run > 10) /* no chunk header, abort */ goto fail; else c->buffer_ptr++; } if (c->buffer_end > c->buffer_ptr) { len = recv(c->fd, c->buffer_ptr, FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) /* error : close connection */ goto fail; } else if (len == 0) /* end of connection : close it */ goto fail; else { c->chunk_size -= len; c->buffer_ptr += len; c->data_count += len; update_datarate(&c->datarate, c->data_count); } } if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) { if (c->buffer[0] != 'f' || c->buffer[1] != 'm') { http_log("Feed stream has become desynchronized -- disconnecting\n"); goto fail; } } if (c->buffer_ptr >= c->buffer_end) { FFServerStream *feed = c->stream; /* a packet has been received : write it in the store, except * if header */ if (c->data_count > FFM_PACKET_SIZE) { /* XXX: use llseek or url_seek * XXX: Should probably fail? */ if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1) http_log("Seek to %"PRId64" failed\n", feed->feed_write_index); if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) { http_log("Error writing to feed file: %s\n", strerror(errno)); goto fail; } feed->feed_write_index += FFM_PACKET_SIZE; /* update file size */ if (feed->feed_write_index > c->stream->feed_size) feed->feed_size = feed->feed_write_index; /* handle wrap around if max file size reached */ if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size) feed->feed_write_index = FFM_PACKET_SIZE; /* write index */ if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) { http_log("Error writing index to feed file: %s\n", strerror(errno)); goto fail; } /* wake up any waiting connections */ for(c1 = first_http_ctx; c1; c1 = c1->next) { if (c1->state == HTTPSTATE_WAIT_FEED && c1->stream->feed == c->stream->feed) c1->state = HTTPSTATE_SEND_DATA; } } else { /* We have a header in our hands that contains useful data */ AVFormatContext *s = avformat_alloc_context(); AVIOContext *pb; AVInputFormat *fmt_in; int i; if (!s) goto fail; /* use feed output format name to find corresponding input format */ fmt_in = av_find_input_format(feed->fmt->name); if (!fmt_in) goto fail; pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer, 0, NULL, NULL, NULL, NULL); if (!pb) goto fail; pb->seekable = 0; s->pb = pb; if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) { av_freep(&pb); goto fail; } /* Now we have the actual streams */ if (s->nb_streams != feed->nb_streams) { avformat_close_input(&s); av_freep(&pb); http_log("Feed '%s' stream number does not match registered feed\n", c->stream->feed_filename); goto fail; } for (i = 0; i < s->nb_streams; i++) { LayeredAVStream *fst = feed->streams[i]; AVStream *st = s->streams[i]; avcodec_parameters_to_context(fst->codec, st->codecpar); avcodec_parameters_from_context(fst->codecpar, fst->codec); } avformat_close_input(&s); av_freep(&pb); } c->buffer_ptr = c->buffer; } return 0; fail: c->stream->feed_opened = 0; close(c->feed_fd); /* wake up any waiting connections to stop waiting for feed */ for(c1 = first_http_ctx; c1; c1 = c1->next) { if (c1->state == HTTPSTATE_WAIT_FEED && c1->stream->feed == c->stream->feed) c1->state = HTTPSTATE_SEND_DATA_TRAILER; } return -1; } Commit Message: ffserver: Check chunk size Fixes out of array access Fixes: poc_ffserver.py Found-by: Paul Cher <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch( base::CommandLine* to_command_line, const base::CommandLine& from_command_line, version_info::Channel channel) { #if defined(OS_ANDROID) const version_info::Channel kMaxDisableEncryptionChannel = version_info::Channel::BETA; #else const version_info::Channel kMaxDisableEncryptionChannel = version_info::Channel::DEV; #endif if (channel <= kMaxDisableEncryptionChannel) { static const char* const kWebRtcDevSwitchNames[] = { switches::kDisableWebRtcEncryption, }; to_command_line->CopySwitchesFrom(from_command_line, kWebRtcDevSwitchNames, base::size(kWebRtcDevSwitchNames)); } } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Browser::UpdateCommandsForBookmarkEditing() { bool enabled = profile_->GetPrefs()->GetBoolean(prefs::kEditBookmarksEnabled) && browser_defaults::bookmarks_enabled; command_updater_.UpdateCommandEnabled(IDC_BOOKMARK_PAGE, enabled && is_type_tabbed()); command_updater_.UpdateCommandEnabled(IDC_BOOKMARK_ALL_TABS, enabled && CanBookmarkAllTabs()); } Commit Message: Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const { PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength)); tTcpIpPacketParsingResult packetReview; packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum, __FUNCTION__); if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) { auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset; auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader); auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0; VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen); VHeader->gso_size = (USHORT)m_ParentNBL->MSS(); VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen); VHeader->csum_offset = TCP_CHECKSUM_OFFSET; } } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: void BluetoothSocketAbstractConnectFunction::OnConnectError( const std::string& message) { DCHECK_CURRENTLY_ON(work_thread_id()); Respond(Error(message)); } Commit Message: chrome.bluetoothSocket: Fix regression in send() In https://crrev.com/c/997098, params_ was changed to a local variable, but it needs to last longer than that since net::WrappedIOBuffer may use the data after the local variable goes out of scope. This CL changed it back to be an instance variable. Bug: 851799 Change-Id: I392f8acaef4c6473d6ea4fbee7209445aa09112e Reviewed-on: https://chromium-review.googlesource.com/1103676 Reviewed-by: Toni Barzic <[email protected]> Commit-Queue: Sonny Sasaka <[email protected]> Cr-Commit-Position: refs/heads/master@{#568137} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void HostCache::Set(const Key& key, const Entry& entry, base::TimeTicks now, base::TimeDelta ttl) { TRACE_EVENT0(kNetTracingCategory, "HostCache::Set"); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (caching_is_disabled()) return; auto it = entries_.find(key); if (it != entries_.end()) { bool is_stale = it->second.IsStale(now, network_changes_); RecordSet(is_stale ? SET_UPDATE_STALE : SET_UPDATE_VALID, now, &it->second, entry); entries_.erase(it); } else { if (size() == max_entries_) EvictOneEntry(now); RecordSet(SET_INSERT, now, nullptr, entry); } AddEntry(Key(key), Entry(entry, now, ttl, network_changes_)); } Commit Message: Add PersistenceDelegate to HostCache PersistenceDelegate is a new interface for persisting the contents of the HostCache. This commit includes the interface itself, the logic in HostCache for interacting with it, and a mock implementation of the interface for testing. It does not include support for immediate data removal since that won't be needed for the currently planned use case. BUG=605149 Review-Url: https://codereview.chromium.org/2943143002 Cr-Commit-Position: refs/heads/master@{#481015} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŧтҭ] > t;" "[ƅьҍв] > b; [ωшщ] > w; [мӎ] > m;" "п > n; [єҽҿ] > e; ґ > r; ғ > f; ҫ > c;" "ұ > y; [χҳӽӿ] > x;" #if defined(OS_WIN) "ӏ > i;" #else "ӏ > l;" #endif "ԃ > d; ԍ > g; ട > s"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Add more entries to the confusability mapping U+014B (ŋ) => n U+1004 (င) => c U+100c (ဌ) => g U+1042 (၂) => j U+1054 (ၔ) => e Bug: 811117,808316 Test: components_unittests -gtest_filter=*IDN* Change-Id: I29f73c48d665bd9070050bd7f0080563635b9c63 Reviewed-on: https://chromium-review.googlesource.com/919423 Reviewed-by: Peter Kasting <[email protected]> Commit-Queue: Jungshik Shin <[email protected]> Cr-Commit-Position: refs/heads/master@{#536955} CWE ID: Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoMatrixLoadfCHROMIUM( GLenum matrixMode, const volatile GLfloat* m) { NOTIMPLEMENTED(); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void reference_32x32_dct_2d(const int16_t input[kNumCoeffs], double output[kNumCoeffs]) { for (int i = 0; i < 32; ++i) { double temp_in[32], temp_out[32]; for (int j = 0; j < 32; ++j) temp_in[j] = input[j*32 + i]; reference_32x32_dct_1d(temp_in, temp_out, 1); for (int j = 0; j < 32; ++j) output[j * 32 + i] = temp_out[j]; } for (int i = 0; i < 32; ++i) { double temp_in[32], temp_out[32]; for (int j = 0; j < 32; ++j) temp_in[j] = output[j + i*32]; reference_32x32_dct_1d(temp_in, temp_out, 1); for (int j = 0; j < 32; ++j) output[j + i * 32] = temp_out[j] / 4; } } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt, const xmlChar *prefix) { if (ctxt && prefix && !xmlXPathRegisterNs(ctxt, prefix, (const xmlChar *) EXSLT_STRINGS_NAMESPACE) && !xmlXPathRegisterFuncNS(ctxt, (const xmlChar *) "encode-uri", (const xmlChar *) EXSLT_STRINGS_NAMESPACE, exsltStrEncodeUriFunction) && !xmlXPathRegisterFuncNS(ctxt, (const xmlChar *) "decode-uri", (const xmlChar *) EXSLT_STRINGS_NAMESPACE, exsltStrDecodeUriFunction) && !xmlXPathRegisterFuncNS(ctxt, (const xmlChar *) "padding", (const xmlChar *) EXSLT_STRINGS_NAMESPACE, exsltStrPaddingFunction) && !xmlXPathRegisterFuncNS(ctxt, (const xmlChar *) "align", (const xmlChar *) EXSLT_STRINGS_NAMESPACE, exsltStrAlignFunction) && !xmlXPathRegisterFuncNS(ctxt, (const xmlChar *) "concat", (const xmlChar *) EXSLT_STRINGS_NAMESPACE, exsltStrConcatFunction) && !xmlXPathRegisterFuncNS(ctxt, (const xmlChar *) "replace", (const xmlChar *) EXSLT_STRINGS_NAMESPACE, exsltStrReplaceFunction)) { return 0; } return -1; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 1 Example 2: Code: void get_random_bytes(void *buf, int nbytes) { extract_entropy(&nonblocking_pool, buf, nbytes, 0, 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 <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) { blink::WebLocalFrame* frame = NULL; GetPrintFrame(&frame); DCHECK(frame); auto plugin = delegate_->GetPdfElement(frame); if (!plugin.isNull()) { PrintNode(plugin); return; } print_preview_context_.InitWithFrame(frame); RequestPrintPreview(selection_only ? PRINT_PREVIEW_USER_INITIATED_SELECTION : PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ff_h263_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; MpegEncContext *s = avctx->priv_data; int ret; int slice_ret = 0; AVFrame *pict = data; /* no supplementary picture */ if (buf_size == 0) { /* special case for last picture */ if (s->low_delay == 0 && s->next_picture_ptr) { if ((ret = av_frame_ref(pict, s->next_picture_ptr->f)) < 0) return ret; s->next_picture_ptr = NULL; *got_frame = 1; } return 0; } if (s->avctx->flags & AV_CODEC_FLAG_TRUNCATED) { int next; if (CONFIG_MPEG4_DECODER && s->codec_id == AV_CODEC_ID_MPEG4) { next = ff_mpeg4_find_frame_end(&s->parse_context, buf, buf_size); } else if (CONFIG_H263_DECODER && s->codec_id == AV_CODEC_ID_H263) { next = ff_h263_find_frame_end(&s->parse_context, buf, buf_size); } else if (CONFIG_H263P_DECODER && s->codec_id == AV_CODEC_ID_H263P) { next = ff_h263_find_frame_end(&s->parse_context, buf, buf_size); } else { av_log(s->avctx, AV_LOG_ERROR, "this codec does not support truncated bitstreams\n"); return AVERROR(ENOSYS); } if (ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0) return buf_size; } retry: if (s->divx_packed && s->bitstream_buffer_size) { int i; for(i=0; i < buf_size-3; i++) { if (buf[i]==0 && buf[i+1]==0 && buf[i+2]==1) { if (buf[i+3]==0xB0) { av_log(s->avctx, AV_LOG_WARNING, "Discarding excessive bitstream in packed xvid\n"); s->bitstream_buffer_size = 0; } break; } } } if (s->bitstream_buffer_size && (s->divx_packed || buf_size <= MAX_NVOP_SIZE)) // divx 5.01+/xvid frame reorder ret = init_get_bits8(&s->gb, s->bitstream_buffer, s->bitstream_buffer_size); else ret = init_get_bits8(&s->gb, buf, buf_size); s->bitstream_buffer_size = 0; if (ret < 0) return ret; if (!s->context_initialized) ff_mpv_idct_init(s); /* let's go :-) */ if (CONFIG_WMV2_DECODER && s->msmpeg4_version == 5) { ret = ff_wmv2_decode_picture_header(s); } else if (CONFIG_MSMPEG4_DECODER && s->msmpeg4_version) { ret = ff_msmpeg4_decode_picture_header(s); } else if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4) { if (s->avctx->extradata_size && s->picture_number == 0) { GetBitContext gb; if (init_get_bits8(&gb, s->avctx->extradata, s->avctx->extradata_size) >= 0 ) ff_mpeg4_decode_picture_header(avctx->priv_data, &gb); } ret = ff_mpeg4_decode_picture_header(avctx->priv_data, &s->gb); } else if (CONFIG_H263I_DECODER && s->codec_id == AV_CODEC_ID_H263I) { ret = ff_intel_h263_decode_picture_header(s); } else if (CONFIG_FLV_DECODER && s->h263_flv) { ret = ff_flv_decode_picture_header(s); } else { ret = ff_h263_decode_picture_header(s); } if (ret < 0 || ret == FRAME_SKIPPED) { if ( s->width != avctx->coded_width || s->height != avctx->coded_height) { av_log(s->avctx, AV_LOG_WARNING, "Reverting picture dimensions change due to header decoding failure\n"); s->width = avctx->coded_width; s->height= avctx->coded_height; } } if (ret == FRAME_SKIPPED) return get_consumed_bytes(s, buf_size); /* skip if the header was thrashed */ if (ret < 0) { av_log(s->avctx, AV_LOG_ERROR, "header damaged\n"); return ret; } if (!s->context_initialized) { avctx->pix_fmt = h263_get_format(avctx); if ((ret = ff_mpv_common_init(s)) < 0) return ret; } if (!s->current_picture_ptr || s->current_picture_ptr->f->data[0]) { int i = ff_find_unused_picture(s->avctx, s->picture, 0); if (i < 0) return i; s->current_picture_ptr = &s->picture[i]; } avctx->has_b_frames = !s->low_delay; if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4) { if (ff_mpeg4_workaround_bugs(avctx) == 1) goto retry; if (s->studio_profile != (s->idsp.idct == NULL)) ff_mpv_idct_init(s); } /* After H.263 & MPEG-4 header decode we have the height, width, * and other parameters. So then we could init the picture. * FIXME: By the way H.263 decoder is evolving it should have * an H263EncContext */ if (s->width != avctx->coded_width || s->height != avctx->coded_height || s->context_reinit) { /* H.263 could change picture size any time */ s->context_reinit = 0; ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; ff_set_sar(avctx, avctx->sample_aspect_ratio); if ((ret = ff_mpv_common_frame_size_change(s))) return ret; if (avctx->pix_fmt != h263_get_format(avctx)) { av_log(avctx, AV_LOG_ERROR, "format change not supported\n"); avctx->pix_fmt = AV_PIX_FMT_NONE; return AVERROR_UNKNOWN; } } if (s->codec_id == AV_CODEC_ID_H263 || s->codec_id == AV_CODEC_ID_H263P || s->codec_id == AV_CODEC_ID_H263I) s->gob_index = H263_GOB_HEIGHT(s->height); s->current_picture.f->pict_type = s->pict_type; s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I; /* skip B-frames if we don't have reference frames */ if (!s->last_picture_ptr && (s->pict_type == AV_PICTURE_TYPE_B || s->droppable)) return get_consumed_bytes(s, buf_size); if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) || (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I) || avctx->skip_frame >= AVDISCARD_ALL) return get_consumed_bytes(s, buf_size); if (s->next_p_frame_damaged) { if (s->pict_type == AV_PICTURE_TYPE_B) return get_consumed_bytes(s, buf_size); else s->next_p_frame_damaged = 0; } if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) { s->me.qpel_put = s->qdsp.put_qpel_pixels_tab; s->me.qpel_avg = s->qdsp.avg_qpel_pixels_tab; } else { s->me.qpel_put = s->qdsp.put_no_rnd_qpel_pixels_tab; s->me.qpel_avg = s->qdsp.avg_qpel_pixels_tab; } if ((ret = ff_mpv_frame_start(s, avctx)) < 0) return ret; if (!s->divx_packed) ff_thread_finish_setup(avctx); if (avctx->hwaccel) { ret = avctx->hwaccel->start_frame(avctx, s->gb.buffer, s->gb.buffer_end - s->gb.buffer); if (ret < 0 ) return ret; } ff_mpeg_er_frame_start(s); /* the second part of the wmv2 header contains the MB skip bits which * are stored in current_picture->mb_type which is not available before * ff_mpv_frame_start() */ if (CONFIG_WMV2_DECODER && s->msmpeg4_version == 5) { ret = ff_wmv2_decode_secondary_picture_header(s); if (ret < 0) return ret; if (ret == 1) goto frame_end; } /* decode each macroblock */ s->mb_x = 0; s->mb_y = 0; slice_ret = decode_slice(s); while (s->mb_y < s->mb_height) { if (s->msmpeg4_version) { if (s->slice_height == 0 || s->mb_x != 0 || slice_ret < 0 || (s->mb_y % s->slice_height) != 0 || get_bits_left(&s->gb) < 0) break; } else { int prev_x = s->mb_x, prev_y = s->mb_y; if (ff_h263_resync(s) < 0) break; if (prev_y * s->mb_width + prev_x < s->mb_y * s->mb_width + s->mb_x) s->er.error_occurred = 1; } if (s->msmpeg4_version < 4 && s->h263_pred) ff_mpeg4_clean_buffers(s); if (decode_slice(s) < 0) slice_ret = AVERROR_INVALIDDATA; } if (s->msmpeg4_version && s->msmpeg4_version < 4 && s->pict_type == AV_PICTURE_TYPE_I) if (!CONFIG_MSMPEG4_DECODER || ff_msmpeg4_decode_ext_header(s, buf_size) < 0) s->er.error_status_table[s->mb_num - 1] = ER_MB_ERROR; av_assert1(s->bitstream_buffer_size == 0); frame_end: ff_er_frame_end(&s->er); if (avctx->hwaccel) { ret = avctx->hwaccel->end_frame(avctx); if (ret < 0) return ret; } ff_mpv_frame_end(s); if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4) ff_mpeg4_frame_end(avctx, buf, buf_size); if (!s->divx_packed && avctx->hwaccel) ff_thread_finish_setup(avctx); av_assert1(s->current_picture.f->pict_type == s->current_picture_ptr->f->pict_type); av_assert1(s->current_picture.f->pict_type == s->pict_type); if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) { if ((ret = av_frame_ref(pict, s->current_picture_ptr->f)) < 0) return ret; ff_print_debug_info(s, s->current_picture_ptr, pict); ff_mpv_export_qp_table(s, pict, s->current_picture_ptr, FF_QSCALE_TYPE_MPEG1); } else if (s->last_picture_ptr) { if ((ret = av_frame_ref(pict, s->last_picture_ptr->f)) < 0) return ret; ff_print_debug_info(s, s->last_picture_ptr, pict); ff_mpv_export_qp_table(s, pict, s->last_picture_ptr, FF_QSCALE_TYPE_MPEG1); } if (s->last_picture_ptr || s->low_delay) { if ( pict->format == AV_PIX_FMT_YUV420P && (s->codec_tag == AV_RL32("GEOV") || s->codec_tag == AV_RL32("GEOX"))) { int x, y, p; av_frame_make_writable(pict); for (p=0; p<3; p++) { int w = AV_CEIL_RSHIFT(pict-> width, !!p); int h = AV_CEIL_RSHIFT(pict->height, !!p); int linesize = pict->linesize[p]; for (y=0; y<(h>>1); y++) for (x=0; x<w; x++) FFSWAP(int, pict->data[p][x + y*linesize], pict->data[p][x + (h-1-y)*linesize]); } } *got_frame = 1; } if (slice_ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE)) return slice_ret; else return get_consumed_bytes(s, buf_size); } Commit Message: avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile The profile field is changed by code inside and outside the decoder, its not a reliable indicator of the internal codec state. Maintaining it consistency with studio_profile is messy. Its easier to just avoid it and use only studio_profile Fixes: assertion failure Fixes: ffmpeg_crash_9.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-617 Target: 1 Example 2: Code: void sock_efree(struct sk_buff *skb) { sock_put(skb->sk); } Commit Message: net: avoid signed overflows for SO_{SND|RCV}BUFFORCE CAP_NET_ADMIN users should not be allowed to set negative sk_sndbuf or sk_rcvbuf values, as it can lead to various memory corruptions, crashes, OOM... Note that before commit 82981930125a ("net: cleanups in sock_setsockopt()"), the bug was even more serious, since SO_SNDBUF and SO_RCVBUF were vulnerable. This needs to be backported to all known linux kernels. Again, many thanks to syzkaller team for discovering this gem. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GDataDirectory::~GDataDirectory() { RemoveChildren(); } Commit Message: gdata: Define the resource ID for the root directory Per the spec, the resource ID for the root directory is defined as "folder:root". Add the resource ID to the root directory in our file system representation so we can look up the root directory by the resource ID. BUG=127697 TEST=add unit tests Review URL: https://chromiumcodereview.appspot.com/10332253 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync( Blob* blob) { loader_->Start(blob->GetBlobDataHandle()); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Marijn Kruisselbrink <[email protected]> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416 Target: 1 Example 2: Code: bool OptimizationHintsComponentInstallerPolicy::VerifyInstallation( const base::DictionaryValue& manifest, const base::FilePath& install_dir) const { return base::PathExists(install_dir); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: call_bind_status(struct rpc_task *task) { int status = -EIO; if (task->tk_status >= 0) { dprint_status(task); task->tk_status = 0; task->tk_action = call_connect; return; } switch (task->tk_status) { case -ENOMEM: dprintk("RPC: %5u rpcbind out of memory\n", task->tk_pid); rpc_delay(task, HZ >> 2); goto retry_timeout; case -EACCES: dprintk("RPC: %5u remote rpcbind: RPC program/version " "unavailable\n", task->tk_pid); /* fail immediately if this is an RPC ping */ if (task->tk_msg.rpc_proc->p_proc == 0) { status = -EOPNOTSUPP; break; } rpc_delay(task, 3*HZ); goto retry_timeout; case -ETIMEDOUT: dprintk("RPC: %5u rpcbind request timed out\n", task->tk_pid); goto retry_timeout; case -EPFNOSUPPORT: /* server doesn't support any rpcbind version we know of */ dprintk("RPC: %5u unrecognized remote rpcbind service\n", task->tk_pid); break; case -EPROTONOSUPPORT: dprintk("RPC: %5u remote rpcbind version unavailable, retrying\n", task->tk_pid); task->tk_status = 0; task->tk_action = call_bind; return; case -ECONNREFUSED: /* connection problems */ case -ECONNRESET: case -ENOTCONN: case -EHOSTDOWN: case -EHOSTUNREACH: case -ENETUNREACH: case -EPIPE: dprintk("RPC: %5u remote rpcbind unreachable: %d\n", task->tk_pid, task->tk_status); if (!RPC_IS_SOFTCONN(task)) { rpc_delay(task, 5*HZ); goto retry_timeout; } status = task->tk_status; break; default: dprintk("RPC: %5u unrecognized rpcbind error (%d)\n", task->tk_pid, -task->tk_status); } rpc_exit(task, status); return; retry_timeout: task->tk_action = call_timeout; } Commit Message: NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> Cc: [email protected] CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickBooleanType sixel_decode(unsigned char /* in */ *p, /* sixel bytes */ unsigned char /* out */ **pixels, /* decoded pixels */ size_t /* out */ *pwidth, /* image width */ size_t /* out */ *pheight, /* image height */ unsigned char /* out */ **palette, /* ARGB palette */ size_t /* out */ *ncolors /* palette size (<= 256) */) { int n, i, r, g, b, sixel_vertical_mask, c; int posision_x, posision_y; int max_x, max_y; int attributed_pan, attributed_pad; int attributed_ph, attributed_pv; int repeat_count, color_index, max_color_index = 2, background_color_index; int param[10]; int sixel_palet[SIXEL_PALETTE_MAX]; unsigned char *imbuf, *dmbuf; int imsx, imsy; int dmsx, dmsy; int y; posision_x = posision_y = 0; max_x = max_y = 0; attributed_pan = 2; attributed_pad = 1; attributed_ph = attributed_pv = 0; repeat_count = 1; color_index = 0; background_color_index = 0; imsx = 2048; imsy = 2048; imbuf = (unsigned char *) AcquireQuantumMemory(imsx * imsy,1); if (imbuf == NULL) { return(MagickFalse); } for (n = 0; n < 16; n++) { sixel_palet[n] = sixel_default_color_table[n]; } /* colors 16-231 are a 6x6x6 color cube */ for (r = 0; r < 6; r++) { for (g = 0; g < 6; g++) { for (b = 0; b < 6; b++) { sixel_palet[n++] = SIXEL_RGB(r * 51, g * 51, b * 51); } } } /* colors 232-255 are a grayscale ramp, intentionally leaving out */ for (i = 0; i < 24; i++) { sixel_palet[n++] = SIXEL_RGB(i * 11, i * 11, i * 11); } for (; n < SIXEL_PALETTE_MAX; n++) { sixel_palet[n] = SIXEL_RGB(255, 255, 255); } (void) ResetMagickMemory(imbuf, background_color_index, imsx * imsy); while (*p != '\0') { if ((p[0] == '\033' && p[1] == 'P') || *p == 0x90) { if (*p == '\033') { p++; } p = get_params(++p, param, &n); if (*p == 'q') { p++; if (n > 0) { /* Pn1 */ switch(param[0]) { case 0: case 1: attributed_pad = 2; break; case 2: attributed_pad = 5; break; case 3: attributed_pad = 4; break; case 4: attributed_pad = 4; break; case 5: attributed_pad = 3; break; case 6: attributed_pad = 3; break; case 7: attributed_pad = 2; break; case 8: attributed_pad = 2; break; case 9: attributed_pad = 1; break; } } if (n > 2) { /* Pn3 */ if (param[2] == 0) { param[2] = 10; } attributed_pan = attributed_pan * param[2] / 10; attributed_pad = attributed_pad * param[2] / 10; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; } } } else if ((p[0] == '\033' && p[1] == '\\') || *p == 0x9C) { break; } else if (*p == '"') { /* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */ p = get_params(++p, param, &n); if (n > 0) attributed_pad = param[0]; if (n > 1) attributed_pan = param[1]; if (n > 2 && param[2] > 0) attributed_ph = param[2]; if (n > 3 && param[3] > 0) attributed_pv = param[3]; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; if (imsx < attributed_ph || imsy < attributed_pv) { dmsx = imsx > attributed_ph ? imsx : attributed_ph; dmsy = imsy > attributed_pv ? imsy : attributed_pv; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) ResetMagickMemory(dmbuf, background_color_index, dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } } else if (*p == '!') { /* DECGRI Graphics Repeat Introducer ! Pn Ch */ p = get_params(++p, param, &n); if (n > 0) { repeat_count = param[0]; } } else if (*p == '#') { /* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */ p = get_params(++p, param, &n); if (n > 0) { if ((color_index = param[0]) < 0) { color_index = 0; } else if (color_index >= SIXEL_PALETTE_MAX) { color_index = SIXEL_PALETTE_MAX - 1; } } if (n > 4) { if (param[1] == 1) { /* HLS */ if (param[2] > 360) param[2] = 360; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = hls_to_rgb(param[2] * 100 / 360, param[3], param[4]); } else if (param[1] == 2) { /* RGB */ if (param[2] > 100) param[2] = 100; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = SIXEL_XRGB(param[2], param[3], param[4]); } } } else if (*p == '$') { /* DECGCR Graphics Carriage Return */ p++; posision_x = 0; repeat_count = 1; } else if (*p == '-') { /* DECGNL Graphics Next Line */ p++; posision_x = 0; posision_y += 6; repeat_count = 1; } else if (*p >= '?' && *p <= '\177') { if (imsx < (posision_x + repeat_count) || imsy < (posision_y + 6)) { int nx = imsx * 2; int ny = imsy * 2; while (nx < (posision_x + repeat_count) || ny < (posision_y + 6)) { nx *= 2; ny *= 2; } dmsx = nx; dmsy = ny; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) ResetMagickMemory(dmbuf, background_color_index, dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } if (color_index > max_color_index) { max_color_index = color_index; } if ((b = *(p++) - '?') == 0) { posision_x += repeat_count; } else { sixel_vertical_mask = 0x01; if (repeat_count <= 1) { for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { imbuf[imsx * (posision_y + i) + posision_x] = color_index; if (max_x < posision_x) { max_x = posision_x; } if (max_y < (posision_y + i)) { max_y = posision_y + i; } } sixel_vertical_mask <<= 1; } posision_x += 1; } else { /* repeat_count > 1 */ for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { c = sixel_vertical_mask << 1; for (n = 1; (i + n) < 6; n++) { if ((b & c) == 0) { break; } c <<= 1; } for (y = posision_y + i; y < posision_y + i + n; ++y) { (void) ResetMagickMemory(imbuf + imsx * y + posision_x, color_index, repeat_count); } if (max_x < (posision_x + repeat_count - 1)) { max_x = posision_x + repeat_count - 1; } if (max_y < (posision_y + i + n - 1)) { max_y = posision_y + i + n - 1; } i += (n - 1); sixel_vertical_mask <<= (n - 1); } sixel_vertical_mask <<= 1; } posision_x += repeat_count; } } repeat_count = 1; } else { p++; } } if (++max_x < attributed_ph) { max_x = attributed_ph; } if (++max_y < attributed_pv) { max_y = attributed_pv; } if (imsx > max_x || imsy > max_y) { dmsx = max_x; dmsy = max_y; if ((dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1)) == NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } for (y = 0; y < dmsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, dmsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } *pixels = imbuf; *pwidth = imsx; *pheight = imsy; *ncolors = max_color_index + 1; *palette = (unsigned char *) AcquireQuantumMemory(*ncolors,4); for (n = 0; n < (ssize_t) *ncolors; ++n) { (*palette)[n * 4 + 0] = sixel_palet[n] >> 16 & 0xff; (*palette)[n * 4 + 1] = sixel_palet[n] >> 8 & 0xff; (*palette)[n * 4 + 2] = sixel_palet[n] & 0xff; (*palette)[n * 4 + 3] = 0xff; } return(MagickTrue); } Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu) CWE ID: CWE-119 Target: 1 Example 2: Code: static void spl_multiple_iterator_get_all(spl_SplObjectStorage *intern, int get_type, zval *return_value TSRMLS_DC) /* {{{ */ { spl_SplObjectStorageElement *element; zval *it, *retval = NULL; int valid = 1, num_elements; num_elements = zend_hash_num_elements(&intern->storage); if (num_elements < 1) { RETURN_FALSE; } array_init_size(return_value, num_elements); zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos); while (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == SUCCESS && !EG(exception)) { it = element->obj; zend_call_method_with_0_params(&it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_valid, "valid", &retval); if (retval) { valid = Z_LVAL_P(retval); zval_ptr_dtor(&retval); } else { valid = 0; } if (valid) { if (SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT == get_type) { zend_call_method_with_0_params(&it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_current, "current", &retval); } else { zend_call_method_with_0_params(&it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_key, "key", &retval); } if (!retval) { zend_throw_exception(spl_ce_RuntimeException, "Failed to call sub iterator method", 0 TSRMLS_CC); return; } } else if (intern->flags & MIT_NEED_ALL) { if (SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT == get_type) { zend_throw_exception(spl_ce_RuntimeException, "Called current() with non valid sub iterator", 0 TSRMLS_CC); } else { zend_throw_exception(spl_ce_RuntimeException, "Called key() with non valid sub iterator", 0 TSRMLS_CC); } return; } else { ALLOC_INIT_ZVAL(retval); } if (intern->flags & MIT_KEYS_ASSOC) { switch (Z_TYPE_P(element->inf)) { case IS_LONG: add_index_zval(return_value, Z_LVAL_P(element->inf), retval); break; case IS_STRING: add_assoc_zval_ex(return_value, Z_STRVAL_P(element->inf), Z_STRLEN_P(element->inf)+1U, retval); break; default: zval_ptr_dtor(&retval); zend_throw_exception(spl_ce_InvalidArgumentException, "Sub-Iterator is associated with NULL", 0 TSRMLS_CC); return; } } else { add_next_index_zval(return_value, retval); } zend_hash_move_forward_ex(&intern->storage, &intern->pos); } } /* }}} */ Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ComponentUpdaterPolicyTest::FinishDefaultPolicy_GroupPolicyNotSupported() { VerifyExpectations(!kUpdateDisabled); cur_test_case_ = std::make_pair( &ComponentUpdaterPolicyTest::EnabledPolicy_GroupPolicySupported, &ComponentUpdaterPolicyTest::FinishEnabledPolicy_GroupPolicySupported); CallAsync(cur_test_case_.first); } Commit Message: Enforce the WebUsbAllowDevicesForUrls policy This change modifies UsbChooserContext to use the UsbAllowDevicesForUrls class to consider devices allowed by the WebUsbAllowDevicesForUrls policy. The WebUsbAllowDevicesForUrls policy overrides the other WebUSB policies. Unit tests are also added to ensure that the policy is being enforced correctly. The design document for this feature is found at: https://docs.google.com/document/d/1MPvsrWiVD_jAC8ELyk8njFpy6j1thfVU5aWT3TCWE8w Bug: 854329 Change-Id: I5f82e662ca9dc544da5918eae766b5535a31296b Reviewed-on: https://chromium-review.googlesource.com/c/1259289 Commit-Queue: Ovidio Henriquez <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Julian Pastarmov <[email protected]> Cr-Commit-Position: refs/heads/master@{#597926} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(ctcptype) emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix); } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: select_opt_map(OptMap* now, OptMap* alt) { static int z = 1<<15; /* 32768: something big value */ int vn, va; if (alt->value == 0) return ; if (now->value == 0) { copy_opt_map(now, alt); return ; } vn = z / now->value; va = z / alt->value; if (comp_distance_value(&now->mmd, &alt->mmd, vn, va) > 0) copy_opt_map(now, alt); } Commit Message: Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode. CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void finalizeStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().finalizeStream(blobRegistryContext->url); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool AppCacheBackendImpl::SelectCacheForWorker( int host_id, int parent_process_id, int parent_host_id) { AppCacheHost* host = GetHost(host_id); if (!host || host->was_select_cache_called()) return false; host->SelectCacheForWorker(parent_process_id, parent_host_id); return true; } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID: Target: 1 Example 2: Code: LayerTreeHostTestCrispUpAfterPinchEnds() : playback_allowed_event_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::SIGNALED) {} Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: send_parameters(struct iperf_test *test) { int r = 0; cJSON *j; j = cJSON_CreateObject(); if (j == NULL) { i_errno = IESENDPARAMS; r = -1; } else { if (test->protocol->id == Ptcp) cJSON_AddTrueToObject(j, "tcp"); else if (test->protocol->id == Pudp) cJSON_AddTrueToObject(j, "udp"); cJSON_AddIntToObject(j, "omit", test->omit); if (test->server_affinity != -1) cJSON_AddIntToObject(j, "server_affinity", test->server_affinity); if (test->duration) cJSON_AddIntToObject(j, "time", test->duration); if (test->settings->bytes) cJSON_AddIntToObject(j, "num", test->settings->bytes); if (test->settings->blocks) cJSON_AddIntToObject(j, "blockcount", test->settings->blocks); if (test->settings->mss) cJSON_AddIntToObject(j, "MSS", test->settings->mss); if (test->no_delay) cJSON_AddTrueToObject(j, "nodelay"); cJSON_AddIntToObject(j, "parallel", test->num_streams); if (test->reverse) cJSON_AddTrueToObject(j, "reverse"); if (test->settings->socket_bufsize) cJSON_AddIntToObject(j, "window", test->settings->socket_bufsize); if (test->settings->blksize) cJSON_AddIntToObject(j, "len", test->settings->blksize); if (test->settings->rate) cJSON_AddIntToObject(j, "bandwidth", test->settings->rate); if (test->settings->burst) cJSON_AddIntToObject(j, "burst", test->settings->burst); if (test->settings->tos) cJSON_AddIntToObject(j, "TOS", test->settings->tos); if (test->settings->flowlabel) cJSON_AddIntToObject(j, "flowlabel", test->settings->flowlabel); if (test->title) cJSON_AddStringToObject(j, "title", test->title); if (test->congestion) cJSON_AddStringToObject(j, "congestion", test->congestion); if (test->get_server_output) cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test)); if (test->debug) { printf("send_parameters:\n%s\n", cJSON_Print(j)); } if (JSON_write(test->ctrl_sck, j) < 0) { i_errno = IESENDPARAMS; r = -1; } cJSON_Delete(j); } return r; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SMBC_server_internal(TALLOC_CTX *ctx, SMBCCTX *context, bool connect_if_not_found, const char *server, uint16_t port, const char *share, char **pp_workgroup, char **pp_username, char **pp_password, bool *in_cache) { SMBCSRV *srv=NULL; char *workgroup = NULL; struct cli_state *c = NULL; const char *server_n = server; int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0); uint32_t fs_attrs = 0; const char *username_used; NTSTATUS status; char *newserver, *newshare; int flags = 0; struct smbXcli_tcon *tcon = NULL; ZERO_STRUCT(c); *in_cache = false; if (server[0] == 0) { errno = EPERM; return NULL; } /* Look for a cached connection */ srv = SMBC_find_server(ctx, context, server, share, pp_workgroup, pp_username, pp_password); /* * If we found a connection and we're only allowed one share per * server... */ if (srv && share != NULL && *share != '\0' && smbc_getOptionOneSharePerServer(context)) { /* * ... then if there's no current connection to the share, * connect to it. SMBC_find_server(), or rather the function * pointed to by context->get_cached_srv_fn which * was called by SMBC_find_server(), will have issued a tree * disconnect if the requested share is not the same as the * one that was already connected. */ /* * Use srv->cli->desthost and srv->cli->share instead of * server and share below to connect to the actual share, * i.e., a normal share or a referred share from * 'msdfs proxy' share. */ if (!cli_state_has_tcon(srv->cli)) { /* Ensure we have accurate auth info */ SMBC_call_auth_fn(ctx, context, smbXcli_conn_remote_name(srv->cli->conn), srv->cli->share, pp_workgroup, pp_username, pp_password); if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; cli_shutdown(srv->cli); srv->cli = NULL; smbc_getFunctionRemoveCachedServer(context)(context, srv); return NULL; } /* * We don't need to renegotiate encryption * here as the encryption context is not per * tid. */ status = cli_tree_connect(srv->cli, srv->cli->share, "?????", *pp_password, strlen(*pp_password)+1); if (!NT_STATUS_IS_OK(status)) { errno = map_errno_from_nt_status(status); cli_shutdown(srv->cli); srv->cli = NULL; smbc_getFunctionRemoveCachedServer(context)(context, srv); srv = NULL; } /* Determine if this share supports case sensitivity */ if (is_ipc) { DEBUG(4, ("IPC$ so ignore case sensitivity\n")); status = NT_STATUS_OK; } else { status = cli_get_fs_attr_info(c, &fs_attrs); } if (!NT_STATUS_IS_OK(status)) { DEBUG(4, ("Could not retrieve " "case sensitivity flag: %s.\n", nt_errstr(status))); /* * We can't determine the case sensitivity of * the share. We have no choice but to use the * user-specified case sensitivity setting. */ if (smbc_getOptionCaseSensitive(context)) { cli_set_case_sensitive(c, True); } else { cli_set_case_sensitive(c, False); } } else if (!is_ipc) { DEBUG(4, ("Case sensitive: %s\n", (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? "True" : "False"))); cli_set_case_sensitive( c, (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? True : False)); } /* * Regenerate the dev value since it's based on both * server and share */ if (srv) { const char *remote_name = smbXcli_conn_remote_name(srv->cli->conn); srv->dev = (dev_t)(str_checksum(remote_name) ^ str_checksum(srv->cli->share)); } } } /* If we have a connection... */ if (srv) { /* ... then we're done here. Give 'em what they came for. */ *in_cache = true; goto done; } /* If we're not asked to connect when a connection doesn't exist... */ if (! connect_if_not_found) { /* ... then we're done here. */ return NULL; } if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; return NULL; } DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server)); DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server)); status = NT_STATUS_UNSUCCESSFUL; if (smbc_getOptionUseKerberos(context)) { flags |= CLI_FULL_CONNECTION_USE_KERBEROS; } if (smbc_getOptionFallbackAfterKerberos(context)) { flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS; } if (smbc_getOptionUseCCache(context)) { flags |= CLI_FULL_CONNECTION_USE_CCACHE; } if (smbc_getOptionUseNTHash(context)) { flags |= CLI_FULL_CONNECTION_USE_NT_HASH; flags |= CLI_FULL_CONNECTION_USE_NT_HASH; } if (port == 0) { if (share == NULL || *share == '\0' || is_ipc) { /* } */ status = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20, smbc_getNetbiosName(context), SMB_SIGNING_DEFAULT, flags, &c); } } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static void mcryptd_hash_init(struct crypto_async_request *req_async, int err) { struct mcryptd_hash_ctx *ctx = crypto_tfm_ctx(req_async->tfm); struct crypto_ahash *child = ctx->child; struct ahash_request *req = ahash_request_cast(req_async); struct mcryptd_hash_request_ctx *rctx = ahash_request_ctx(req); struct ahash_request *desc = &rctx->areq; if (unlikely(err == -EINPROGRESS)) goto out; ahash_request_set_tfm(desc, child); ahash_request_set_callback(desc, CRYPTO_TFM_REQ_MAY_SLEEP, rctx->complete, req_async); rctx->out = req->result; err = crypto_ahash_init(desc); out: local_bh_disable(); rctx->complete(&req->base, err); local_bh_enable(); } Commit Message: crypto: mcryptd - Check mcryptd algorithm compatibility Algorithms not compatible with mcryptd could be spawned by mcryptd with a direct crypto_alloc_tfm invocation using a "mcryptd(alg)" name construct. This causes mcryptd to crash the kernel if an arbitrary "alg" is incompatible and not intended to be used with mcryptd. It is an issue if AF_ALG tries to spawn mcryptd(alg) to expose it externally. But such algorithms must be used internally and not be exposed. We added a check to enforce that only internal algorithms are allowed with mcryptd at the time mcryptd is spawning an algorithm. Link: http://marc.info/?l=linux-crypto-vger&m=148063683310477&w=2 Cc: [email protected] Reported-by: Mikulas Patocka <[email protected]> Signed-off-by: Tim Chen <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: char* _multi_string_alloc_and_copy( LPCWSTR in ) { char *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { len ++; } chr = malloc( len + 2 ); len = 0; while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { chr[ len ] = 0xFF & in[ len ]; len ++; } chr[ len ++ ] = '\0'; chr[ len ++ ] = '\0'; return chr; } Commit Message: New Pre Source CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Add(int original_content_length, int received_content_length) { AddInt64ToListPref( kNumDaysInHistory - 1, original_content_length, original_update_.Get()); AddInt64ToListPref( kNumDaysInHistory - 1, received_content_length, received_update_.Get()); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 1 Example 2: Code: hstore_send(PG_FUNCTION_ARGS) { HStore *in = PG_GETARG_HS(0); int i; int count = HS_COUNT(in); char *base = STRPTR(in); HEntry *entries = ARRPTR(in); StringInfoData buf; pq_begintypsend(&buf); pq_sendint(&buf, count, 4); for (i = 0; i < count; i++) { int32 keylen = HS_KEYLEN(entries, i); pq_sendint(&buf, keylen, 4); pq_sendtext(&buf, HS_KEY(entries, base, i), keylen); if (HS_VALISNULL(entries, i)) { pq_sendint(&buf, -1, 4); } else { int32 vallen = HS_VALLEN(entries, i); pq_sendint(&buf, vallen, 4); pq_sendtext(&buf, HS_VAL(entries, base, i), vallen); } } PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype, const ASN1_ITEM *it) { ASN1_BOOLEAN *tbool = NULL; ASN1_STRING *strtmp; ASN1_OBJECT *otmp; int utype; const unsigned char *cont; unsigned char c; int len; const ASN1_PRIMITIVE_FUNCS *pf; pf = it->funcs; if (pf && pf->prim_i2c) return pf->prim_i2c(pval, cout, putype, it); /* Should type be omitted? */ if ((it->itype != ASN1_ITYPE_PRIMITIVE) || (it->utype != V_ASN1_BOOLEAN)) { if (!*pval) return -1; } if (it->itype == ASN1_ITYPE_MSTRING) { /* If MSTRING type set the underlying type */ strtmp = (ASN1_STRING *)*pval; utype = strtmp->type; *putype = utype; } else if (it->utype == V_ASN1_ANY) { /* If ANY set type and pointer to value */ ASN1_TYPE *typ; typ = (ASN1_TYPE *)*pval; utype = typ->type; *putype = utype; pval = &typ->value.asn1_value; } else utype = *putype; switch (utype) { case V_ASN1_OBJECT: otmp = (ASN1_OBJECT *)*pval; cont = otmp->data; len = otmp->length; break; case V_ASN1_NULL: cont = NULL; len = 0; break; case V_ASN1_BOOLEAN: tbool = (ASN1_BOOLEAN *)pval; if (*tbool == -1) return -1; if (it->utype != V_ASN1_ANY) { /* * Default handling if value == size field then omit */ if (*tbool && (it->size > 0)) return -1; if (!*tbool && !it->size) return -1; } c = (unsigned char)*tbool; cont = &c; len = 1; break; case V_ASN1_BIT_STRING: return i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval, cout ? &cout : NULL); break; case V_ASN1_INTEGER: case V_ASN1_NEG_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_NEG_ENUMERATED: /* * These are all have the same content format as ASN1_INTEGER */ * These are all have the same content format as ASN1_INTEGER */ return i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL); break; case V_ASN1_OCTET_STRING: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: default: /* All based on ASN1_STRING and handled the same */ strtmp = (ASN1_STRING *)*pval; /* Special handling for NDEF */ if ((it->size == ASN1_TFLG_NDEF) && (strtmp->flags & ASN1_STRING_FLAG_NDEF)) { if (cout) { strtmp->data = cout; strtmp->length = 0; } /* Special return code */ return -2; } cont = strtmp->data; len = strtmp->length; break; } if (cout && len) memcpy(cout, cont, len); return len; } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_get_asm_flags (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ return (png_ptr? 0L: 0L); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: struct rds_connection *rds_conn_create(struct net *net, __be32 laddr, __be32 faddr, struct rds_transport *trans, gfp_t gfp) { return __rds_conn_create(net, laddr, faddr, trans, gfp, 0); } Commit Message: RDS: fix race condition when sending a message on unbound socket Sasha's found a NULL pointer dereference in the RDS connection code when sending a message to an apparently unbound socket. The problem is caused by the code checking if the socket is bound in rds_sendmsg(), which checks the rs_bound_addr field without taking a lock on the socket. This opens a race where rs_bound_addr is temporarily set but where the transport is not in rds_bind(), leading to a NULL pointer dereference when trying to dereference 'trans' in __rds_conn_create(). Vegard wrote a reproducer for this issue, so kindly ask him to share if you're interested. I cannot reproduce the NULL pointer dereference using Vegard's reproducer with this patch, whereas I could without. Complete earlier incomplete fix to CVE-2015-6937: 74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection") Cc: David S. Miller <[email protected]> Cc: [email protected] Reviewed-by: Vegard Nossum <[email protected]> Reviewed-by: Sasha Levin <[email protected]> Acked-by: Santosh Shilimkar <[email protected]> Signed-off-by: Quentin Casasnovas <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Wait() { base::RunLoop run_loop; DCHECK(!run_loop_); run_loop_ = &run_loop; CheckForWaitingLoop(); run_loop.Run(); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "aead"); snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv ?: "<built-in>"); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix info leaks in report API Three errors resulting in kernel memory disclosure: 1/ The structures used for the netlink based crypto algorithm report API are located on the stack. As snprintf() does not fill the remainder of the buffer with null bytes, those stack bytes will be disclosed to users of the API. Switch to strncpy() to fix this. 2/ crypto_report_one() does not initialize all field of struct crypto_user_alg. Fix this to fix the heap info leak. 3/ For the module name we should copy only as many bytes as module_name() returns -- not as much as the destination buffer could hold. But the current code does not and therefore copies random data from behind the end of the module name, as the module name is always shorter than CRYPTO_MAX_ALG_NAME. Also switch to use strncpy() to copy the algorithm's name and driver_name. They are strings, after all. Signed-off-by: Mathias Krause <[email protected]> Cc: Steffen Klassert <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-310 Target: 1 Example 2: Code: static int in_set_parameters(struct audio_stream *stream, const char *kvpairs) { struct stream_in *in = (struct stream_in *)stream; struct audio_device *adev = in->dev; struct str_parms *parms; char *str; char value[32]; int ret, val = 0; struct audio_usecase *uc_info; bool do_standby = false; struct listnode *node; struct pcm_device *pcm_device; struct pcm_device_profile *pcm_profile; ALOGV("%s: enter: kvpairs=%s", __func__, kvpairs); parms = str_parms_create_str(kvpairs); ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value)); pthread_mutex_lock(&adev->lock_inputs); lock_input_stream(in); pthread_mutex_lock(&adev->lock); if (ret >= 0) { val = atoi(value); /* no audio source uses val == 0 */ if (((int)in->source != val) && (val != 0)) { in->source = val; } } ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value)); if (ret >= 0) { val = atoi(value); if (((int)in->devices != val) && (val != 0)) { in->devices = val; /* If recording is in progress, change the tx device to new device */ if (!in->standby) { uc_info = get_usecase_from_id(adev, in->usecase); if (uc_info == NULL) { ALOGE("%s: Could not find the usecase (%d) in the list", __func__, in->usecase); } else { if (list_empty(&in->pcm_dev_list)) ALOGE("%s: pcm device list empty", __func__); else { pcm_device = node_to_item(list_head(&in->pcm_dev_list), struct pcm_device, stream_list_node); if ((pcm_device->pcm_profile->devices & val & ~AUDIO_DEVICE_BIT_IN) == 0) { do_standby = true; } } } if (do_standby) { ret = do_in_standby_l(in); } else ret = select_devices(adev, in->usecase); } } } pthread_mutex_unlock(&adev->lock); pthread_mutex_unlock(&in->lock); pthread_mutex_unlock(&adev->lock_inputs); str_parms_destroy(parms); if (ret > 0) ret = 0; return ret; } Commit Message: Fix audio record pre-processing proc_buf_out consistently initialized. intermediate scratch buffers consistently initialized. prevent read failure from overwriting memory. Test: POC, CTS, camera record Bug: 62873231 Change-Id: Ie26e12a419a5819c1c5c3a0bcf1876d6d7aca686 (cherry picked from commit 6d7b330c27efba944817e647955da48e54fd74eb) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int php_openssl_write_rand_file(const char * file, int egdsocket, int seeded) /* {{{ */ { char buffer[MAXPATHLEN]; if (egdsocket || !seeded) { /* if we did not manage to read the seed file, we should not write * a low-entropy seed file back */ return FAILURE; } if (file == NULL) { file = RAND_file_name(buffer, sizeof(buffer)); } PHP_OPENSSL_RAND_ADD_TIME(); if (file == NULL || !RAND_write_file(file)) { php_error_docref(NULL, E_WARNING, "unable to write random state"); return FAILURE; } return SUCCESS; } /* }}} */ Commit Message: CWE ID: CWE-754 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ovl_setattr(struct dentry *dentry, struct iattr *attr) { int err; struct dentry *upperdentry; err = ovl_want_write(dentry); if (err) goto out; upperdentry = ovl_dentry_upper(dentry); if (upperdentry) { mutex_lock(&upperdentry->d_inode->i_mutex); err = notify_change(upperdentry, attr, NULL); mutex_unlock(&upperdentry->d_inode->i_mutex); } else { err = ovl_copy_up_last(dentry, attr, false); } ovl_drop_write(dentry); out: return err; } Commit Message: ovl: fix permission checking for setattr [Al Viro] The bug is in being too enthusiastic about optimizing ->setattr() away - instead of "copy verbatim with metadata" + "chmod/chown/utimes" (with the former being always safe and the latter failing in case of insufficient permissions) it tries to combine these two. Note that copyup itself will have to do ->setattr() anyway; _that_ is where the elevated capabilities are right. Having these two ->setattr() (one to set verbatim copy of metadata, another to do what overlayfs ->setattr() had been asked to do in the first place) combined is where it breaks. Signed-off-by: Miklos Szeredi <[email protected]> Cc: <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void SetEnableAutoImeShutdown(bool enable) { enable_auto_ime_shutdown_ = enable; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ReportPreconnectAccuracy( const PreconnectStats& stats, const std::map<GURL, OriginRequestSummary>& requests) { if (stats.requests_stats.empty()) return; int preresolve_hits_count = 0; int preresolve_misses_count = 0; int preconnect_hits_count = 0; int preconnect_misses_count = 0; for (const auto& request_stats : stats.requests_stats) { bool hit = requests.find(request_stats.origin) != requests.end(); bool preconnect = request_stats.was_preconnected; preresolve_hits_count += hit; preresolve_misses_count += !hit; preconnect_hits_count += preconnect && hit; preconnect_misses_count += preconnect && !hit; } int total_preresolves = preresolve_hits_count + preresolve_misses_count; int total_preconnects = preconnect_hits_count + preconnect_misses_count; DCHECK_EQ(static_cast<int>(stats.requests_stats.size()), preresolve_hits_count + preresolve_misses_count); DCHECK_GT(total_preresolves, 0); size_t preresolve_hits_percentage = (100 * preresolve_hits_count) / total_preresolves; if (total_preconnects > 0) { size_t preconnect_hits_percentage = (100 * preconnect_hits_count) / total_preconnects; UMA_HISTOGRAM_PERCENTAGE( internal::kLoadingPredictorPreconnectHitsPercentage, preconnect_hits_percentage); } UMA_HISTOGRAM_PERCENTAGE(internal::kLoadingPredictorPreresolveHitsPercentage, preresolve_hits_percentage); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreresolveCount, total_preresolves); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreconnectCount, total_preconnects); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintViewManager::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { if (render_frame_host == print_preview_rfh_) print_preview_state_ = NOT_PREVIEWING; PrintViewManagerBase::RenderFrameDeleted(render_frame_host); } Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated(). BUG=694382,698622 Review-Url: https://codereview.chromium.org/2742853003 Cr-Commit-Position: refs/heads/master@{#457363} CWE ID: CWE-125 Target: 1 Example 2: Code: on_ok_clicked(void *user_data, Evas_Object *obj, void *event_info) { Eina_Bool *confirmed = (Eina_Bool *)user_data; *confirmed = EINA_TRUE; ecore_main_loop_quit(); } Commit Message: [EFL][WK2] Add --window-size command line option to EFL MiniBrowser https://bugs.webkit.org/show_bug.cgi?id=100942 Patch by Mikhail Pozdnyakov <[email protected]> on 2012-11-05 Reviewed by Kenneth Rohde Christiansen. Added window-size (-s) command line option to EFL MiniBrowser. * MiniBrowser/efl/main.c: (window_create): (parse_window_size): (elm_main): git-svn-id: svn://svn.chromium.org/blink/trunk@133450 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static __u32 tcp_v4_init_sequence(const struct sk_buff *skb) { return secure_tcp_sequence_number(ip_hdr(skb)->daddr, ip_hdr(skb)->saddr, tcp_hdr(skb)->dest, tcp_hdr(skb)->source); } Commit Message: tcp: take care of truncations done by sk_filter() With syzkaller help, Marco Grassi found a bug in TCP stack, crashing in tcp_collapse() Root cause is that sk_filter() can truncate the incoming skb, but TCP stack was not really expecting this to happen. It probably was expecting a simple DROP or ACCEPT behavior. We first need to make sure no part of TCP header could be removed. Then we need to adjust TCP_SKB_CB(skb)->end_seq Many thanks to syzkaller team and Marco for giving us a reproducer. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Marco Grassi <[email protected]> Reported-by: Vladis Dronov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void handle_ld_nf(u32 insn, struct pt_regs *regs) { int rd = ((insn >> 25) & 0x1f); int from_kernel = (regs->tstate & TSTATE_PRIV) != 0; unsigned long *reg; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); maybe_flush_windows(0, 0, rd, from_kernel); reg = fetch_reg_addr(rd, regs); if (from_kernel || rd < 16) { reg[0] = 0; if ((insn & 0x780000) == 0x180000) reg[1] = 0; } else if (test_thread_flag(TIF_32BIT)) { put_user(0, (int __user *) reg); if ((insn & 0x780000) == 0x180000) put_user(0, ((int __user *) reg) + 1); } else { put_user(0, (unsigned long __user *) reg); if ((insn & 0x780000) == 0x180000) put_user(0, (unsigned long __user *) reg + 1); } advance(regs); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static void ftrace_hash_clear(struct ftrace_hash *hash) { struct hlist_head *hhd; struct hlist_node *tn; struct ftrace_func_entry *entry; int size = 1 << hash->size_bits; int i; if (!hash->count) return; for (i = 0; i < size; i++) { hhd = &hash->buckets[i]; hlist_for_each_entry_safe(entry, tn, hhd, hlist) free_hash_entry(hash, entry); } FTRACE_WARN_ON(hash->count); } Commit Message: tracing: Fix possible NULL pointer dereferences Currently set_ftrace_pid and set_graph_function files use seq_lseek for their fops. However seq_open() is called only for FMODE_READ in the fops->open() so that if an user tries to seek one of those file when she open it for writing, it sees NULL seq_file and then panic. It can be easily reproduced with following command: $ cd /sys/kernel/debug/tracing $ echo 1234 | sudo tee -a set_ftrace_pid In this example, GNU coreutils' tee opens the file with fopen(, "a") and then the fopen() internally calls lseek(). Link: http://lkml.kernel.org/r/[email protected] Cc: Frederic Weisbecker <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Namhyung Kim <[email protected]> Cc: [email protected] Signed-off-by: Namhyung Kim <[email protected]> Signed-off-by: Steven Rostedt <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: QStringList NotificationsEngine::GetCapabilities() { return QStringList() << QStringLiteral("body") << QStringLiteral("body-hyperlinks") << QStringLiteral("body-markup") << QStringLiteral("icon-static") << QStringLiteral("actions") ; } Commit Message: CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int read_header(FFV1Context *f) { uint8_t state[CONTEXT_SIZE]; int i, j, context_count = -1; //-1 to avoid warning RangeCoder *const c = &f->slice_context[0]->c; memset(state, 128, sizeof(state)); if (f->version < 2) { int chroma_planes, chroma_h_shift, chroma_v_shift, transparency; unsigned v= get_symbol(c, state, 0); if (v >= 2) { av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v); return AVERROR_INVALIDDATA; } f->version = v; f->ac = f->avctx->coder_type = get_symbol(c, state, 0); if (f->ac > 1) { for (i = 1; i < 256; i++) f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i]; } f->colorspace = get_symbol(c, state, 0); //YUV cs type if (f->version > 0) f->avctx->bits_per_raw_sample = get_symbol(c, state, 0); chroma_planes = get_rac(c, state); chroma_h_shift = get_symbol(c, state, 0); chroma_v_shift = get_symbol(c, state, 0); transparency = get_rac(c, state); if (f->plane_count) { if ( chroma_planes != f->chroma_planes || chroma_h_shift!= f->chroma_h_shift || chroma_v_shift!= f->chroma_v_shift || transparency != f->transparency) { av_log(f->avctx, AV_LOG_ERROR, "Invalid change of global parameters\n"); return AVERROR_INVALIDDATA; } } f->chroma_planes = chroma_planes; f->chroma_h_shift = chroma_h_shift; f->chroma_v_shift = chroma_v_shift; f->transparency = transparency; f->plane_count = 2 + f->transparency; } if (f->colorspace == 0) { if (!f->transparency && !f->chroma_planes) { if (f->avctx->bits_per_raw_sample <= 8) f->avctx->pix_fmt = AV_PIX_FMT_GRAY8; else f->avctx->pix_fmt = AV_PIX_FMT_GRAY16; } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) { switch(16 * f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break; case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break; case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break; case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) { switch(16*f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } else if (f->avctx->bits_per_raw_sample == 9) { f->packed_at_lsb = 1; switch(16 * f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } else if (f->avctx->bits_per_raw_sample == 10) { f->packed_at_lsb = 1; switch(16 * f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } else { switch(16 * f->chroma_h_shift + f->chroma_v_shift) { case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break; case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break; case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break; default: av_log(f->avctx, AV_LOG_ERROR, "format not supported\n"); return AVERROR(ENOSYS); } } } else if (f->colorspace == 1) { if (f->chroma_h_shift || f->chroma_v_shift) { av_log(f->avctx, AV_LOG_ERROR, "chroma subsampling not supported in this colorspace\n"); return AVERROR(ENOSYS); } if ( f->avctx->bits_per_raw_sample == 9) f->avctx->pix_fmt = AV_PIX_FMT_GBRP9; else if (f->avctx->bits_per_raw_sample == 10) f->avctx->pix_fmt = AV_PIX_FMT_GBRP10; else if (f->avctx->bits_per_raw_sample == 12) f->avctx->pix_fmt = AV_PIX_FMT_GBRP12; else if (f->avctx->bits_per_raw_sample == 14) f->avctx->pix_fmt = AV_PIX_FMT_GBRP14; else if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32; else f->avctx->pix_fmt = AV_PIX_FMT_0RGB32; } else { av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n"); return AVERROR(ENOSYS); } av_dlog(f->avctx, "%d %d %d\n", f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt); if (f->version < 2) { context_count = read_quant_tables(c, f->quant_table); if (context_count < 0) { av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n"); return AVERROR_INVALIDDATA; } } else if (f->version < 3) { f->slice_count = get_symbol(c, state, 0); } else { const uint8_t *p = c->bytestream_end; for (f->slice_count = 0; f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start; f->slice_count++) { int trailer = 3 + 5*!!f->ec; int size = AV_RB24(p-trailer); if (size + trailer > p - c->bytestream_start) break; p -= size + trailer; } } if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) { av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count); return AVERROR_INVALIDDATA; } for (j = 0; j < f->slice_count; j++) { FFV1Context *fs = f->slice_context[j]; fs->ac = f->ac; fs->packed_at_lsb = f->packed_at_lsb; fs->slice_damaged = 0; if (f->version == 2) { fs->slice_x = get_symbol(c, state, 0) * f->width ; fs->slice_y = get_symbol(c, state, 0) * f->height; fs->slice_width = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x; fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y; fs->slice_x /= f->num_h_slices; fs->slice_y /= f->num_v_slices; fs->slice_width = fs->slice_width / f->num_h_slices - fs->slice_x; fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y; if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height) return AVERROR_INVALIDDATA; if ( (unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height) return AVERROR_INVALIDDATA; } for (i = 0; i < f->plane_count; i++) { PlaneContext *const p = &fs->plane[i]; if (f->version == 2) { int idx = get_symbol(c, state, 0); if (idx > (unsigned)f->quant_table_count) { av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n"); return AVERROR_INVALIDDATA; } p->quant_table_index = idx; memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table)); context_count = f->context_count[idx]; } else { memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table)); } if (f->version <= 2) { av_assert0(context_count >= 0); if (p->context_count < context_count) { av_freep(&p->state); av_freep(&p->vlc_state); } p->context_count = context_count; } } } return 0; } Commit Message: ffv1dec: Check bits_per_raw_sample and colorspace for equality in ver 0/1 headers Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static void xhci_runtime_write(void *ptr, hwaddr reg, uint64_t val, unsigned size) { XHCIState *xhci = ptr; int v = (reg - 0x20) / 0x20; XHCIInterrupter *intr = &xhci->intr[v]; trace_usb_xhci_runtime_write(reg, val); if (reg < 0x20) { trace_usb_xhci_unimplemented("runtime write", reg); return; } switch (reg & 0x1f) { case 0x00: /* IMAN */ if (val & IMAN_IP) { intr->iman &= ~IMAN_IP; } intr->iman &= ~IMAN_IE; intr->iman |= val & IMAN_IE; if (v == 0) { xhci_intx_update(xhci); } xhci_msix_update(xhci, v); break; case 0x04: /* IMOD */ intr->imod = val; break; case 0x08: /* ERSTSZ */ intr->erstsz = val & 0xffff; break; case 0x10: /* ERSTBA low */ /* XXX NEC driver bug: it doesn't align this to 64 bytes intr->erstba_low = val & 0xffffffc0; */ intr->erstba_low = val & 0xfffffff0; break; case 0x14: /* ERSTBA high */ intr->erstba_high = val; xhci_er_reset(xhci, v); break; case 0x18: /* ERDP low */ if (val & ERDP_EHB) { intr->erdp_low &= ~ERDP_EHB; } intr->erdp_low = (val & ~ERDP_EHB) | (intr->erdp_low & ERDP_EHB); break; case 0x1c: /* ERDP high */ intr->erdp_high = val; xhci_events_update(xhci, v); break; default: trace_usb_xhci_unimplemented("oper write", reg); } } Commit Message: CWE ID: CWE-835 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static ssize_t hfi1_file_write(struct file *fp, const char __user *data, size_t count, loff_t *offset) { const struct hfi1_cmd __user *ucmd; struct hfi1_filedata *fd = fp->private_data; struct hfi1_ctxtdata *uctxt = fd->uctxt; struct hfi1_cmd cmd; struct hfi1_user_info uinfo; struct hfi1_tid_info tinfo; unsigned long addr; ssize_t consumed = 0, copy = 0, ret = 0; void *dest = NULL; __u64 user_val = 0; int uctxt_required = 1; int must_be_root = 0; if (count < sizeof(cmd)) { ret = -EINVAL; goto bail; } ucmd = (const struct hfi1_cmd __user *)data; if (copy_from_user(&cmd, ucmd, sizeof(cmd))) { ret = -EFAULT; goto bail; } consumed = sizeof(cmd); switch (cmd.type) { case HFI1_CMD_ASSIGN_CTXT: uctxt_required = 0; /* assigned user context not required */ copy = sizeof(uinfo); dest = &uinfo; break; case HFI1_CMD_SDMA_STATUS_UPD: case HFI1_CMD_CREDIT_UPD: copy = 0; break; case HFI1_CMD_TID_UPDATE: case HFI1_CMD_TID_FREE: case HFI1_CMD_TID_INVAL_READ: copy = sizeof(tinfo); dest = &tinfo; break; case HFI1_CMD_USER_INFO: case HFI1_CMD_RECV_CTRL: case HFI1_CMD_POLL_TYPE: case HFI1_CMD_ACK_EVENT: case HFI1_CMD_CTXT_INFO: case HFI1_CMD_SET_PKEY: case HFI1_CMD_CTXT_RESET: copy = 0; user_val = cmd.addr; break; case HFI1_CMD_EP_INFO: case HFI1_CMD_EP_ERASE_CHIP: case HFI1_CMD_EP_ERASE_RANGE: case HFI1_CMD_EP_READ_RANGE: case HFI1_CMD_EP_WRITE_RANGE: uctxt_required = 0; /* assigned user context not required */ must_be_root = 1; /* validate user */ copy = 0; break; default: ret = -EINVAL; goto bail; } /* If the command comes with user data, copy it. */ if (copy) { if (copy_from_user(dest, (void __user *)cmd.addr, copy)) { ret = -EFAULT; goto bail; } consumed += copy; } /* * Make sure there is a uctxt when needed. */ if (uctxt_required && !uctxt) { ret = -EINVAL; goto bail; } /* only root can do these operations */ if (must_be_root && !capable(CAP_SYS_ADMIN)) { ret = -EPERM; goto bail; } switch (cmd.type) { case HFI1_CMD_ASSIGN_CTXT: ret = assign_ctxt(fp, &uinfo); if (ret < 0) goto bail; ret = setup_ctxt(fp); if (ret) goto bail; ret = user_init(fp); break; case HFI1_CMD_CTXT_INFO: ret = get_ctxt_info(fp, (void __user *)(unsigned long) user_val, cmd.len); break; case HFI1_CMD_USER_INFO: ret = get_base_info(fp, (void __user *)(unsigned long) user_val, cmd.len); break; case HFI1_CMD_SDMA_STATUS_UPD: break; case HFI1_CMD_CREDIT_UPD: if (uctxt && uctxt->sc) sc_return_credits(uctxt->sc); break; case HFI1_CMD_TID_UPDATE: ret = hfi1_user_exp_rcv_setup(fp, &tinfo); if (!ret) { /* * Copy the number of tidlist entries we used * and the length of the buffer we registered. * These fields are adjacent in the structure so * we can copy them at the same time. */ addr = (unsigned long)cmd.addr + offsetof(struct hfi1_tid_info, tidcnt); if (copy_to_user((void __user *)addr, &tinfo.tidcnt, sizeof(tinfo.tidcnt) + sizeof(tinfo.length))) ret = -EFAULT; } break; case HFI1_CMD_TID_INVAL_READ: ret = hfi1_user_exp_rcv_invalid(fp, &tinfo); if (ret) break; addr = (unsigned long)cmd.addr + offsetof(struct hfi1_tid_info, tidcnt); if (copy_to_user((void __user *)addr, &tinfo.tidcnt, sizeof(tinfo.tidcnt))) ret = -EFAULT; break; case HFI1_CMD_TID_FREE: ret = hfi1_user_exp_rcv_clear(fp, &tinfo); if (ret) break; addr = (unsigned long)cmd.addr + offsetof(struct hfi1_tid_info, tidcnt); if (copy_to_user((void __user *)addr, &tinfo.tidcnt, sizeof(tinfo.tidcnt))) ret = -EFAULT; break; case HFI1_CMD_RECV_CTRL: ret = manage_rcvq(uctxt, fd->subctxt, (int)user_val); break; case HFI1_CMD_POLL_TYPE: uctxt->poll_type = (typeof(uctxt->poll_type))user_val; break; case HFI1_CMD_ACK_EVENT: ret = user_event_ack(uctxt, fd->subctxt, user_val); break; case HFI1_CMD_SET_PKEY: if (HFI1_CAP_IS_USET(PKEY_CHECK)) ret = set_ctxt_pkey(uctxt, fd->subctxt, user_val); else ret = -EPERM; break; case HFI1_CMD_CTXT_RESET: { struct send_context *sc; struct hfi1_devdata *dd; if (!uctxt || !uctxt->dd || !uctxt->sc) { ret = -EINVAL; break; } /* * There is no protection here. User level has to * guarantee that no one will be writing to the send * context while it is being re-initialized. * If user level breaks that guarantee, it will break * it's own context and no one else's. */ dd = uctxt->dd; sc = uctxt->sc; /* * Wait until the interrupt handler has marked the * context as halted or frozen. Report error if we time * out. */ wait_event_interruptible_timeout( sc->halt_wait, (sc->flags & SCF_HALTED), msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT)); if (!(sc->flags & SCF_HALTED)) { ret = -ENOLCK; break; } /* * If the send context was halted due to a Freeze, * wait until the device has been "unfrozen" before * resetting the context. */ if (sc->flags & SCF_FROZEN) { wait_event_interruptible_timeout( dd->event_queue, !(ACCESS_ONCE(dd->flags) & HFI1_FROZEN), msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT)); if (dd->flags & HFI1_FROZEN) { ret = -ENOLCK; break; } if (dd->flags & HFI1_FORCED_FREEZE) { /* * Don't allow context reset if we are into * forced freeze */ ret = -ENODEV; break; } sc_disable(sc); ret = sc_enable(sc); hfi1_rcvctrl(dd, HFI1_RCVCTRL_CTXT_ENB, uctxt->ctxt); } else { ret = sc_restart(sc); } if (!ret) sc_return_credits(sc); break; } case HFI1_CMD_EP_INFO: case HFI1_CMD_EP_ERASE_CHIP: case HFI1_CMD_EP_ERASE_RANGE: case HFI1_CMD_EP_READ_RANGE: case HFI1_CMD_EP_WRITE_RANGE: ret = handle_eprom_command(fp, &cmd); break; } if (ret >= 0) ret = consumed; bail: return ret; } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, 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); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1614 CWE ID: CWE-119 Target: 1 Example 2: Code: static int ext4_find_delayed_extent(struct inode *inode, struct extent_status *newes) { struct extent_status es; ext4_lblk_t block, next_del; if (newes->es_pblk == 0) { ext4_es_find_delayed_extent_range(inode, newes->es_lblk, newes->es_lblk + newes->es_len - 1, &es); /* * No extent in extent-tree contains block @newes->es_pblk, * then the block may stay in 1)a hole or 2)delayed-extent. */ if (es.es_len == 0) /* A hole found. */ return 0; if (es.es_lblk > newes->es_lblk) { /* A hole found. */ newes->es_len = min(es.es_lblk - newes->es_lblk, newes->es_len); return 0; } newes->es_len = es.es_lblk + es.es_len - newes->es_lblk; } block = newes->es_lblk + newes->es_len; ext4_es_find_delayed_extent_range(inode, block, EXT_MAX_BLOCKS, &es); if (es.es_len == 0) next_del = EXT_MAX_BLOCKS; else next_del = es.es_lblk; return next_del; } Commit Message: ext4: allocate entire range in zero range Currently there is a bug in zero range code which causes zero range calls to only allocate block aligned portion of the range, while ignoring the rest in some cases. In some cases, namely if the end of the range is past i_size, we do attempt to preallocate the last nonaligned block. However this might cause kernel to BUG() in some carefully designed zero range requests on setups where page size > block size. Fix this problem by first preallocating the entire range, including the nonaligned edges and converting the written extents to unwritten in the next step. This approach will also give us the advantage of having the range to be as linearly contiguous as possible. Signed-off-by: Lukas Czerner <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-17 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err) { const char *cl; if (!get_message(conn, ebuf, ebuf_len, err)) { return 0; } if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info) <= 0) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request"); *err = 400; return 0; } /* Message is a valid request */ /* Is there a "host" ? */ conn->host = alloc_get_host(conn); if (!conn->host) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request: Host mismatch"); *err = 400; return 0; } /* Do we know the content length? */ if ((cl = get_header(conn->request_info.http_headers, conn->request_info.num_headers, "Content-Length")) != NULL) { /* Request/response has content length set */ char *endptr = NULL; conn->content_len = strtoll(cl, &endptr, 10); if (endptr == cl) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request"); *err = 411; return 0; } /* Publish the content length back to the request info. */ conn->request_info.content_length = conn->content_len; } else if ((cl = get_header(conn->request_info.http_headers, conn->request_info.num_headers, "Transfer-Encoding")) != NULL && !mg_strcasecmp(cl, "chunked")) { conn->is_chunked = 1; conn->content_len = -1; /* unknown content length */ } else { const struct mg_http_method_info *meth = get_http_method_info(conn->request_info.request_method); if (!meth) { /* No valid HTTP method */ mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request"); *err = 411; return 0; } if (meth->request_has_body) { /* POST or PUT request without content length set */ conn->content_len = -1; /* unknown content length */ } else { /* Other request */ conn->content_len = 0; /* No content */ } } conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */ return 1; } Commit Message: Check length of memcmp CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __sock_diag_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { int err; struct sock_diag_req *req = nlmsg_data(nlh); const struct sock_diag_handler *hndl; if (nlmsg_len(nlh) < sizeof(*req)) return -EINVAL; hndl = sock_diag_lock_handler(req->sdiag_family); if (hndl == NULL) err = -ENOENT; else err = hndl->dump(skb, nlh); sock_diag_unlock_handler(hndl); return err; } Commit Message: sock_diag: Fix out-of-bounds access to sock_diag_handlers[] Userland can send a netlink message requesting SOCK_DIAG_BY_FAMILY with a family greater or equal then AF_MAX -- the array size of sock_diag_handlers[]. The current code does not test for this condition therefore is vulnerable to an out-of-bound access opening doors for a privilege escalation. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: void V8TestObject::XPathNSResolverMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_xPathNSResolverMethod"); test_object_v8_internal::XPathNSResolverMethodMethod(info); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FrameImpl::Reload() { NOTIMPLEMENTED(); } 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 <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void get_socket_name( char* buf, int len ) { char* dpy = g_strdup(g_getenv("DISPLAY")); if(dpy && *dpy) { char* p = strchr(dpy, ':'); for(++p; *p && *p != '.' && *p != '\n';) ++p; if(*p) *p = '\0'; } g_snprintf( buf, len, "%s/.menu-cached-%s-%s", g_get_tmp_dir(), dpy ? dpy : ":0", g_get_user_name() ); g_free(dpy); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static bool trap_dbgauthstatus_el1(struct kvm_vcpu *vcpu, struct sys_reg_params *p, const struct sys_reg_desc *r) { if (p->is_write) { return ignore_write(vcpu, p); } else { p->regval = read_sysreg(dbgauthstatus_el1); return true; } } Commit Message: arm64: KVM: pmu: Fix AArch32 cycle counter access We're missing the handling code for the cycle counter accessed from a 32bit guest, leading to unexpected results. Cc: [email protected] # 4.6+ Signed-off-by: Wei Huang <[email protected]> Signed-off-by: Marc Zyngier <[email protected]> CWE ID: CWE-617 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static PHP_NAMED_FUNCTION(zif_zip_open) { char *filename; int filename_len; char resolved_path[MAXPATHLEN + 1]; zip_rsrc *rsrc_int; int err = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) { return; } if (filename_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string as source"); RETURN_FALSE; } if (ZIP_OPENBASEDIR_CHECKPATH(filename)) { RETURN_FALSE; } if(!expand_filepath(filename, resolved_path TSRMLS_CC)) { RETURN_FALSE; } rsrc_int = (zip_rsrc *)emalloc(sizeof(zip_rsrc)); rsrc_int->za = zip_open(resolved_path, 0, &err); if (rsrc_int->za == NULL) { efree(rsrc_int); RETURN_LONG((long)err); } rsrc_int->index_current = 0; rsrc_int->num_files = zip_get_num_files(rsrc_int->za); ZEND_REGISTER_RESOURCE(return_value, rsrc_int, le_zip_dir); } Commit Message: Fix bug #72434: ZipArchive class Use After Free Vulnerability in PHP's GC algorithm and unserialize CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); assert(send_buf != NULL); } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows CWE ID: CWE-190 Target: 1 Example 2: Code: void LockContentsView::SuspendImminent( power_manager::SuspendImminent::Reason reason) { LoginAuthUserView* auth_user = CurrentBigUserView()->auth_user(); if (auth_user) auth_user->password_view()->Clear(); } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context, MIMETypeCheck mime_type_check) const { if (ErrorOccurred()) return false; KURL sheet_url = GetResponse().Url(); if (sheet_url.IsLocalFile()) { if (parser_context) { parser_context->Count(WebFeature::kLocalCSSFile); } String extension; int last_dot = sheet_url.LastPathComponent().ReverseFind('.'); if (last_dot != -1) extension = sheet_url.LastPathComponent().Substring(last_dot + 1); if (!EqualIgnoringASCIICase( MIMETypeRegistry::GetMIMETypeForExtension(extension), "text/css")) { if (parser_context) { parser_context->CountDeprecation( WebFeature::kLocalCSSFileExtensionRejected); } if (RuntimeEnabledFeatures::RequireCSSExtensionForFileEnabled()) { return false; } } } if (mime_type_check == MIMETypeCheck::kLax) return true; AtomicString content_type = HttpContentType(); return content_type.IsEmpty() || DeprecatedEqualIgnoringCase(content_type, "text/css") || DeprecatedEqualIgnoringCase(content_type, "application/x-unknown-content-type"); } Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag. The feature has long since been stable (since M64) and doesn't seem to be a need for this flag. BUG=788936 Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0 Reviewed-on: https://chromium-review.googlesource.com/c/1324143 Reviewed-by: Mike West <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Dave Tapuska <[email protected]> Cr-Commit-Position: refs/heads/master@{#607329} CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: struct xt_table_info *xt_alloc_table_info(unsigned int size) { struct xt_table_info *info = NULL; size_t sz = sizeof(*info) + size; /* Pedantry: prevent them from hitting BUG() in vmalloc.c --RR */ if ((SMP_ALIGN(size) >> PAGE_SHIFT) + 2 > totalram_pages) return NULL; if (sz <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) info = kmalloc(sz, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); if (!info) { info = vmalloc(sz); if (!info) return NULL; } memset(info, 0, sizeof(*info)); info->size = size; return info; } Commit Message: netfilter: x_tables: check for size overflow Ben Hawkes says: integer overflow in xt_alloc_table_info, which on 32-bit systems can lead to small structure allocation and a copy_from_user based heap corruption. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: static RBinInfo *info(RBinFile *arch) { struct r_bin_bflt_obj *obj = NULL; RBinInfo *info = NULL; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } obj = (struct r_bin_bflt_obj*)arch->o->bin_obj; if (!(info = R_NEW0 (RBinInfo))) { return NULL; } info->file = arch->file ? strdup (arch->file) : NULL; info->rclass = strdup ("bflt"); info->bclass = strdup ("bflt" ); info->type = strdup ("bFLT (Executable file)"); info->os = strdup ("Linux"); info->subsystem = strdup ("Linux"); info->arch = strdup ("arm"); info->big_endian = obj->endian; info->bits = 32; info->has_va = false; info->dbg_info = 0; info->machine = strdup ("unknown"); return info; } Commit Message: Fix #6829 oob write because of using wrong struct CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int MDC2_Update(MDC2_CTX *c, const unsigned char *in, size_t len) { size_t i, j; i = c->num; if (i != 0) { if (i + len < MDC2_BLOCK) { /* partial block */ memcpy(&(c->data[i]), in, len); c->num += (int)len; return 1; } else { /* filled one */ j = MDC2_BLOCK - i; memcpy(&(c->data[i]), in, j); len -= j; in += j; c->num = 0; mdc2_body(c, &(c->data[0]), MDC2_BLOCK); } } i = len & ~((size_t)MDC2_BLOCK - 1); if (i > 0) mdc2_body(c, in, i); j = len - i; if (j > 0) { memcpy(&(c->data[0]), &(in[i]), j); c->num = (int)j; } return 1; } Commit Message: CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool Instance::HandleInputEvent(const pp::InputEvent& event) { pp::InputEvent event_device_res(event); { pp::MouseInputEvent mouse_event(event); if (!mouse_event.is_null()) { pp::Point point = mouse_event.GetPosition(); pp::Point movement = mouse_event.GetMovement(); ScalePoint(device_scale_, &point); ScalePoint(device_scale_, &movement); mouse_event = pp::MouseInputEvent( this, event.GetType(), event.GetTimeStamp(), event.GetModifiers(), mouse_event.GetButton(), point, mouse_event.GetClickCount(), movement); event_device_res = mouse_event; } } if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE && (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) { pp::MouseInputEvent mouse_event(event_device_res); pp::Point pos = mouse_event.GetPosition(); EnableAutoscroll(pos); UpdateCursor(CalculateAutoscroll(pos)); return true; } else { DisableAutoscroll(); } #ifdef ENABLE_THUMBNAILS if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE) thumbnails_.SlideOut(); if (thumbnails_.HandleEvent(event_device_res)) return true; #endif if (toolbar_->HandleEvent(event_device_res)) return true; #ifdef ENABLE_THUMBNAILS if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) { pp::MouseInputEvent mouse_event(event); pp::Point pt = mouse_event.GetPosition(); pp::Rect v_scrollbar_rc; v_scrollbar_->GetLocation(&v_scrollbar_rc); if (v_scrollbar_rc.Contains(pt) && (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) { thumbnails_.SlideIn(); } if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() && !(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) && !thumbnails_.rect().Contains(pt)) { thumbnails_.SlideOut(); } } #endif pp::InputEvent offset_event(event_device_res); bool try_engine_first = true; switch (offset_event.GetType()) { case PP_INPUTEVENT_TYPE_MOUSEDOWN: case PP_INPUTEVENT_TYPE_MOUSEUP: case PP_INPUTEVENT_TYPE_MOUSEMOVE: case PP_INPUTEVENT_TYPE_MOUSEENTER: case PP_INPUTEVENT_TYPE_MOUSELEAVE: { pp::MouseInputEvent mouse_event(event_device_res); pp::MouseInputEvent mouse_event_dip(event); pp::Point point = mouse_event.GetPosition(); point.set_x(point.x() - available_area_.x()); offset_event = pp::MouseInputEvent( this, event.GetType(), event.GetTimeStamp(), event.GetModifiers(), mouse_event.GetButton(), point, mouse_event.GetClickCount(), mouse_event.GetMovement()); if (!engine_->IsSelecting()) { if (!IsOverlayScrollbar() && !available_area_.Contains(mouse_event.GetPosition())) { try_engine_first = false; } else if (IsOverlayScrollbar()) { pp::Rect temp; if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) && temp.Contains(mouse_event_dip.GetPosition())) || (h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) && temp.Contains(mouse_event_dip.GetPosition()))) { try_engine_first = false; } } } break; } default: break; } if (try_engine_first && engine_->HandleEvent(offset_event)) return true; if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) { pp::KeyboardInputEvent keyboard_event(event); bool no_h_scrollbar = !h_scrollbar_.get(); uint32_t key_code = keyboard_event.GetKeyCode(); bool page_down = no_h_scrollbar && key_code == ui::VKEY_RIGHT; bool page_up = no_h_scrollbar && key_code == ui::VKEY_LEFT; if (zoom_mode_ == ZOOM_FIT_TO_PAGE) { bool has_shift = keyboard_event.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY; bool key_is_space = key_code == ui::VKEY_SPACE; page_down |= key_is_space || key_code == ui::VKEY_NEXT; page_up |= (key_is_space && has_shift) || (key_code == ui::VKEY_PRIOR); } if (page_down) { int page = engine_->GetFirstVisiblePage(); if (engine_->GetPageRect(page).bottom() * zoom_ <= v_scrollbar_->GetValue()) page++; ScrollToPage(page + 1); UpdateCursor(PP_CURSORTYPE_POINTER); return true; } else if (page_up) { int page = engine_->GetFirstVisiblePage(); if (engine_->GetPageRect(page).y() * zoom_ >= v_scrollbar_->GetValue()) page--; ScrollToPage(page); UpdateCursor(PP_CURSORTYPE_POINTER); return true; } } if (v_scrollbar_.get() && v_scrollbar_->HandleEvent(event)) { UpdateCursor(PP_CURSORTYPE_POINTER); return true; } if (h_scrollbar_.get() && h_scrollbar_->HandleEvent(event)) { UpdateCursor(PP_CURSORTYPE_POINTER); return true; } if (timer_pending_ && (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP || event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE)) { timer_factory_.CancelAll(); timer_pending_ = false; } else if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE && engine_->IsSelecting()) { bool set_timer = false; pp::MouseInputEvent mouse_event(event); if (v_scrollbar_.get() && (mouse_event.GetPosition().y() <= 0 || mouse_event.GetPosition().y() >= (plugin_dip_size_.height() - 1))) { v_scrollbar_->ScrollBy( PP_SCROLLBY_LINE, mouse_event.GetPosition().y() >= 0 ? 1: -1); set_timer = true; } if (h_scrollbar_.get() && (mouse_event.GetPosition().x() <= 0 || mouse_event.GetPosition().x() >= (plugin_dip_size_.width() - 1))) { h_scrollbar_->ScrollBy(PP_SCROLLBY_LINE, mouse_event.GetPosition().x() >= 0 ? 1: -1); set_timer = true; } if (set_timer) { last_mouse_event_ = pp::MouseInputEvent(event); pp::CompletionCallback callback = timer_factory_.NewCallback(&Instance::OnTimerFired); pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs, callback); timer_pending_ = true; } } if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN && event.GetModifiers() & kDefaultKeyModifier) { pp::KeyboardInputEvent keyboard_event(event); switch (keyboard_event.GetKeyCode()) { case 'A': engine_->SelectAll(); return true; } } return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN); } Commit Message: Let PDFium handle event when there is not yet a visible page. Speculative fix for 415307. CF will confirm. The stack trace for that bug indicates an attempt to index by -1, which is consistent with no visible page. BUG=415307 Review URL: https://codereview.chromium.org/560133004 Cr-Commit-Position: refs/heads/master@{#295421} CWE ID: CWE-119 Target: 1 Example 2: Code: static void anyAttributeAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_VOID(ScriptValue, cppValue, ScriptValue(jsValue, info.GetIsolate())); imp->setAnyAttribute(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct bsg_device *bd = file->private_data; ssize_t bytes_written; int ret; dprintk("%s: write %Zd bytes\n", bd->name, count); bsg_set_block(bd, file); bytes_written = 0; ret = __bsg_write(bd, buf, count, &bytes_written, file->f_mode & FMODE_WRITE); *ppos = bytes_written; /* * return bytes written on non-fatal errors */ if (!bytes_written || err_block_err(ret)) bytes_written = ret; dprintk("%s: returning %Zd\n", bd->name, bytes_written); return bytes_written; } Commit Message: sg_write()/bsg_write() is not fit to be called under KERNEL_DS Both damn things interpret userland pointers embedded into the payload; worse, they are actually traversing those. Leaving aside the bad API design, this is very much _not_ safe to call with KERNEL_DS. Bail out early if that happens. Cc: [email protected] Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx) { struct xenvif *vif; struct pending_tx_info *pending_tx_info; pending_ring_idx_t index; /* Already complete? */ if (netbk->mmap_pages[pending_idx] == NULL) return; pending_tx_info = &netbk->pending_tx_info[pending_idx]; vif = pending_tx_info->vif; make_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY); index = pending_index(netbk->pending_prod++); netbk->pending_ring[index] = pending_idx; xenvif_put(vif); netbk->mmap_pages[pending_idx]->mapping = 0; put_page(netbk->mmap_pages[pending_idx]); netbk->mmap_pages[pending_idx] = NULL; } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Ian Campbell <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static ssize_t pagemap_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode); struct mm_struct *mm; struct pagemapread pm; int ret = -ESRCH; struct mm_walk pagemap_walk = {}; unsigned long src; unsigned long svpfn; unsigned long start_vaddr; unsigned long end_vaddr; int copied = 0; if (!task) goto out; ret = -EINVAL; /* file position must be aligned */ if ((*ppos % PM_ENTRY_BYTES) || (count % PM_ENTRY_BYTES)) goto out_task; ret = 0; if (!count) goto out_task; pm.len = PM_ENTRY_BYTES * (PAGEMAP_WALK_SIZE >> PAGE_SHIFT); pm.buffer = kmalloc(pm.len, GFP_TEMPORARY); ret = -ENOMEM; if (!pm.buffer) goto out_task; mm = mm_for_maps(task); ret = PTR_ERR(mm); if (!mm || IS_ERR(mm)) goto out_free; pagemap_walk.pmd_entry = pagemap_pte_range; pagemap_walk.pte_hole = pagemap_pte_hole; #ifdef CONFIG_HUGETLB_PAGE pagemap_walk.hugetlb_entry = pagemap_hugetlb_range; #endif pagemap_walk.mm = mm; pagemap_walk.private = &pm; src = *ppos; svpfn = src / PM_ENTRY_BYTES; start_vaddr = svpfn << PAGE_SHIFT; end_vaddr = TASK_SIZE_OF(task); /* watch out for wraparound */ if (svpfn > TASK_SIZE_OF(task) >> PAGE_SHIFT) start_vaddr = end_vaddr; /* * The odds are that this will stop walking way * before end_vaddr, because the length of the * user buffer is tracked in "pm", and the walk * will stop when we hit the end of the buffer. */ ret = 0; while (count && (start_vaddr < end_vaddr)) { int len; unsigned long end; pm.pos = 0; end = (start_vaddr + PAGEMAP_WALK_SIZE) & PAGEMAP_WALK_MASK; /* overflow ? */ if (end < start_vaddr || end > end_vaddr) end = end_vaddr; down_read(&mm->mmap_sem); ret = walk_page_range(start_vaddr, end, &pagemap_walk); up_read(&mm->mmap_sem); start_vaddr = end; len = min(count, PM_ENTRY_BYTES * pm.pos); if (copy_to_user(buf, pm.buffer, len)) { ret = -EFAULT; goto out_mm; } copied += len; buf += len; count -= len; } *ppos += copied; if (!ret || ret == PM_END_OF_BUFFER) ret = copied; out_mm: mmput(mm); out_free: kfree(pm.buffer); out_task: put_task_struct(task); out: return ret; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ras_validate(jas_stream_t *in) { uchar buf[RAS_MAGICLEN]; int i; int n; uint_fast32_t magic; assert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN); /* Read the validation data (i.e., the data used for detecting the format). */ if ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) { return -1; } /* Put the validation data back onto the stream, so that the stream position will not be changed. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Did we read enough data? */ if (n < RAS_MAGICLEN) { return -1; } magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) | (JAS_CAST(uint_fast32_t, buf[1]) << 16) | (JAS_CAST(uint_fast32_t, buf[2]) << 8) | buf[3]; /* Is the signature correct for the Sun Rasterfile format? */ if (magic != RAS_MAGIC) { return -1; } return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: v8::Handle<v8::Value> V8WebGLRenderingContext::getUniformCallback(const v8::Arguments& args) { INC_STATS("DOM.WebGLRenderingContext.getUniform()"); if (args.Length() != 2) return V8Proxy::throwNotEnoughArgumentsError(); ExceptionCode ec = 0; WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLProgram::HasInstance(args[0])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } WebGLProgram* program = V8WebGLProgram::HasInstance(args[0]) ? V8WebGLProgram::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0; if (args.Length() > 1 && !isUndefinedOrNull(args[1]) && !V8WebGLUniformLocation::HasInstance(args[1])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } bool ok = false; WebGLUniformLocation* location = toWebGLUniformLocation(args[1], ok); WebGLGetInfo info = context->getUniform(program, location, ec); if (ec) { V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } return toV8Object(info, args.GetIsolate()); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: gp_abgr16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = pp[3]; p->g = pp[2]; p->b = pp[1]; p->a = pp[0]; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: http_PrintfHeader(struct worker *w, int fd, struct http *to, const char *fmt, ...) { va_list ap; unsigned l, n; CHECK_OBJ_NOTNULL(to, HTTP_MAGIC); l = WS_Reserve(to->ws, 0); va_start(ap, fmt); n = vsnprintf(to->ws->f, l, fmt, ap); va_end(ap); if (n + 1 >= l || to->nhd >= to->shd) { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%s", to->ws->f); WS_Release(to->ws, 0); } else { to->hd[to->nhd].b = to->ws->f; to->hd[to->nhd].e = to->ws->f + n; to->hdf[to->nhd] = 0; WS_Release(to->ws, n + 1); to->nhd++; } } Commit Message: Check for duplicate Content-Length headers in requests If a duplicate CL header is in the request, we fail the request with a 400 (Bad Request) Fix a test case that was sending duplicate CL by misstake and would not fail because of that. CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ssl23_get_client_hello(SSL *s) { char buf_space[11]; /* Request this many bytes in initial read. * We can detect SSL 3.0/TLS 1.0 Client Hellos * ('type == 3') correctly only when the following * is in a single record, which is not guaranteed by * the protocol specification: * Byte Content * 0 type \ * 1/2 version > record header * 3/4 length / * 5 msg_type \ * 6-8 length > Client Hello message * 9/10 client_version / */ char *buf= &(buf_space[0]); unsigned char *p,*d,*d_len,*dd; unsigned int i; unsigned int csl,sil,cl; int n=0,j; int type=0; int v[2]; if (s->state == SSL23_ST_SR_CLNT_HELLO_A) { /* read the initial header */ v[0]=v[1]=0; if (!ssl3_setup_buffers(s)) goto err; n=ssl23_read_bytes(s, sizeof buf_space); if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ p=s->packet; memcpy(buf,p,n); if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 header */ if ((p[3] == 0x00) && (p[4] == 0x02)) { v[0]=p[3]; v[1]=p[4]; /* SSLv2 */ if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } else if (p[3] == SSL3_VERSION_MAJOR) { v[0]=p[3]; v[1]=p[4]; /* SSLv3/TLSv1 */ if (p[4] >= TLS1_VERSION_MINOR) { if (p[4] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (p[4] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) { type=1; } } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } } else if ((p[0] == SSL3_RT_HANDSHAKE) && (p[1] == SSL3_VERSION_MAJOR) && (p[5] == SSL3_MT_CLIENT_HELLO) && ((p[3] == 0 && p[4] < 5 /* silly record length? */) || (p[9] >= p[1]))) { /* * SSLv3 or tls1 header */ v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ /* We must look at client_version inside the Client Hello message * to get the correct minor version. * However if we have only a pathologically small fragment of the * Client Hello message, this would be difficult, and we'd have * to read more records to find out. * No known SSL 3.0 client fragments ClientHello like this, * so we simply reject such connections to avoid * protocol version downgrade attacks. */ if (p[3] == 0 && p[4] < 6) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); goto err; } /* if major version number > 3 set minor to a value * which will use the highest version 3 we support. * If TLS 2.0 ever appears we will need to revise * this.... */ if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ if (v[1] >= TLS1_VERSION_MINOR) { if (v[1] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; type=3; } else if (v[1] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } } else { /* client requests SSL 3.0 */ if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { /* we won't be able to use TLS of course, * but this will send an appropriate alert */ s->version=TLS1_VERSION; type=3; } } } else if ((strncmp("GET ", (char *)p,4) == 0) || (strncmp("POST ",(char *)p,5) == 0) || (strncmp("HEAD ",(char *)p,5) == 0) || (strncmp("PUT ", (char *)p,4) == 0)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); goto err; } else if (strncmp("CONNECT",(char *)p,7) == 0) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); goto err; } } /* ensure that TLS_MAX_VERSION is up-to-date */ OPENSSL_assert(s->version <= TLS_MAX_VERSION); #ifdef OPENSSL_FIPS if (FIPS_mode() && (s->version < TLS1_VERSION)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); goto err; } #endif if (s->state == SSL23_ST_SR_CLNT_HELLO_B) { /* we have SSLv3/TLSv1 in an SSLv2 header * (other cases skip this state) */ type=2; p=s->packet; v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ v[1] = p[4]; /* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 * header is sent directly on the wire, not wrapped as a TLS * record. It's format is: * Byte Content * 0-1 msg_length * 2 msg_type * 3-4 version * 5-6 cipher_spec_length * 7-8 session_id_length * 9-10 challenge_length * ... ... */ n=((p[0]&0x7f)<<8)|p[1]; if (n > (1024*4)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); goto err; } if (n < 9) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } j=ssl23_read_bytes(s,n+2); /* We previously read 11 bytes, so if j > 0, we must have * j == n+2 == s->packet_length. We have at least 11 valid * packet bytes. */ if (j <= 0) return(j); ssl3_finish_mac(s, s->packet+2, s->packet_length-2); if (s->msg_callback) s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */ p=s->packet; p+=5; n2s(p,csl); n2s(p,sil); n2s(p,cl); d=(unsigned char *)s->init_buf->data; if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format * Client Hello, can we? Error condition should be * '>' otherweise */ { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } /* record header: msg_type ... */ *(d++) = SSL3_MT_CLIENT_HELLO; /* ... and length (actual value will be written later) */ d_len = d; d += 3; /* client_version */ *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ *(d++) = v[1]; /* lets populate the random area */ /* get the challenge_length */ i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; memset(d,0,SSL3_RANDOM_SIZE); memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); d+=SSL3_RANDOM_SIZE; /* no session-id reuse */ *(d++)=0; /* ciphers */ j=0; dd=d; d+=2; for (i=0; i<csl; i+=3) { if (p[i] != 0) continue; *(d++)=p[i+1]; *(d++)=p[i+2]; j+=2; } s2n(j,dd); /* COMPRESSION */ *(d++)=1; *(d++)=0; #if 0 /* copy any remaining data with may be extensions */ p = p+csl+sil+cl; while (p < s->packet+s->packet_length) { *(d++)=*(p++); } #endif i = (d-(unsigned char *)s->init_buf->data) - 4; l2n3((long)i, d_len); /* get the data reused from the init_buf */ s->s3->tmp.reuse_message=1; s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; s->s3->tmp.message_size=i; } /* imaginary new state (for program structure): */ /* s->state = SSL23_SR_CLNT_HELLO_C */ if (type == 1) { #ifdef OPENSSL_NO_SSL2 SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; #else /* we are talking sslv2 */ /* we need to clean up the SSLv3/TLSv1 setup and put in the * sslv2 stuff. */ if (s->s2 == NULL) { if (!ssl2_new(s)) goto err; } else ssl2_clear(s); if (s->s3 != NULL) ssl3_free(s); if (!BUF_MEM_grow_clean(s->init_buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { goto err; } s->state=SSL2_ST_GET_CLIENT_HELLO_A; if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) s->s2->ssl2_rollback=0; else /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 * (SSL 3.0 draft/RFC 2246, App. E.2) */ s->s2->ssl2_rollback=1; /* setup the n bytes we have read so we get them from * the sslv2 buffer */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s2->rbuf[0]); memcpy(s->packet,buf,n); s->s2->rbuf_left=n; s->s2->rbuf_offs=0; s->method=SSLv2_server_method(); s->handshake_func=s->method->ssl_accept; #endif } if ((type == 2) || (type == 3)) { /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ s->method = ssl23_get_server_method(s->version); if (s->method == NULL) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; } if (!ssl_init_wbio_buffer(s,1)) goto err; if (type == 3) { /* put the 'n' bytes we have read into the input buffer * for SSLv3 */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; if (s->s3->rbuf.buf == NULL) if (!ssl3_setup_read_buffer(s)) goto err; s->packet= &(s->s3->rbuf.buf[0]); memcpy(s->packet,buf,n); s->s3->rbuf.left=n; s->s3->rbuf.offset=0; } else { s->packet_length=0; s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } #if 0 /* ssl3_get_client_hello does this */ s->client_version=(v[0]<<8)|v[1]; #endif s->handshake_func=s->method->ssl_accept; } if ((type < 1) || (type > 3)) { /* bad, very bad */ SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL); goto err; } s->init_num=0; if (buf != buf_space) OPENSSL_free(buf); return(SSL_accept(s)); err: if (buf != buf_space) OPENSSL_free(buf); return(-1); } Commit Message: CWE ID: Target: 1 Example 2: Code: void BrowserNonClientFrameViewAura::GetAccessibleState( ui::AccessibleViewState* state) { state->role = ui::AccessibilityTypes::ROLE_TITLEBAR; } Commit Message: Ash: Fix fullscreen window bounds I was computing the non-client frame top border height incorrectly for fullscreen windows, so it was trying to draw a few pixels of transparent non-client border. BUG=118774 TEST=visual Review URL: http://codereview.chromium.org/9810014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@128014 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: NTSTATUS MountManagerUnmount (int nDosDriveNo) { NTSTATUS ntStatus; char buf[256], out[300]; PMOUNTMGR_MOUNT_POINT in = (PMOUNTMGR_MOUNT_POINT) buf; memset (buf, 0, sizeof buf); TCGetDosNameFromNumber ((PWSTR) &in[1], sizeof(buf) - sizeof(MOUNTMGR_MOUNT_POINT),nDosDriveNo, DeviceNamespaceDefault); in->SymbolicLinkNameOffset = sizeof (MOUNTMGR_MOUNT_POINT); in->SymbolicLinkNameLength = (USHORT) wcslen ((PWCHAR) &in[1]) * 2; ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_DELETE_POINTS, in, sizeof(MOUNTMGR_MOUNT_POINT) + in->SymbolicLinkNameLength, out, sizeof out); Dump ("IOCTL_MOUNTMGR_DELETE_POINTS returned 0x%08x\n", ntStatus); return ntStatus; } Commit Message: Windows: fix low severity vulnerability in driver that allowed reading 3 bytes of kernel stack memory (with a rare possibility of 25 additional bytes). Reported by Tim Harrison. CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ChromeContentBrowserClient::ShouldSwapProcessesForNavigation( const GURL& current_url, const GURL& new_url) { if (current_url.is_empty()) { if (new_url.SchemeIs(extensions::kExtensionScheme)) return true; return false; } if (current_url.SchemeIs(extensions::kExtensionScheme) || new_url.SchemeIs(extensions::kExtensionScheme)) { if (current_url.GetOrigin() != new_url.GetOrigin()) return true; } return false; } Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances. BUG=174943 TEST=Can't post message to CWS. See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12301013 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 1 Example 2: Code: void blk_queue_bypass_end(struct request_queue *q) { spin_lock_irq(q->queue_lock); if (!--q->bypass_depth) queue_flag_clear(QUEUE_FLAG_BYPASS, q); WARN_ON_ONCE(q->bypass_depth < 0); spin_unlock_irq(q->queue_lock); } Commit Message: block: blk_init_allocated_queue() set q->fq as NULL in the fail case We find the memory use-after-free issue in __blk_drain_queue() on the kernel 4.14. After read the latest kernel 4.18-rc6 we think it has the same problem. Memory is allocated for q->fq in the blk_init_allocated_queue(). If the elevator init function called with error return, it will run into the fail case to free the q->fq. Then the __blk_drain_queue() uses the same memory after the free of the q->fq, it will lead to the unpredictable event. The patch is to set q->fq as NULL in the fail case of blk_init_allocated_queue(). Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery") Cc: <[email protected]> Reviewed-by: Ming Lei <[email protected]> Reviewed-by: Bart Van Assche <[email protected]> Signed-off-by: xiao jin <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void MaybeRestoreIBusConfig() { if (!ibus_) { return; } MaybeDestroyIBusConfig(); if (!ibus_config_) { GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_); if (!ibus_connection) { LOG(INFO) << "Couldn't create an ibus config object since " << "IBus connection is not ready."; return; } const gboolean disconnected = g_dbus_connection_is_closed(ibus_connection); if (disconnected) { LOG(ERROR) << "Couldn't create an ibus config object since " << "IBus connection is closed."; return; } ibus_config_ = ibus_config_new(ibus_connection, NULL /* do not cancel the operation */, NULL /* do not get error information */); if (!ibus_config_) { LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?"; return; } g_object_ref(ibus_config_); LOG(INFO) << "ibus_config_ is ready."; } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { Image *clone_image; double scale; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "NegativeOrZeroImageSize","`%s'",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image)); if (clone_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickCoreSignature; clone_image->storage_class=image->storage_class; clone_image->number_channels=image->number_channels; clone_image->number_meta_channels=image->number_meta_channels; clone_image->metacontent_extent=image->metacontent_extent; clone_image->colorspace=image->colorspace; clone_image->read_mask=image->read_mask; clone_image->write_mask=image->write_mask; clone_image->alpha_trait=image->alpha_trait; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; if (image->colormap != (PixelInfo *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } clone_image->image_info=CloneImageInfo(image->image_info); (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; clone_image->channel_mask=image->channel_mask; clone_image->channel_map=ClonePixelChannelMap(image->channel_map); (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MagickPathExtent); (void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent); (void) CopyMagickString(clone_image->filename,image->filename, MagickPathExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AcquireSemaphoreInfo(); if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->columns=columns; clone_image->rows=rows; clone_image->cache=ClonePixelCache(image->cache); return(clone_image); } Commit Message: Set pixel cache to undefined if any resource limit is exceeded CWE ID: CWE-119 Target: 1 Example 2: Code: OperationID FileSystemOperationRunner::Write( const FileSystemURL& url, std::unique_ptr<storage::BlobDataHandle> blob, int64_t offset, const WriteCallback& callback) { base::File::Error error = base::File::FILE_OK; std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); OperationID id = BeginOperation(std::move(operation)); base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { DidWrite(id, callback, error, 0, true); return id; } std::unique_ptr<FileStreamWriter> writer( file_system_context_->CreateFileStreamWriter(url, offset)); if (!writer) { DidWrite(id, callback, base::File::FILE_ERROR_SECURITY, 0, true); return id; } std::unique_ptr<FileWriterDelegate> writer_delegate(new FileWriterDelegate( std::move(writer), url.mount_option().flush_policy())); std::unique_ptr<BlobReader> blob_reader; if (blob) blob_reader = blob->CreateReader(); PrepareForWrite(id, url); operation_raw->WriteBlob( url, std::move(writer_delegate), std::move(blob_reader), base::BindRepeating(&FileSystemOperationRunner::DidWrite, weak_ptr_, id, callback)); return id; } Commit Message: [FileSystem] Harden against overflows of OperationID a bit better. Rather than having a UAF when OperationID overflows instead overwrite the old operation with the new one. Can still cause weirdness, but at least won't result in UAF. Also update OperationID to uint64_t to make sure we don't overflow to begin with. Bug: 925864 Change-Id: Ifdf3fa0935ab5ea8802d91bba39601f02b0dbdc9 Reviewed-on: https://chromium-review.googlesource.com/c/1441498 Commit-Queue: Marijn Kruisselbrink <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#627115} CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Browser::HandleKeyboardEvent(content::WebContents* source, const NativeWebKeyboardEvent& event) { window()->HandleKeyboardEvent(event); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: psf_fwrite (const void *ptr, sf_count_t bytes, sf_count_t items, SF_PRIVATE *psf) { sf_count_t total = 0 ; ssize_t count ; if (psf->virtual_io) return psf->vio.write (ptr, bytes*items, psf->vio_user_data) / bytes ; items *= bytes ; /* Do this check after the multiplication above. */ if (items <= 0) return 0 ; while (items > 0) { /* Break the writes down to a sensible size. */ count = (items > SENSIBLE_SIZE) ? SENSIBLE_SIZE : items ; count = write (psf->file.filedes, ((const char*) ptr) + total, count) ; if (count == -1) { if (errno == EINTR) continue ; psf_log_syserr (psf, errno) ; break ; } ; if (count == 0) break ; total += count ; items -= count ; } ; if (psf->is_pipe) psf->pipeoffset += total ; return total / bytes ; } /* psf_fwrite */ Commit Message: src/file_io.c : Prevent potential divide-by-zero. Closes: https://github.com/erikd/libsndfile/issues/92 CWE ID: CWE-189 Target: 1 Example 2: Code: static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc, struct tpacket3_hdr *ppd) { ppd->hv1.tp_rxhash = skb_get_hash(pkc->skb); } Commit Message: packet: fix race condition in packet_set_ring When packet_set_ring creates a ring buffer it will initialize a struct timer_list if the packet version is TPACKET_V3. This value can then be raced by a different thread calling setsockopt to set the version to TPACKET_V1 before packet_set_ring has finished. This leads to a use-after-free on a function pointer in the struct timer_list when the socket is closed as the previously initialized timer will not be deleted. The bug is fixed by taking lock_sock(sk) in packet_setsockopt when changing the packet version while also taking the lock at the start of packet_set_ring. Fixes: f6fb8f100b80 ("af-packet: TPACKET_V3 flexible buffer implementation.") Signed-off-by: Philip Pettersson <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BlockEntry::~BlockEntry() {} 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MediaElementAudioSourceHandler::OnCurrentSrcChanged( const KURL& current_src) { DCHECK(IsMainThread()); Locker<MediaElementAudioSourceHandler> locker(*this); passes_current_src_cors_access_check_ = PassesCurrentSrcCORSAccessCheck(current_src); maybe_print_cors_message_ = !passes_current_src_cors_access_check_; current_src_string_ = current_src.GetString(); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20 Target: 1 Example 2: Code: void FlagsState::ConvertFlagsToSwitches(FlagsStorage* flags_storage, base::CommandLine* command_line, SentinelsMode sentinels) { if (command_line->HasSwitch(switches::kNoExperiments)) return; std::set<std::string> enabled_experiments; GetSanitizedEnabledFlagsForCurrentPlatform(flags_storage, &enabled_experiments); NameToSwitchAndValueMap name_to_switch_map; for (size_t i = 0; i < num_experiments; ++i) { const Experiment& e = experiments[i]; if (e.type == Experiment::SINGLE_VALUE) { SetFlagToSwitchMapping(e.internal_name, e.command_line_switch, e.command_line_value, &name_to_switch_map); } else if (e.type == Experiment::MULTI_VALUE) { for (int j = 0; j < e.num_choices; ++j) { SetFlagToSwitchMapping(e.NameForChoice(j), e.choices[j].command_line_switch, e.choices[j].command_line_value, &name_to_switch_map); } } else { DCHECK_EQ(e.type, Experiment::ENABLE_DISABLE_VALUE); SetFlagToSwitchMapping(e.NameForChoice(0), std::string(), std::string(), &name_to_switch_map); SetFlagToSwitchMapping(e.NameForChoice(1), e.command_line_switch, e.command_line_value, &name_to_switch_map); SetFlagToSwitchMapping(e.NameForChoice(2), e.disable_command_line_switch, e.disable_command_line_value, &name_to_switch_map); } } if (sentinels == kAddSentinels) { command_line->AppendSwitch(switches::kFlagSwitchesBegin); flags_switches_.insert( std::pair<std::string, std::string>(switches::kFlagSwitchesBegin, std::string())); } for (const std::string& experiment_name : enabled_experiments) { NameToSwitchAndValueMap::const_iterator name_to_switch_it = name_to_switch_map.find(experiment_name); if (name_to_switch_it == name_to_switch_map.end()) { NOTREACHED(); continue; } const std::pair<std::string, std::string>& switch_and_value_pair = name_to_switch_it->second; CHECK(!switch_and_value_pair.first.empty()); command_line->AppendSwitchASCII(switch_and_value_pair.first, switch_and_value_pair.second); flags_switches_[switch_and_value_pair.first] = switch_and_value_pair.second; } if (sentinels == kAddSentinels) { command_line->AppendSwitch(switches::kFlagSwitchesEnd); flags_switches_.insert( std::pair<std::string, std::string>(switches::kFlagSwitchesEnd, std::string())); } } Commit Message: Move smart deploy to tristate. BUG= Review URL: https://codereview.chromium.org/1149383006 Cr-Commit-Position: refs/heads/master@{#333058} CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void cJSON_ReplaceItemInObject( cJSON *object, const char *string, cJSON *newitem ) { int i = 0; cJSON *c = object->child; while ( c && cJSON_strcasecmp( c->string, string ) ) { ++i; c = c->next; } if ( c ) { newitem->string = cJSON_strdup( string ); cJSON_ReplaceItemInArray( object, i, newitem ); } } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BrowserLauncherItemController::TabDetachedAt(TabContents* contents, int index) { launcher_controller()->UpdateAppState( contents->web_contents(), ChromeLauncherController::APP_STATE_REMOVED); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderFrameHostImpl::OnAccessibilityLocationChanges( const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) { if (accessibility_reset_token_) return; RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetWidget()->GetView()); if (view && is_active()) { ui::AXMode accessibility_mode = delegate_->GetAccessibilityMode(); if (accessibility_mode.has_mode(ui::AXMode::kNativeAPIs)) { BrowserAccessibilityManager* manager = GetOrCreateBrowserAccessibilityManager(); if (manager) manager->OnLocationChanges(params); } std::vector<AXLocationChangeNotificationDetails> details; details.reserve(params.size()); for (size_t i = 0; i < params.size(); ++i) { const AccessibilityHostMsg_LocationChangeParams& param = params[i]; AXLocationChangeNotificationDetails detail; detail.id = param.id; detail.ax_tree_id = GetAXTreeID(); detail.new_location = param.new_location; details.push_back(detail); } delegate_->AccessibilityLocationChangesReceived(details); } } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ssl3_connect(SSL *s) { BUF_MEM *buf=NULL; unsigned long Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; int ret= -1; int new_state,state,skip=0; RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch(s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=1; s->state=SSL_ST_CONNECT; s->ctx->stats.sess_connect_renegotiate++; /* break */ case SSL_ST_BEFORE: case SSL_ST_CONNECT: case SSL_ST_BEFORE|SSL_ST_CONNECT: case SSL_ST_OK|SSL_ST_CONNECT: s->server=0; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version & 0xff00 ) != 0x0300) { SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR); ret = -1; goto end; } /* s->version=SSL3_VERSION; */ s->type=SSL_ST_CONNECT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { ret= -1; goto end; } s->init_buf=buf; buf=NULL; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } /* setup buffing BIO */ if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; } /* don't push the buffering BIO quite yet */ ssl3_init_finished_mac(s); s->state=SSL3_ST_CW_CLNT_HELLO_A; s->ctx->stats.sess_connect++; s->init_num=0; break; case SSL3_ST_CW_CLNT_HELLO_A: case SSL3_ST_CW_CLNT_HELLO_B: s->shutdown=0; ret=ssl3_client_hello(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_SRVR_HELLO_A; s->init_num=0; /* turn on buffering for the next lot of output */ if (s->bbio != s->wbio) s->wbio=BIO_push(s->bbio,s->wbio); break; case SSL3_ST_CR_SRVR_HELLO_A: case SSL3_ST_CR_SRVR_HELLO_B: ret=ssl3_get_server_hello(s); if (ret <= 0) goto end; if (s->hit) { s->state=SSL3_ST_CR_FINISHED_A; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_ticket_expected) { /* receive renewed session ticket */ s->state=SSL3_ST_CR_SESSION_TICKET_A; } #endif } else s->state=SSL3_ST_CR_CERT_A; s->init_num=0; break; case SSL3_ST_CR_CERT_A: case SSL3_ST_CR_CERT_B: #ifndef OPENSSL_NO_TLSEXT ret=ssl3_check_finished(s); if (ret <= 0) goto end; if (ret == 2) { s->hit = 1; if (s->tlsext_ticket_expected) s->state=SSL3_ST_CR_SESSION_TICKET_A; else s->state=SSL3_ST_CR_FINISHED_A; s->init_num=0; break; } #endif /* Check if it is anon DH/ECDH */ /* or PSK */ if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { ret=ssl3_get_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_CR_CERT_STATUS_A; else s->state=SSL3_ST_CR_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_CR_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_CR_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_CR_KEY_EXCH_A: case SSL3_ST_CR_KEY_EXCH_B: ret=ssl3_get_key_exchange(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_CERT_REQ_A; s->init_num=0; /* at this point we check that we have the * required stuff from the server */ if (!ssl3_check_cert_and_algorithm(s)) { ret= -1; goto end; } break; case SSL3_ST_CR_CERT_REQ_A: case SSL3_ST_CR_CERT_REQ_B: ret=ssl3_get_certificate_request(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_SRVR_DONE_A; s->init_num=0; break; case SSL3_ST_CR_SRVR_DONE_A: case SSL3_ST_CR_SRVR_DONE_B: ret=ssl3_get_server_done(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SRP if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) { if ((ret = SRP_Calc_A_param(s))<=0) { SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); goto end; } } #endif if (s->s3->tmp.cert_req) s->state=SSL3_ST_CW_CERT_A; else s->state=SSL3_ST_CW_KEY_EXCH_A; s->init_num=0; break; case SSL3_ST_CW_CERT_A: case SSL3_ST_CW_CERT_B: case SSL3_ST_CW_CERT_C: case SSL3_ST_CW_CERT_D: ret=ssl3_send_client_certificate(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_KEY_EXCH_A; s->init_num=0; break; case SSL3_ST_CW_KEY_EXCH_A: case SSL3_ST_CW_KEY_EXCH_B: ret=ssl3_send_client_key_exchange(s); if (ret <= 0) goto end; /* EAY EAY EAY need to check for DH fix cert * sent back */ /* For TLS, cert_req is set to 2, so a cert chain * of nothing is sent, but no verify packet is sent */ /* XXX: For now, we do not support client * authentication in ECDH cipher suites with * ECDH (rather than ECDSA) certificates. * We need to skip the certificate verify * message when client's ECDH public key is sent * inside the client certificate. */ if (s->s3->tmp.cert_req == 1) { s->state=SSL3_ST_CW_CERT_VRFY_A; } else { s->state=SSL3_ST_CW_CHANGE_A; s->s3->change_cipher_spec=0; } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { s->state=SSL3_ST_CW_CHANGE_A; s->s3->change_cipher_spec=0; } s->init_num=0; break; case SSL3_ST_CW_CERT_VRFY_A: case SSL3_ST_CW_CERT_VRFY_B: ret=ssl3_send_client_verify(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_CHANGE_A; s->init_num=0; s->s3->change_cipher_spec=0; break; case SSL3_ST_CW_CHANGE_A: case SSL3_ST_CW_CHANGE_B: ret=ssl3_send_change_cipher_spec(s, SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B); if (ret <= 0) goto end; #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_CW_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_CW_NEXT_PROTO_A; else s->state=SSL3_ST_CW_FINISHED_A; #endif s->init_num=0; s->session->cipher=s->s3->tmp.new_cipher; #ifdef OPENSSL_NO_COMP s->session->compress_meth=0; #else if (s->s3->tmp.new_compression == NULL) s->session->compress_meth=0; else s->session->compress_meth= s->s3->tmp.new_compression->id; #endif if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) { ret= -1; goto end; } break; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) case SSL3_ST_CW_NEXT_PROTO_A: case SSL3_ST_CW_NEXT_PROTO_B: ret=ssl3_send_next_proto(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_FINISHED_A; break; #endif case SSL3_ST_CW_FINISHED_A: case SSL3_ST_CW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B, s->method->ssl3_enc->client_finished_label, s->method->ssl3_enc->client_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_CW_FLUSH; /* clear flags */ s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER; if (s->hit) { s->s3->tmp.next_state=SSL_ST_OK; if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) { s->state=SSL_ST_OK; s->s3->flags|=SSL3_FLAGS_POP_BUFFER; s->s3->delay_buf_pop_ret=0; } } else { #ifndef OPENSSL_NO_TLSEXT /* Allow NewSessionTicket if ticket expected */ if (s->tlsext_ticket_expected) s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A; else #endif s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A; } s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_CR_SESSION_TICKET_A: case SSL3_ST_CR_SESSION_TICKET_B: ret=ssl3_get_new_session_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_FINISHED_A; s->init_num=0; break; case SSL3_ST_CR_CERT_STATUS_A: case SSL3_ST_CR_CERT_STATUS_B: ret=ssl3_get_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_CR_FINISHED_A: case SSL3_ST_CR_FINISHED_B: ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A, SSL3_ST_CR_FINISHED_B); if (ret <= 0) goto end; if (s->hit) s->state=SSL3_ST_CW_CHANGE_A; else s->state=SSL_ST_OK; s->init_num=0; break; case SSL3_ST_CW_FLUSH: s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); if (s->init_buf != NULL) { BUF_MEM_free(s->init_buf); s->init_buf=NULL; } /* If we are not 'joining' the last two packets, * remove the buffering now */ if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER)) ssl_free_wbio_buffer(s); /* else do it later in ssl3_write */ s->init_num=0; s->renegotiate=0; s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_CLIENT); if (s->hit) s->ctx->stats.sess_hit++; ret=1; /* s->server=0; */ s->handshake_func=ssl3_connect; s->ctx->stats.sess_connect_good++; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); goto end; /* break; */ default: SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } /* did we do anything */ if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_CONNECT_LOOP,1); s->state=new_state; } } skip=0; } Commit Message: CWE ID: CWE-310 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ParseJSONDictionary(const std::string& json, DictionaryValue** dict, std::string* error) { int error_code = 0; Value* params = base::JSONReader::ReadAndReturnError(json, true, &error_code, error); if (error_code != 0) { VLOG(1) << "Could not parse JSON object, " << *error; if (params) delete params; return false; } if (!params || params->GetType() != Value::TYPE_DICTIONARY) { *error = "Data passed in URL must be of type dictionary."; VLOG(1) << "Invalid type to parse"; if (params) delete params; return false; } *dict = static_cast<DictionaryValue*>(params); return true; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: void AutomationProviderBookmarkModelObserver::ReplyAndDelete(bool success) { if (automation_provider_) { if (use_json_interface_) { AutomationJSONReply(automation_provider_, reply_message_.release()).SendSuccess(NULL); } else { AutomationMsg_WaitForBookmarkModelToLoad::WriteReplyParams( reply_message_.get(), success); automation_provider_->Send(reply_message_.release()); } } delete this; } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CGaiaCredentialBase::TellOmahaDidRun() { #if defined(GOOGLE_CHROME_BUILD) base::win::RegKey key; LONG sts = key.Create(HKEY_CURRENT_USER, kRegUpdaterClientStateAppPath, KEY_SET_VALUE | KEY_WOW64_32KEY); if (sts != ERROR_SUCCESS) { LOGFN(INFO) << "Unable to open omaha key sts=" << sts; } else { sts = key.WriteValue(L"dr", L"1"); if (sts != ERROR_SUCCESS) LOGFN(INFO) << "Unable to write omaha dr value sts=" << sts; } #endif // defined(GOOGLE_CHROME_BUILD) } Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled. Unless the registry key "mdm_aca" is explicitly set to 1, always fail sign in of consumer accounts when mdm enrollment is enabled. Consumer accounts are defined as accounts with gmail.com or googlemail.com domain. Bug: 944049 Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903 Commit-Queue: Tien Mai <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#646278} CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cJSON *cJSON_GetArrayItem( cJSON *array, int item ) { cJSON *c = array->child; while ( c && item > 0 ) { --item; c = c->next; } return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void TabStripGtk::OnMap(GtkWidget* widget) { ReStack(); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadMIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define BZipMaxExtent(x) ((x)+((x)/100)+600) #define LZMAMaxExtent(x) ((x)+((x)/3)+128) #define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11) #if defined(MAGICKCORE_BZLIB_DELEGATE) bz_stream bzip_info; #endif char id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; double version; GeometryInfo geometry_info; Image *image; IndexPacket index; int c; LinkedListInfo *profiles; #if defined(MAGICKCORE_LZMA_DELEGATE) lzma_stream initialize_lzma = LZMA_STREAM_INIT, lzma_info; lzma_allocator allocator; #endif MagickBooleanType status; MagickStatusType flags; PixelPacket pixel; QuantumFormatType quantum_format; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length, packet_size; ssize_t count; unsigned char *compress_pixels, *pixels; size_t colors; ssize_t y; #if defined(MAGICKCORE_ZLIB_DELEGATE) z_stream zip_info; #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header; header terminates one character beyond a ':'. */ c=ReadBlobByte(image); if (c == EOF) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); version=0.0; (void) version; do { /* Decode image header; header terminates one character beyond a ':'. */ length=MaxTextExtent; options=AcquireString((char *) NULL); quantum_format=UndefinedQuantumFormat; profiles=(LinkedListInfo *) NULL; colors=0; image->depth=8UL; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF)) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"gravity") == 0) { ssize_t gravity; gravity=ParseCommandOption(MagickGravityOptions,MagickFalse, options); if (gravity < 0) break; image->gravity=(GravityType) gravity; break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { StringInfo *profile; if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } if ((LocaleCompare(keyword,"quantum-format") == 0) || (LocaleCompare(keyword,"quantum:format") == 0)) { ssize_t format; format=ParseCommandOption(MagickQuantumFormatOptions, MagickFalse,options); if (format < 0) break; quantum_format=(QuantumFormatType) format; break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y= image->chromaticity.red_primary.x; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions, MagickFalse,options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'v': case 'V': { if (LocaleCompare(keyword,"version") == 0) { version=StringToDouble(options,(char **) NULL); break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"ImageMagick") != 0) || (image->storage_class == UndefinedClass) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { register unsigned char *p; p=GetStringInfoDatum(profile); count=ReadBlob(image,GetStringInfoLength(profile),p); (void) count; } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ status=AcquireImageColormap(image,colors != 0 ? colors : 256); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*image->depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); p=colormap; switch (image->depth) { default: ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate image pixels. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (quantum_format != UndefinedQuantumFormat) { status=SetQuantumFormat(image,quantum_info,quantum_format); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } packet_size=(size_t) (quantum_info->depth/8); if (image->storage_class == DirectClass) packet_size=(size_t) (3*quantum_info->depth/8); if (IsGrayColorspace(image->colorspace) != MagickFalse) packet_size=quantum_info->depth/8; if (image->matte != MagickFalse) packet_size+=quantum_info->depth/8; if (image->colorspace == CMYKColorspace) packet_size+=quantum_info->depth/8; if (image->compression == RLECompression) packet_size++; length=image->columns; length=MagickMax(MagickMax(BZipMaxExtent(packet_size*image->columns), LZMAMaxExtent(packet_size*image->columns)),ZipMaxExtent(packet_size* image->columns)); compress_pixels=(unsigned char *) AcquireQuantumMemory(length, sizeof(*compress_pixels)); if (compress_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read image pixels. */ quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->matte != MagickFalse) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->matte != MagickFalse) quantum_type=IndexAlphaQuantum; } status=MagickTrue; (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); #if defined(MAGICKCORE_BZLIB_DELEGATE) (void) ResetMagickMemory(&bzip_info,0,sizeof(bzip_info)); #endif #if defined(MAGICKCORE_LZMA_DELEGATE) (void) ResetMagickMemory(&allocator,0,sizeof(allocator)); #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) (void) ResetMagickMemory(&zip_info,0,sizeof(zip_info)); #endif switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { int code; bzip_info.bzalloc=AcquireBZIPMemory; bzip_info.bzfree=RelinquishBZIPMemory; bzip_info.opaque=(void *) NULL; code=BZ2_bzDecompressInit(&bzip_info,(int) image_info->verbose, MagickFalse); if (code != BZ_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { int code; allocator.alloc=AcquireLZMAMemory; allocator.free=RelinquishLZMAMemory; lzma_info=initialize_lzma; lzma_info.allocator=(&allocator); (void) ResetMagickMemory(&allocator,0,sizeof(allocator)); allocator.alloc=AcquireLZMAMemory; allocator.free=RelinquishLZMAMemory; lzma_info=initialize_lzma; lzma_info.allocator=(&allocator); code=lzma_auto_decoder(&lzma_info,-1,0); if (code != LZMA_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { int code; zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque=(voidpf) NULL; code=inflateInit(&zip_info); if (code != Z_OK) status=MagickFalse; break; } #endif case RLECompression: { pixel.opacity=(Quantum) TransparentOpacity; index=(IndexPacket) 0; break; } default: break; } pixels=GetQuantumPixels(quantum_info); index=(IndexPacket) 0; length=0; for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { bzip_info.next_out=(char *) pixels; bzip_info.avail_out=(unsigned int) (packet_size*image->columns); do { if (bzip_info.avail_in == 0) { bzip_info.next_in=(char *) compress_pixels; length=(size_t) BZipMaxExtent(packet_size*image->columns); if (version != 0.0) length=(size_t) ReadBlobMSBLong(image); bzip_info.avail_in=(unsigned int) ReadBlob(image,length, (unsigned char *) bzip_info.next_in); } if (BZ2_bzDecompress(&bzip_info) == BZ_STREAM_END) break; } while (bzip_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { lzma_info.next_out=pixels; lzma_info.avail_out=packet_size*image->columns; do { int code; if (lzma_info.avail_in == 0) { lzma_info.next_in=compress_pixels; length=(size_t) ReadBlobMSBLong(image); lzma_info.avail_in=(unsigned int) ReadBlob(image,length, (unsigned char *) lzma_info.next_in); } code=lzma_code(&lzma_info,LZMA_RUN); if (code < 0) { status=MagickFalse; break; } if (code == LZMA_STREAM_END) break; } while (lzma_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { zip_info.next_out=pixels; zip_info.avail_out=(uInt) (packet_size*image->columns); do { if (zip_info.avail_in == 0) { zip_info.next_in=compress_pixels; length=(size_t) ZipMaxExtent(packet_size*image->columns); if (version != 0.0) length=(size_t) ReadBlobMSBLong(image); zip_info.avail_in=(unsigned int) ReadBlob(image,length, zip_info.next_in); } if (inflate(&zip_info,Z_SYNC_FLUSH) == Z_STREAM_END) break; } while (zip_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif case RLECompression: { for (x=0; x < (ssize_t) image->columns; x++) { if (length == 0) { count=ReadBlob(image,packet_size,pixels); PushRunlengthPacket(image,pixels,&length,&pixel,&index); } length--; if ((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,index); SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); SetPixelOpacity(q,pixel.opacity); q++; } break; } default: { count=ReadBlob(image,packet_size*image->columns,pixels); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } SetQuantumImageType(image,quantum_type); switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { int code; if (version == 0.0) { MagickOffsetType offset; offset=SeekBlob(image,-((MagickOffsetType) bzip_info.avail_in), SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } code=BZ2_bzDecompressEnd(&bzip_info); if (code != BZ_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { int code; code=lzma_code(&lzma_info,LZMA_FINISH); if ((code != LZMA_STREAM_END) && (code != LZMA_OK)) status=MagickFalse; lzma_end(&lzma_info); break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { int code; if (version == 0.0) { MagickOffsetType offset; offset=SeekBlob(image,-((MagickOffsetType) zip_info.avail_in), SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } code=inflateEnd(&zip_info); if (code != LZMA_OK) status=MagickFalse; break; } #endif default: break; } quantum_info=DestroyQuantumInfo(quantum_info); compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels); if (((y != (ssize_t) image->rows)) || (status == MagickFalse)) { image=DestroyImageList(image); return((Image *) NULL); } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Initialized(mojo::ScopedSharedBufferHandle shared_buffer, mojo::ScopedHandle socket_handle) { ASSERT_TRUE(shared_buffer.is_valid()); ASSERT_TRUE(socket_handle.is_valid()); base::PlatformFile fd; mojo::UnwrapPlatformFile(std::move(socket_handle), &fd); socket_ = std::make_unique<base::CancelableSyncSocket>(fd); EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle); size_t memory_length; base::SharedMemoryHandle shmem_handle; bool read_only; EXPECT_EQ( mojo::UnwrapSharedMemoryHandle(std::move(shared_buffer), &shmem_handle, &memory_length, &read_only), MOJO_RESULT_OK); EXPECT_FALSE(read_only); buffer_ = std::make_unique<base::SharedMemory>(shmem_handle, read_only); GotNotification(); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 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: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 1 Example 2: Code: void Document::ActiveChainNodeDetached(Element& element) { if (element == active_element_) active_element_ = SkipDisplayNoneAncestors(&element); } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: png_get_mmx_bitdepth_threshold (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ return (png_ptr? 0: 0); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg) { struct xc2028_data *priv = fe->tuner_priv; struct xc2028_ctrl *p = priv_cfg; int rc = 0; tuner_dbg("%s called\n", __func__); mutex_lock(&priv->lock); /* * Copy the config data. * For the firmware name, keep a local copy of the string, * in order to avoid troubles during device release. */ kfree(priv->ctrl.fname); memcpy(&priv->ctrl, p, sizeof(priv->ctrl)); if (p->fname) { priv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL); if (priv->ctrl.fname == NULL) rc = -ENOMEM; } /* * If firmware name changed, frees firmware. As free_firmware will * reset the status to NO_FIRMWARE, this forces a new request_firmware */ if (!firmware_name[0] && p->fname && priv->fname && strcmp(p->fname, priv->fname)) free_firmware(priv); if (priv->ctrl.max_len < 9) priv->ctrl.max_len = 13; if (priv->state == XC2028_NO_FIRMWARE) { if (!firmware_name[0]) priv->fname = priv->ctrl.fname; else priv->fname = firmware_name; rc = request_firmware_nowait(THIS_MODULE, 1, priv->fname, priv->i2c_props.adap->dev.parent, GFP_KERNEL, fe, load_firmware_cb); if (rc < 0) { tuner_err("Failed to request firmware %s\n", priv->fname); priv->state = XC2028_NODEV; } else priv->state = XC2028_WAITING_FIRMWARE; } mutex_unlock(&priv->lock); return rc; } Commit Message: [media] xc2028: avoid use after free If struct xc2028_config is passed without a firmware name, the following trouble may happen: [11009.907205] xc2028 5-0061: type set to XCeive xc2028/xc3028 tuner [11009.907491] ================================================================== [11009.907750] BUG: KASAN: use-after-free in strcmp+0x96/0xb0 at addr ffff8803bd78ab40 [11009.907992] Read of size 1 by task modprobe/28992 [11009.907994] ============================================================================= [11009.907997] BUG kmalloc-16 (Tainted: G W ): kasan: bad access detected [11009.907999] ----------------------------------------------------------------------------- [11009.908008] INFO: Allocated in xhci_urb_enqueue+0x214/0x14c0 [xhci_hcd] age=0 cpu=3 pid=28992 [11009.908012] ___slab_alloc+0x581/0x5b0 [11009.908014] __slab_alloc+0x51/0x90 [11009.908017] __kmalloc+0x27b/0x350 [11009.908022] xhci_urb_enqueue+0x214/0x14c0 [xhci_hcd] [11009.908026] usb_hcd_submit_urb+0x1e8/0x1c60 [11009.908029] usb_submit_urb+0xb0e/0x1200 [11009.908032] usb_serial_generic_write_start+0xb6/0x4c0 [11009.908035] usb_serial_generic_write+0x92/0xc0 [11009.908039] usb_console_write+0x38a/0x560 [11009.908045] call_console_drivers.constprop.14+0x1ee/0x2c0 [11009.908051] console_unlock+0x40d/0x900 [11009.908056] vprintk_emit+0x4b4/0x830 [11009.908061] vprintk_default+0x1f/0x30 [11009.908064] printk+0x99/0xb5 [11009.908067] kasan_report_error+0x10a/0x550 [11009.908070] __asan_report_load1_noabort+0x43/0x50 [11009.908074] INFO: Freed in xc2028_set_config+0x90/0x630 [tuner_xc2028] age=1 cpu=3 pid=28992 [11009.908077] __slab_free+0x2ec/0x460 [11009.908080] kfree+0x266/0x280 [11009.908083] xc2028_set_config+0x90/0x630 [tuner_xc2028] [11009.908086] xc2028_attach+0x310/0x8a0 [tuner_xc2028] [11009.908090] em28xx_attach_xc3028.constprop.7+0x1f9/0x30d [em28xx_dvb] [11009.908094] em28xx_dvb_init.part.3+0x8e4/0x5cf4 [em28xx_dvb] [11009.908098] em28xx_dvb_init+0x81/0x8a [em28xx_dvb] [11009.908101] em28xx_register_extension+0xd9/0x190 [em28xx] [11009.908105] em28xx_dvb_register+0x10/0x1000 [em28xx_dvb] [11009.908108] do_one_initcall+0x141/0x300 [11009.908111] do_init_module+0x1d0/0x5ad [11009.908114] load_module+0x6666/0x9ba0 [11009.908117] SyS_finit_module+0x108/0x130 [11009.908120] entry_SYSCALL_64_fastpath+0x16/0x76 [11009.908123] INFO: Slab 0xffffea000ef5e280 objects=25 used=25 fp=0x (null) flags=0x2ffff8000004080 [11009.908126] INFO: Object 0xffff8803bd78ab40 @offset=2880 fp=0x0000000000000001 [11009.908130] Bytes b4 ffff8803bd78ab30: 01 00 00 00 2a 07 00 00 9d 28 00 00 01 00 00 00 ....*....(...... [11009.908133] Object ffff8803bd78ab40: 01 00 00 00 00 00 00 00 b0 1d c3 6a 00 88 ff ff ...........j.... [11009.908137] CPU: 3 PID: 28992 Comm: modprobe Tainted: G B W 4.5.0-rc1+ #43 [11009.908140] Hardware name: /NUC5i7RYB, BIOS RYBDWi35.86A.0350.2015.0812.1722 08/12/2015 [11009.908142] ffff8803bd78a000 ffff8802c273f1b8 ffffffff81932007 ffff8803c6407a80 [11009.908148] ffff8802c273f1e8 ffffffff81556759 ffff8803c6407a80 ffffea000ef5e280 [11009.908153] ffff8803bd78ab40 dffffc0000000000 ffff8802c273f210 ffffffff8155ccb4 [11009.908158] Call Trace: [11009.908162] [<ffffffff81932007>] dump_stack+0x4b/0x64 [11009.908165] [<ffffffff81556759>] print_trailer+0xf9/0x150 [11009.908168] [<ffffffff8155ccb4>] object_err+0x34/0x40 [11009.908171] [<ffffffff8155f260>] kasan_report_error+0x230/0x550 [11009.908175] [<ffffffff81237d71>] ? trace_hardirqs_off_caller+0x21/0x290 [11009.908179] [<ffffffff8155e926>] ? kasan_unpoison_shadow+0x36/0x50 [11009.908182] [<ffffffff8155f5c3>] __asan_report_load1_noabort+0x43/0x50 [11009.908185] [<ffffffff8155ea00>] ? __asan_register_globals+0x50/0xa0 [11009.908189] [<ffffffff8194cea6>] ? strcmp+0x96/0xb0 [11009.908192] [<ffffffff8194cea6>] strcmp+0x96/0xb0 [11009.908196] [<ffffffffa13ba4ac>] xc2028_set_config+0x15c/0x630 [tuner_xc2028] [11009.908200] [<ffffffffa13bac90>] xc2028_attach+0x310/0x8a0 [tuner_xc2028] [11009.908203] [<ffffffff8155ea78>] ? memset+0x28/0x30 [11009.908206] [<ffffffffa13ba980>] ? xc2028_set_config+0x630/0x630 [tuner_xc2028] [11009.908211] [<ffffffffa157a59a>] em28xx_attach_xc3028.constprop.7+0x1f9/0x30d [em28xx_dvb] [11009.908215] [<ffffffffa157aa2a>] ? em28xx_dvb_init.part.3+0x37c/0x5cf4 [em28xx_dvb] [11009.908219] [<ffffffffa157a3a1>] ? hauppauge_hvr930c_init+0x487/0x487 [em28xx_dvb] [11009.908222] [<ffffffffa01795ac>] ? lgdt330x_attach+0x1cc/0x370 [lgdt330x] [11009.908226] [<ffffffffa01793e0>] ? i2c_read_demod_bytes.isra.2+0x210/0x210 [lgdt330x] [11009.908230] [<ffffffff812e87d0>] ? ref_module.part.15+0x10/0x10 [11009.908233] [<ffffffff812e56e0>] ? module_assert_mutex_or_preempt+0x80/0x80 [11009.908238] [<ffffffffa157af92>] em28xx_dvb_init.part.3+0x8e4/0x5cf4 [em28xx_dvb] [11009.908242] [<ffffffffa157a6ae>] ? em28xx_attach_xc3028.constprop.7+0x30d/0x30d [em28xx_dvb] [11009.908245] [<ffffffff8195222d>] ? string+0x14d/0x1f0 [11009.908249] [<ffffffff8195381f>] ? symbol_string+0xff/0x1a0 [11009.908253] [<ffffffff81953720>] ? uuid_string+0x6f0/0x6f0 [11009.908257] [<ffffffff811a775e>] ? __kernel_text_address+0x7e/0xa0 [11009.908260] [<ffffffff8104b02f>] ? print_context_stack+0x7f/0xf0 [11009.908264] [<ffffffff812e9846>] ? __module_address+0xb6/0x360 [11009.908268] [<ffffffff8137fdc9>] ? is_ftrace_trampoline+0x99/0xe0 [11009.908271] [<ffffffff811a775e>] ? __kernel_text_address+0x7e/0xa0 [11009.908275] [<ffffffff81240a70>] ? debug_check_no_locks_freed+0x290/0x290 [11009.908278] [<ffffffff8104a24b>] ? dump_trace+0x11b/0x300 [11009.908282] [<ffffffffa13e8143>] ? em28xx_register_extension+0x23/0x190 [em28xx] [11009.908285] [<ffffffff81237d71>] ? trace_hardirqs_off_caller+0x21/0x290 [11009.908289] [<ffffffff8123ff56>] ? trace_hardirqs_on_caller+0x16/0x590 [11009.908292] [<ffffffff812404dd>] ? trace_hardirqs_on+0xd/0x10 [11009.908296] [<ffffffffa13e8143>] ? em28xx_register_extension+0x23/0x190 [em28xx] [11009.908299] [<ffffffff822dcbb0>] ? mutex_trylock+0x400/0x400 [11009.908302] [<ffffffff810021a1>] ? do_one_initcall+0x131/0x300 [11009.908306] [<ffffffff81296dc7>] ? call_rcu_sched+0x17/0x20 [11009.908309] [<ffffffff8159e708>] ? put_object+0x48/0x70 [11009.908314] [<ffffffffa1579f11>] em28xx_dvb_init+0x81/0x8a [em28xx_dvb] [11009.908317] [<ffffffffa13e81f9>] em28xx_register_extension+0xd9/0x190 [em28xx] [11009.908320] [<ffffffffa0150000>] ? 0xffffffffa0150000 [11009.908324] [<ffffffffa0150010>] em28xx_dvb_register+0x10/0x1000 [em28xx_dvb] [11009.908327] [<ffffffff810021b1>] do_one_initcall+0x141/0x300 [11009.908330] [<ffffffff81002070>] ? try_to_run_init_process+0x40/0x40 [11009.908333] [<ffffffff8123ff56>] ? trace_hardirqs_on_caller+0x16/0x590 [11009.908337] [<ffffffff8155e926>] ? kasan_unpoison_shadow+0x36/0x50 [11009.908340] [<ffffffff8155e926>] ? kasan_unpoison_shadow+0x36/0x50 [11009.908343] [<ffffffff8155e926>] ? kasan_unpoison_shadow+0x36/0x50 [11009.908346] [<ffffffff8155ea37>] ? __asan_register_globals+0x87/0xa0 [11009.908350] [<ffffffff8144da7b>] do_init_module+0x1d0/0x5ad [11009.908353] [<ffffffff812f2626>] load_module+0x6666/0x9ba0 [11009.908356] [<ffffffff812e9c90>] ? symbol_put_addr+0x50/0x50 [11009.908361] [<ffffffffa1580037>] ? em28xx_dvb_init.part.3+0x5989/0x5cf4 [em28xx_dvb] [11009.908366] [<ffffffff812ebfc0>] ? module_frob_arch_sections+0x20/0x20 [11009.908369] [<ffffffff815bc940>] ? open_exec+0x50/0x50 [11009.908374] [<ffffffff811671bb>] ? ns_capable+0x5b/0xd0 [11009.908377] [<ffffffff812f5e58>] SyS_finit_module+0x108/0x130 [11009.908379] [<ffffffff812f5d50>] ? SyS_init_module+0x1f0/0x1f0 [11009.908383] [<ffffffff81004044>] ? lockdep_sys_exit_thunk+0x12/0x14 [11009.908394] [<ffffffff822e6936>] entry_SYSCALL_64_fastpath+0x16/0x76 [11009.908396] Memory state around the buggy address: [11009.908398] ffff8803bd78aa00: 00 00 fc fc fc fc fc fc fc fc fc fc fc fc fc fc [11009.908401] ffff8803bd78aa80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [11009.908403] >ffff8803bd78ab00: fc fc fc fc fc fc fc fc 00 00 fc fc fc fc fc fc [11009.908405] ^ [11009.908407] ffff8803bd78ab80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [11009.908409] ffff8803bd78ac00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [11009.908411] ================================================================== In order to avoid it, let's set the cached value of the firmware name to NULL after freeing it. While here, return an error if the memory allocation fails. Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: static int regulator_mode_constrain(struct regulator_dev *rdev, int *mode) { switch (*mode) { case REGULATOR_MODE_FAST: case REGULATOR_MODE_NORMAL: case REGULATOR_MODE_IDLE: case REGULATOR_MODE_STANDBY: break; default: rdev_err(rdev, "invalid mode %x specified\n", *mode); return -EINVAL; } if (!rdev->constraints) { rdev_err(rdev, "no constraints\n"); return -ENODEV; } if (!(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_MODE)) { rdev_err(rdev, "operation not allowed\n"); return -EPERM; } /* The modes are bitmasks, the most power hungry modes having * the lowest values. If the requested mode isn't supported * try higher modes. */ while (*mode) { if (rdev->constraints->valid_modes_mask & *mode) return 0; *mode /= 2; } return -EINVAL; } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <[email protected]> Signed-off-by: Mark Brown <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __net_exit sctp_net_exit(struct net *net) { /* Free the local address list */ sctp_free_addr_wq(net); sctp_free_local_addr_list(net); /* Free the control endpoint. */ inet_ctl_sock_destroy(net->sctp.ctl_sock); sctp_dbg_objcnt_exit(net); sctp_proc_exit(net); cleanup_sctp_mibs(net); sctp_sysctl_net_unregister(net); } Commit Message: sctp: fix race on protocol/netns initialization Consider sctp module is unloaded and is being requested because an user is creating a sctp socket. During initialization, sctp will add the new protocol type and then initialize pernet subsys: status = sctp_v4_protosw_init(); if (status) goto err_protosw_init; status = sctp_v6_protosw_init(); if (status) goto err_v6_protosw_init; status = register_pernet_subsys(&sctp_net_ops); The problem is that after those calls to sctp_v{4,6}_protosw_init(), it is possible for userspace to create SCTP sockets like if the module is already fully loaded. If that happens, one of the possible effects is that we will have readers for net->sctp.local_addr_list list earlier than expected and sctp_net_init() does not take precautions while dealing with that list, leading to a potential panic but not limited to that, as sctp_sock_init() will copy a bunch of blank/partially initialized values from net->sctp. The race happens like this: CPU 0 | CPU 1 socket() | __sock_create | socket() inet_create | __sock_create list_for_each_entry_rcu( | answer, &inetsw[sock->type], | list) { | inet_create /* no hits */ | if (unlikely(err)) { | ... | request_module() | /* socket creation is blocked | * the module is fully loaded | */ | sctp_init | sctp_v4_protosw_init | inet_register_protosw | list_add_rcu(&p->list, | last_perm); | | list_for_each_entry_rcu( | answer, &inetsw[sock->type], sctp_v6_protosw_init | list) { | /* hit, so assumes protocol | * is already loaded | */ | /* socket creation continues | * before netns is initialized | */ register_pernet_subsys | Simply inverting the initialization order between register_pernet_subsys() and sctp_v4_protosw_init() is not possible because register_pernet_subsys() will create a control sctp socket, so the protocol must be already visible by then. Deferring the socket creation to a work-queue is not good specially because we loose the ability to handle its errors. So, as suggested by Vlad, the fix is to split netns initialization in two moments: defaults and control socket, so that the defaults are already loaded by when we register the protocol, while control socket initialization is kept at the same moment it is today. Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace") Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FragmentPaintPropertyTreeBuilder::UpdateEffect() { DCHECK(properties_); const ComputedStyle& style = object_.StyleRef(); if (NeedsPaintPropertyUpdate()) { const auto* output_clip = object_.IsSVGChild() ? context_.current.clip : nullptr; if (NeedsEffect(object_)) { base::Optional<IntRect> mask_clip = CSSMaskPainter::MaskBoundingBox( object_, context_.current.paint_offset); bool has_clip_path = style.ClipPath() && fragment_data_.ClipPathBoundingBox(); bool has_spv1_composited_clip_path = has_clip_path && object_.HasLayer() && ToLayoutBoxModelObject(object_).Layer()->GetCompositedLayerMapping(); bool has_mask_based_clip_path = has_clip_path && !fragment_data_.ClipPathPath(); base::Optional<IntRect> clip_path_clip; if (has_spv1_composited_clip_path || has_mask_based_clip_path) { clip_path_clip = fragment_data_.ClipPathBoundingBox(); } if ((mask_clip || clip_path_clip) && RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { IntRect combined_clip = mask_clip ? *mask_clip : *clip_path_clip; if (mask_clip && clip_path_clip) combined_clip.Intersect(*clip_path_clip); OnUpdateClip(properties_->UpdateMaskClip( context_.current.clip, ClipPaintPropertyNode::State{context_.current.transform, FloatRoundedRect(combined_clip)})); output_clip = properties_->MaskClip(); } else { OnClearClip(properties_->ClearMaskClip()); } EffectPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; state.output_clip = output_clip; state.opacity = style.Opacity(); if (object_.IsBlendingAllowed()) { state.blend_mode = WebCoreCompositeToSkiaComposite( kCompositeSourceOver, style.GetBlendMode()); } if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { if (CompositingReasonFinder::RequiresCompositingForOpacityAnimation( style)) { state.direct_compositing_reasons = CompositingReason::kActiveOpacityAnimation; } state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kPrimary); } OnUpdate( properties_->UpdateEffect(context_.current_effect, std::move(state))); if (mask_clip || has_spv1_composited_clip_path) { EffectPaintPropertyNode::State mask_state; mask_state.local_transform_space = context_.current.transform; mask_state.output_clip = output_clip; mask_state.color_filter = CSSMaskPainter::MaskColorFilter(object_); mask_state.blend_mode = SkBlendMode::kDstIn; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { mask_state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kEffectMask); } OnUpdate(properties_->UpdateMask(properties_->Effect(), std::move(mask_state))); } else { OnClear(properties_->ClearMask()); } if (has_mask_based_clip_path) { const EffectPaintPropertyNode* parent = has_spv1_composited_clip_path ? properties_->Mask() : properties_->Effect(); EffectPaintPropertyNode::State clip_path_state; clip_path_state.local_transform_space = context_.current.transform; clip_path_state.output_clip = output_clip; clip_path_state.blend_mode = SkBlendMode::kDstIn; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { clip_path_state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kEffectClipPath); } OnUpdate( properties_->UpdateClipPath(parent, std::move(clip_path_state))); } else { OnClear(properties_->ClearClipPath()); } } else { OnClear(properties_->ClearEffect()); OnClear(properties_->ClearMask()); OnClear(properties_->ClearClipPath()); OnClearClip(properties_->ClearMaskClip()); } } if (properties_->Effect()) { context_.current_effect = properties_->Effect(); if (properties_->MaskClip()) { context_.current.clip = context_.absolute_position.clip = context_.fixed_position.clip = properties_->MaskClip(); } } } 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 <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > 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 <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # 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 <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID: Target: 1 Example 2: Code: apply_keysalt_policy(kadm5_server_handle_t handle, const char *policy, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, int *new_n_kstp, krb5_key_salt_tuple **new_kstp) { kadm5_ret_t ret; kadm5_policy_ent_rec polent; krb5_boolean have_polent; int ak_n_ks_tuple = 0; int new_n_ks_tuple = 0; krb5_key_salt_tuple *ak_ks_tuple = NULL; krb5_key_salt_tuple *new_ks_tuple = NULL; krb5_key_salt_tuple *subset; int i, m; if (new_n_kstp != NULL) { *new_n_kstp = 0; *new_kstp = NULL; } memset(&polent, 0, sizeof(polent)); ret = get_policy(handle, policy, &polent, &have_polent); if (ret) goto cleanup; if (polent.allowed_keysalts == NULL) { /* Requested keysalts allowed or default to supported_enctypes. */ if (n_ks_tuple == 0) { /* Default to supported_enctypes. */ n_ks_tuple = handle->params.num_keysalts; ks_tuple = handle->params.keysalts; } /* Dup the requested or defaulted keysalt tuples. */ new_ks_tuple = malloc(n_ks_tuple * sizeof(*new_ks_tuple)); if (new_ks_tuple == NULL) { ret = ENOMEM; goto cleanup; } memcpy(new_ks_tuple, ks_tuple, n_ks_tuple * sizeof(*new_ks_tuple)); new_n_ks_tuple = n_ks_tuple; ret = 0; goto cleanup; } ret = krb5_string_to_keysalts(polent.allowed_keysalts, ",", /* Tuple separators */ NULL, /* Key/salt separators */ 0, /* No duplicates */ &ak_ks_tuple, &ak_n_ks_tuple); /* * Malformed policy? Shouldn't happen, but it's remotely possible * someday, so we don't assert, just bail. */ if (ret) goto cleanup; /* Check that the requested ks_tuples are within policy, if we have one. */ for (i = 0; i < n_ks_tuple; i++) { if (!ks_tuple_present(ak_n_ks_tuple, ak_ks_tuple, &ks_tuple[i])) { ret = KADM5_BAD_KEYSALTS; goto cleanup; } } /* Have policy but no ks_tuple input? Output the policy. */ if (n_ks_tuple == 0) { new_n_ks_tuple = ak_n_ks_tuple; new_ks_tuple = ak_ks_tuple; ak_ks_tuple = NULL; goto cleanup; } /* * Now filter the policy ks tuples by the requested ones so as to * preserve in the requested sub-set the relative ordering from the * policy. We could optimize this (if (n_ks_tuple == ak_n_ks_tuple) * then skip this), but we don't bother. */ subset = calloc(n_ks_tuple, sizeof(*subset)); if (subset == NULL) { ret = ENOMEM; goto cleanup; } for (m = 0, i = 0; i < ak_n_ks_tuple && m < n_ks_tuple; i++) { if (ks_tuple_present(n_ks_tuple, ks_tuple, &ak_ks_tuple[i])) subset[m++] = ak_ks_tuple[i]; } new_ks_tuple = subset; new_n_ks_tuple = m; ret = 0; cleanup: if (have_polent) kadm5_free_policy_ent(handle->lhandle, &polent); free(ak_ks_tuple); if (new_n_kstp != NULL) { *new_n_kstp = new_n_ks_tuple; *new_kstp = new_ks_tuple; } else { free(new_ks_tuple); } return ret; } Commit Message: Return only new keys in randkey [CVE-2014-5351] In kadmind's randkey operation, if a client specifies the keepold flag, do not include the preserved old keys in the response. CVE-2014-5351: An authenticated remote attacker can retrieve the current keys for a service principal when generating a new set of keys for that principal. The attacker needs to be authenticated as a user who has the elevated privilege for randomizing the keys of other principals. Normally, when a Kerberos administrator randomizes the keys of a service principal, kadmind returns only the new keys. This prevents an administrator who lacks legitimate privileged access to a service from forging tickets to authenticate to that service. If the "keepold" flag to the kadmin randkey RPC operation is true, kadmind retains the old keys in the KDC database as intended, but also unexpectedly returns the old keys to the client, which exposes the service to ticket forgery attacks from the administrator. A mitigating factor is that legitimate clients of the affected service will start failing to authenticate to the service once they begin to receive service tickets encrypted in the new keys. The affected service will be unable to decrypt the newly issued tickets, possibly alerting the legitimate administrator of the affected service. CVSSv2: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C [[email protected]: CVE description and CVSS score] ticket: 8018 (new) target_version: 1.13 tags: pullup CWE ID: CWE-255 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg) { unsigned char *buffer; unsigned int *dest; int x, y; ImageStream *imgStr; Guchar *pix; int i; double *ctm; QMatrix matrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); if (maskColors) { for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); for (x = 0; x < width; x++) { for (i = 0; i < colorMap->getNumPixelComps(); ++i) { if (pix[i] < maskColors[2*i] * 255|| pix[i] > maskColors[2*i+1] * 255) { *dest = *dest | 0xff000000; break; } } pix += colorMap->getNumPixelComps(); dest++; } } m_image = new QImage(buffer, width, height, QImage::Format_ARGB32); } else { for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } m_image = new QImage(buffer, width, height, QImage::Format_RGB32); } if (m_image == NULL || m_image->isNull()) { qDebug() << "Null image"; delete imgStr; return; } ctm = state->getCTM(); matrix.setMatrix(ctm[0] / width, ctm[1] / width, -ctm[2] / height, -ctm[3] / height, ctm[2] + ctm[4], ctm[3] + ctm[5]); m_painter->setMatrix(matrix, true); m_painter->drawImage( QPoint(0,0), *m_image ); delete m_image; m_image = 0; free (buffer); delete imgStr; } Commit Message: CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CheckClientDownloadRequest::UploadBinary( DownloadCheckResult result, DownloadCheckResultReason reason) { saved_result_ = result; saved_reason_ = reason; bool upload_for_dlp = ShouldUploadForDlpScan(); bool upload_for_malware = ShouldUploadForMalwareScan(reason); auto request = std::make_unique<DownloadItemRequest>( item_, /*read_immediately=*/true, base::BindOnce(&CheckClientDownloadRequest::OnDeepScanningComplete, weakptr_factory_.GetWeakPtr())); Profile* profile = Profile::FromBrowserContext(GetBrowserContext()); if (upload_for_dlp) { DlpDeepScanningClientRequest dlp_request; dlp_request.set_content_source(DlpDeepScanningClientRequest::FILE_DOWNLOAD); request->set_request_dlp_scan(std::move(dlp_request)); } if (upload_for_malware) { MalwareDeepScanningClientRequest malware_request; malware_request.set_population( MalwareDeepScanningClientRequest::POPULATION_ENTERPRISE); malware_request.set_download_token( DownloadProtectionService::GetDownloadPingToken(item_)); request->set_request_malware_scan(std::move(malware_request)); } request->set_dm_token( policy::BrowserDMTokenStorage::Get()->RetrieveDMToken()); service()->UploadForDeepScanning(profile, std::move(request)); } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20 Target: 1 Example 2: Code: RenderViewImpl::RenderViewImpl(RenderViewImplParams* params) : RenderWidget(WebKit::WebPopupTypeNone, params->screen_info, params->swapped_out), webkit_preferences_(params->webkit_prefs), send_content_state_immediately_(false), enabled_bindings_(0), send_preferred_size_changes_(false), auto_resize_mode_(false), is_loading_(false), navigation_gesture_(NavigationGestureUnknown), opened_by_user_gesture_(true), opener_suppressed_(false), page_id_(-1), last_page_id_sent_to_browser_(-1), next_page_id_(params->next_page_id), history_list_offset_(-1), history_list_length_(0), target_url_status_(TARGET_NONE), selection_text_offset_(0), selection_range_(ui::Range::InvalidRange()), cached_is_main_frame_pinned_to_left_(false), cached_is_main_frame_pinned_to_right_(false), cached_has_main_frame_horizontal_scrollbar_(false), cached_has_main_frame_vertical_scrollbar_(false), ALLOW_THIS_IN_INITIALIZER_LIST(cookie_jar_(this)), notification_provider_(NULL), geolocation_dispatcher_(NULL), input_tag_speech_dispatcher_(NULL), speech_recognition_dispatcher_(NULL), device_orientation_dispatcher_(NULL), media_stream_dispatcher_(NULL), browser_plugin_manager_(NULL), media_stream_impl_(NULL), devtools_agent_(NULL), accessibility_mode_(AccessibilityModeOff), renderer_accessibility_(NULL), java_bridge_dispatcher_(NULL), mouse_lock_dispatcher_(NULL), favicon_helper_(NULL), #if defined(OS_ANDROID) body_background_color_(SK_ColorWHITE), update_frame_info_scheduled_(false), expected_content_intent_id_(0), media_player_proxy_(NULL), synchronous_find_active_match_ordinal_(-1), enumeration_completion_id_(0), ALLOW_THIS_IN_INITIALIZER_LIST( load_progress_tracker_(new LoadProgressTracker(this))), #endif session_storage_namespace_id_(params->session_storage_namespace_id), decrement_shared_popup_at_destruction_(false), handling_select_range_(false), next_snapshot_id_(0), #if defined(OS_WIN) focused_plugin_id_(-1), #endif updating_frame_tree_(false), pending_frame_tree_update_(false), target_process_id_(0), target_routing_id_(0) { } Commit Message: Let the browser handle external navigations from DevTools. BUG=180555 Review URL: https://chromiumcodereview.appspot.com/12531004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@186793 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __free_domain_allocs(struct s_data *d, enum s_alloc what, const struct cpumask *cpu_map) { switch (what) { case sa_sched_groups: free_sched_groups(cpu_map, d->tmpmask); /* fall through */ d->sched_group_nodes = NULL; case sa_rootdomain: free_rootdomain(d->rd); /* fall through */ case sa_tmpmask: free_cpumask_var(d->tmpmask); /* fall through */ case sa_send_covered: free_cpumask_var(d->send_covered); /* fall through */ case sa_this_book_map: free_cpumask_var(d->this_book_map); /* fall through */ case sa_this_core_map: free_cpumask_var(d->this_core_map); /* fall through */ case sa_this_sibling_map: free_cpumask_var(d->this_sibling_map); /* fall through */ case sa_nodemask: free_cpumask_var(d->nodemask); /* fall through */ case sa_sched_group_nodes: #ifdef CONFIG_NUMA kfree(d->sched_group_nodes); /* fall through */ case sa_notcovered: free_cpumask_var(d->notcovered); /* fall through */ case sa_covered: free_cpumask_var(d->covered); /* fall through */ case sa_domainspan: free_cpumask_var(d->domainspan); /* fall through */ #endif case sa_none: break; } } Commit Message: Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <[email protected]> Reported-by: Bjoern B. Brandenburg <[email protected]> Tested-by: Yong Zhang <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: [email protected] LKML-Reference: <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void ptrace_link(struct task_struct *child, struct task_struct *new_parent) { rcu_read_lock(); __ptrace_link(child, new_parent, __task_cred(new_parent)); rcu_read_unlock(); } Commit Message: ptrace: Fix ->ptracer_cred handling for PTRACE_TRACEME Fix two issues: When called for PTRACE_TRACEME, ptrace_link() would obtain an RCU reference to the parent's objective credentials, then give that pointer to get_cred(). However, the object lifetime rules for things like struct cred do not permit unconditionally turning an RCU reference into a stable reference. PTRACE_TRACEME records the parent's credentials as if the parent was acting as the subject, but that's not the case. If a malicious unprivileged child uses PTRACE_TRACEME and the parent is privileged, and at a later point, the parent process becomes attacker-controlled (because it drops privileges and calls execve()), the attacker ends up with control over two processes with a privileged ptrace relationship, which can be abused to ptrace a suid binary and obtain root privileges. Fix both of these by always recording the credentials of the process that is requesting the creation of the ptrace relationship: current_cred() can't change under us, and current is the proper subject for access control. This change is theoretically userspace-visible, but I am not aware of any code that it will actually break. Fixes: 64b875f7ac8a ("ptrace: Capture the ptracer's creds not PT_PTRACE_CAP") Signed-off-by: Jann Horn <[email protected]> Acked-by: Oleg Nesterov <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void registerMockedHttpURLLoad(const std::string& fileName) { URLTestHelpers::registerMockedURLFromBaseURL(WebString::fromUTF8(m_baseURL.c_str()), WebString::fromUTF8(fileName.c_str())); } Commit Message: Call didAccessInitialDocument when javascript: URLs are used. BUG=265221 TEST=See bug for repro. Review URL: https://chromiumcodereview.appspot.com/22572004 git-svn-id: svn://svn.chromium.org/blink/trunk@155790 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int propagate_mnt(struct mount *dest_mnt, struct dentry *dest_dentry, struct mount *source_mnt, struct list_head *tree_list) { struct mount *m, *child; int ret = 0; struct mount *prev_dest_mnt = dest_mnt; struct mount *prev_src_mnt = source_mnt; LIST_HEAD(tmp_list); LIST_HEAD(umount_list); for (m = propagation_next(dest_mnt, dest_mnt); m; m = propagation_next(m, dest_mnt)) { int type; struct mount *source; if (IS_MNT_NEW(m)) continue; source = get_source(m, prev_dest_mnt, prev_src_mnt, &type); child = copy_tree(source, source->mnt.mnt_root, type); if (IS_ERR(child)) { ret = PTR_ERR(child); list_splice(tree_list, tmp_list.prev); goto out; } if (is_subdir(dest_dentry, m->mnt.mnt_root)) { mnt_set_mountpoint(m, dest_dentry, child); list_add_tail(&child->mnt_hash, tree_list); } else { /* * This can happen if the parent mount was bind mounted * on some subdirectory of a shared/slave mount. */ list_add_tail(&child->mnt_hash, &tmp_list); } prev_dest_mnt = m; prev_src_mnt = child; } out: br_write_lock(&vfsmount_lock); while (!list_empty(&tmp_list)) { child = list_first_entry(&tmp_list, struct mount, mnt_hash); umount_tree(child, 0, &umount_list); } br_write_unlock(&vfsmount_lock); release_mounts(&umount_list); return ret; } Commit Message: vfs: Carefully propogate mounts across user namespaces As a matter of policy MNT_READONLY should not be changable if the original mounter had more privileges than creator of the mount namespace. Add the flag CL_UNPRIVILEGED to note when we are copying a mount from a mount namespace that requires more privileges to a mount namespace that requires fewer privileges. When the CL_UNPRIVILEGED flag is set cause clone_mnt to set MNT_NO_REMOUNT if any of the mnt flags that should never be changed are set. This protects both mount propagation and the initial creation of a less privileged mount namespace. Cc: [email protected] Acked-by: Serge Hallyn <[email protected]> Reported-by: Andy Lutomirski <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget) { WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container); WebKitWebViewBasePrivate* priv = webView->priv; if (WEBKIT_IS_WEB_VIEW_BASE(widget) && WebInspectorProxy::isInspectorPage(WEBKIT_WEB_VIEW_BASE(widget)->priv->pageProxy.get())) { ASSERT(!priv->inspectorView); priv->inspectorView = widget; priv->inspectorViewHeight = gMinimumAttachedInspectorHeight; } else { GtkAllocation childAllocation; gtk_widget_get_allocation(widget, &childAllocation); priv->children.set(widget, childAllocation); } gtk_widget_set_parent(widget, GTK_WIDGET(container)); } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: static void init_all_refs_cb(struct all_refs_cb *cb, struct rev_info *revs, unsigned flags) { cb->all_revs = revs; cb->all_flags = flags; } 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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SaveTestFileSystem() { GDataRootDirectoryProto root; GDataDirectoryProto* root_dir = root.mutable_gdata_directory(); GDataEntryProto* file_base = root_dir->mutable_gdata_entry(); PlatformFileInfoProto* platform_info = file_base->mutable_file_info(); file_base->set_title("drive"); platform_info->set_is_directory(true); GDataFileProto* file = root_dir->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File1"); platform_info->set_is_directory(false); platform_info->set_size(1048576); GDataDirectoryProto* dir1 = root_dir->add_child_directories(); file_base = dir1->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("Dir1"); platform_info->set_is_directory(true); file = dir1->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File2"); platform_info->set_is_directory(false); platform_info->set_size(555); GDataDirectoryProto* dir2 = dir1->add_child_directories(); file_base = dir2->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("SubDir2"); platform_info->set_is_directory(true); file = dir2->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File3"); platform_info->set_is_directory(false); platform_info->set_size(12345); std::string serialized_proto; ASSERT_TRUE(root.SerializeToString(&serialized_proto)); ASSERT_TRUE(!serialized_proto.empty()); FilePath cache_dir_path = profile_->GetPath().Append( FILE_PATH_LITERAL("GCache/v1/meta/")); ASSERT_TRUE(file_util::CreateDirectory(cache_dir_path)); const int file_size = static_cast<int>(serialized_proto.length()); ASSERT_EQ(file_util::WriteFile(cache_dir_path.Append("file_system.pb"), serialized_proto.data(), file_size), file_size); } Commit Message: gdata: Define the resource ID for the root directory Per the spec, the resource ID for the root directory is defined as "folder:root". Add the resource ID to the root directory in our file system representation so we can look up the root directory by the resource ID. BUG=127697 TEST=add unit tests Review URL: https://chromiumcodereview.appspot.com/10332253 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FaviconSource::StartDataRequest(const std::string& path, bool is_incognito, int request_id) { FaviconService* favicon_service = profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); if (favicon_service) { FaviconService::Handle handle; if (path.empty()) { SendDefaultResponse(request_id); return; } if (path.size() > 8 && path.substr(0, 8) == "iconurl/") { handle = favicon_service->GetFavicon( GURL(path.substr(8)), history::FAVICON, &cancelable_consumer_, NewCallback(this, &FaviconSource::OnFaviconDataAvailable)); } else { handle = favicon_service->GetFaviconForURL( GURL(path), icon_types_, &cancelable_consumer_, NewCallback(this, &FaviconSource::OnFaviconDataAvailable)); } cancelable_consumer_.SetClientData(favicon_service, handle, request_id); } else { SendResponse(request_id, NULL); } } Commit Message: ntp4: show larger favicons in most visited page extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe). BUG=none TEST=manual Review URL: http://codereview.chromium.org/7300017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void unix_state_double_lock(struct sock *sk1, struct sock *sk2) { if (unlikely(sk1 == sk2) || !sk2) { unix_state_lock(sk1); return; } if (sk1 < sk2) { unix_state_lock(sk1); unix_state_lock_nested(sk2); } else { unix_state_lock(sk2); unix_state_lock_nested(sk1); } } Commit Message: af_netlink: force credentials passing [CVE-2012-3520] Pablo Neira Ayuso discovered that avahi and potentially NetworkManager accept spoofed Netlink messages because of a kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data to the receiver if the sender did not provide such data, instead of not including any such data at all or including the correct data from the peer (as it is the case with AF_UNIX). This bug was introduced in commit 16e572626961 (af_unix: dont send SCM_CREDENTIALS by default) This patch forces passing credentials for netlink, as before the regression. Another fix would be to not add SCM_CREDENTIALS in netlink messages if not provided by the sender, but it might break some programs. With help from Florian Weimer & Petr Matousek This issue is designated as CVE-2012-3520 Signed-off-by: Eric Dumazet <[email protected]> Cc: Petr Matousek <[email protected]> Cc: Florian Weimer <[email protected]> Cc: Pablo Neira Ayuso <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-287 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int wait_for_discard(void *word) { schedule(); return 0; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: parse_file (FILE* input_file, char* directory, char *body_filename, char *body_pref, int flags) { uint32 d; uint16 key; Attr *attr = NULL; File *file = NULL; int rtf_size = 0, html_size = 0; MessageBody body; memset (&body, '\0', sizeof (MessageBody)); /* store the program options in our file global variables */ g_flags = flags; /* check that this is in fact a TNEF file */ d = geti32(input_file); if (d != TNEF_SIGNATURE) { fprintf (stdout, "Seems not to be a TNEF file\n"); return 1; } /* Get the key */ key = geti16(input_file); debug_print ("TNEF Key: %hx\n", key); /* The rest of the file is a series of 'messages' and 'attachments' */ while ( data_left( input_file ) ) { attr = read_object( input_file ); if ( attr == NULL ) break; /* This signals the beginning of a file */ if (attr->name == attATTACHRENDDATA) { if (file) { file_write (file, directory); file_free (file); } else { file = CHECKED_XCALLOC (File, 1); } } /* Add the data to our lists. */ switch (attr->lvl_type) { case LVL_MESSAGE: if (attr->name == attBODY) { body.text_body = get_text_data (attr); } else if (attr->name == attMAPIPROPS) { MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf); if (mapi_attrs) { int i; for (i = 0; mapi_attrs[i]; i++) { MAPI_Attr *a = mapi_attrs[i]; if (a->name == MAPI_BODY_HTML) { body.html_bodies = get_html_data (a); html_size = a->num_values; } else if (a->name == MAPI_RTF_COMPRESSED) { body.rtf_bodies = get_rtf_data (a); rtf_size = a->num_values; } } /* cannot save attributes to file, since they * are not attachment attributes */ /* file_add_mapi_attrs (file, mapi_attrs); */ mapi_attr_free_list (mapi_attrs); XFREE (mapi_attrs); } } break; case LVL_ATTACHMENT: file_add_attr (file, attr); break; default: fprintf (stderr, "Invalid lvl type on attribute: %d\n", attr->lvl_type); return 1; break; } attr_free (attr); XFREE (attr); } if (file) { file_write (file, directory); file_free (file); XFREE (file); } /* Write the message body */ if (flags & SAVEBODY) { int i = 0; int all_flag = 0; if (strcmp (body_pref, "all") == 0) { all_flag = 1; body_pref = "rht"; } for (; i < 3; i++) { File **files = get_body_files (body_filename, body_pref[i], &body); if (files) { int j = 0; for (; files[j]; j++) { file_write(files[j], directory); file_free (files[j]); XFREE(files[j]); } XFREE(files); if (!all_flag) break; } } } if (body.text_body) { free_bodies(body.text_body, 1); XFREE(body.text_body); } if (rtf_size > 0) { free_bodies(body.rtf_bodies, rtf_size); XFREE(body.rtf_bodies); } if (html_size > 0) { free_bodies(body.html_bodies, html_size); XFREE(body.html_bodies); } return 0; } Commit Message: Check types to avoid invalid reads/writes. CWE ID: CWE-125 Target: 1 Example 2: Code: bool ChromeContentRendererClient::HasErrorPage(int http_status_code, std::string* error_domain) { if (!LocalizedError::HasStrings(LocalizedError::kHttpErrorDomain, http_status_code)) { return false; } *error_domain = LocalizedError::kHttpErrorDomain; return true; } Commit Message: Do not require DevTools extension resources to be white-listed in manifest. Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is (a) trusted and (b) picky on the frames it loads. This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check. BUG=none TEST=DevToolsExtensionTest.* Review URL: https://chromiumcodereview.appspot.com/9663076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: error::Error GLES2DecoderImpl::HandleTexImage2DImmediate( uint32 immediate_data_size, const gles2::TexImage2DImmediate& c) { GLenum target = static_cast<GLenum>(c.target); GLint level = static_cast<GLint>(c.level); GLint internal_format = static_cast<GLint>(c.internalformat); GLsizei width = static_cast<GLsizei>(c.width); GLsizei height = static_cast<GLsizei>(c.height); GLint border = static_cast<GLint>(c.border); GLenum format = static_cast<GLenum>(c.format); GLenum type = static_cast<GLenum>(c.type); uint32 size; if (!GLES2Util::ComputeImageDataSize( width, height, format, type, unpack_alignment_, &size)) { return error::kOutOfBounds; } const void* pixels = GetImmediateDataAs<const void*>( c, size, immediate_data_size); if (!pixels) { return error::kOutOfBounds; } DoTexImage2D( target, level, internal_format, width, height, border, format, type, pixels, size); return error::kNoError; } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 [email protected] Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static __u8 *sp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 107 && rdesc[104] == 0x26 && rdesc[105] == 0x80 && rdesc[106] == 0x03) { hid_info(hdev, "fixing up Sunplus Wireless Desktop report descriptor\n"); rdesc[105] = rdesc[110] = 0x03; rdesc[106] = rdesc[111] = 0x21; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int apparmor_path_unlink(const struct path *dir, struct dentry *dentry) { return common_perm_rm(OP_UNLINK, dir, dentry, AA_MAY_DELETE); } Commit Message: apparmor: fix oops, validate buffer size in apparmor_setprocattr() When proc_pid_attr_write() was changed to use memdup_user apparmor's (interface violating) assumption that the setprocattr buffer was always a single page was violated. The size test is not strictly speaking needed as proc_pid_attr_write() will reject anything larger, but for the sake of robustness we can keep it in. SMACK and SELinux look safe to me, but somebody else should probably have a look just in case. Based on original patch from Vegard Nossum <[email protected]> modified for the case that apparmor provides null termination. Fixes: bb646cdb12e75d82258c2f2e7746d5952d3e321a Reported-by: Vegard Nossum <[email protected]> Cc: Al Viro <[email protected]> Cc: John Johansen <[email protected]> Cc: Paul Moore <[email protected]> Cc: Stephen Smalley <[email protected]> Cc: Eric Paris <[email protected]> Cc: Casey Schaufler <[email protected]> Cc: [email protected] Signed-off-by: John Johansen <[email protected]> Reviewed-by: Tyler Hicks <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long Segment::DoParseNext(const Cluster*& pResult, long long& pos, long& len) { 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 off_next = 0; long long cluster_size = -1; for (;;) { if ((total >= 0) && (pos >= total)) return 1; // EOF if ((segment_stop >= 0) && (pos >= segment_stop)) return 1; // EOF 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; // absolute const long long idoff = pos - m_start; // relative const long long id = ReadUInt(m_pReader, idpos, len); // absolute if (id < 0) // error return static_cast<long>(id); if (id == 0) // weird return -1; // generic error pos += len; // consume ID 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 length of size of element if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if ((segment_stop >= 0) && (size != unknown_size) && ((pos + size) > segment_stop)) { return E_FILE_FORMAT_INVALID; } if (id == 0x0C53BB6B) { // Cues ID if (size == unknown_size) return E_FILE_FORMAT_INVALID; const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; const long long element_start = idpos; const long long element_size = element_stop - element_start; if (m_pCues == NULL) { m_pCues = new Cues(this, pos, size, element_start, element_size); assert(m_pCues); // TODO } pos += size; // consume payload assert((segment_stop < 0) || (pos <= segment_stop)); continue; } if (id != 0x0F43B675) { // not a Cluster ID if (size == unknown_size) return E_FILE_FORMAT_INVALID; pos += size; // consume payload assert((segment_stop < 0) || (pos <= segment_stop)); continue; } #if 0 // this is commented-out to support incremental cluster parsing len = static_cast<long>(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; #endif off_next = idoff; if (size != unknown_size) cluster_size = size; break; } assert(off_next > 0); // have cluster Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); const Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); assert(pos >= 0); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else { pResult = pNext; return 0; // success } } assert(i == j); long long pos_; long len_; status = Cluster::HasBlockEntries(this, off_next, pos_, len_); if (status < 0) { // error or underflow pos = pos_; len = len_; return status; } if (status > 0) { // means "found at least one block entry" Cluster* const pNext = Cluster::Create(this, -1, // preloaded off_next); assert(pNext); const ptrdiff_t idx_next = i - m_clusters; // insertion position PreloadCluster(pNext, idx_next); assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); pResult = pNext; return 0; // success } if (cluster_size < 0) { // unknown size const long long payload_pos = pos; // absolute pos of cluster payload for (;;) { // determine cluster size if ((total >= 0) && (pos >= total)) break; if ((segment_stop >= 0) && (pos >= segment_stop)) break; // no more clusters 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) // Cluster ID break; if (id == 0x0C53BB6B) // Cues ID break; 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 cluster_size = pos - payload_pos; assert(cluster_size >= 0); // TODO: handle cluster_size = 0 pos = payload_pos; // reset and re-parse original cluster } pos += cluster_size; // consume payload assert((segment_stop < 0) || (pos <= segment_stop)); return 2; // try to find a cluster that follows next } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AppControllerImpl::LaunchHomeUrl(const std::string& suffix, LaunchHomeUrlCallback callback) { if (url_prefix_.empty()) { std::move(callback).Run(false, "No URL prefix."); return; } GURL url(url_prefix_ + suffix); if (!url.is_valid()) { std::move(callback).Run(false, "Invalid URL."); return; } arc::mojom::AppInstance* app_instance = arc::ArcServiceManager::Get() ? ARC_GET_INSTANCE_FOR_METHOD( arc::ArcServiceManager::Get()->arc_bridge_service()->app(), LaunchIntent) : nullptr; if (!app_instance) { std::move(callback).Run(false, "ARC bridge not available."); return; } app_instance->LaunchIntent(url.spec(), display::kDefaultDisplayId); std::move(callback).Run(true, base::nullopt); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416 Target: 1 Example 2: Code: static void flush_change(H264Context *h) { int i, j; h->outputed_poc = h->next_outputed_poc = INT_MIN; h->prev_interlaced_frame = 1; idr(h); h->prev_frame_num = -1; if (h->cur_pic_ptr) { h->cur_pic_ptr->reference = 0; for (j=i=0; h->delayed_pic[i]; i++) if (h->delayed_pic[i] != h->cur_pic_ptr) h->delayed_pic[j++] = h->delayed_pic[i]; h->delayed_pic[j] = NULL; } h->first_field = 0; memset(h->ref_list[0], 0, sizeof(h->ref_list[0])); memset(h->ref_list[1], 0, sizeof(h->ref_list[1])); memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0])); memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1])); ff_h264_reset_sei(h); h->recovery_frame= -1; h->sync= 0; h->list_count = 0; h->current_slice = 0; } Commit Message: avcodec/h264: do not trust last_pic_droppable when marking pictures as done This simplifies the code and fixes a deadlock Fixes Ticket2927 Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: AvailableSpaceQueryTask( QuotaManager* manager, const AvailableSpaceCallback& callback) : QuotaThreadTask(manager, manager->db_thread_), profile_path_(manager->profile_path_), space_(-1), get_disk_space_fn_(manager->get_disk_space_fn_), callback_(callback) { DCHECK(get_disk_space_fn_); } Commit Message: Wipe out QuotaThreadTask. This is a one of a series of refactoring patches for QuotaManager. http://codereview.chromium.org/10872054/ http://codereview.chromium.org/10917060/ BUG=139270 Review URL: https://chromiumcodereview.appspot.com/10919070 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154987 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> overloadedMethod7Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.overloadedMethod7"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(RefPtr<DOMStringList>, arrayArg, v8ValueToWebCoreDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(arrayArg); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: NO_INLINE bool jspeFunctionDefinitionInternal(JsVar *funcVar, bool expressionOnly) { if (expressionOnly) { if (funcVar) funcVar->flags = (funcVar->flags & ~JSV_VARTYPEMASK) | JSV_FUNCTION_RETURN; } else { JSP_MATCH('{'); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_STR && !strcmp(jslGetTokenValueAsString(lex), "compiled")) { jsWarn("Function marked with \"compiled\" uploaded in source form"); } #endif /* If the function starts with return, treat it specially - * we don't want to store the 'return' part of it */ if (funcVar && lex->tk==LEX_R_RETURN) { funcVar->flags = (funcVar->flags & ~JSV_VARTYPEMASK) | JSV_FUNCTION_RETURN; JSP_ASSERT_MATCH(LEX_R_RETURN); } } JsVarInt lineNumber = 0; if (funcVar && lex->lineNumberOffset) { lineNumber = (JsVarInt)jslGetLineNumber(lex) + (JsVarInt)lex->lineNumberOffset - 1; } JslCharPos funcBegin = jslCharPosClone(&lex->tokenStart); int lastTokenEnd = -1; if (!expressionOnly) { int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; lastTokenEnd = (int)jsvStringIteratorGetIndex(&lex->it)-1; JSP_ASSERT_MATCH(lex->tk); } } else { JsExecFlags oldExec = execInfo.execute; execInfo.execute = EXEC_NO; jsvUnLock(jspeAssignmentExpression()); execInfo.execute = oldExec; lastTokenEnd = (int)jsvStringIteratorGetIndex(&lex->tokenStart.it)-1; } if (funcVar && lastTokenEnd>0) { JsVar *funcCodeVar; if (jsvIsNativeString(lex->sourceVar)) { /* If we're parsing from a Native String (eg. E.memoryArea, E.setBootCode) then use another Native String to load function code straight from flash */ int s = (int)jsvStringIteratorGetIndex(&funcBegin.it) - 1; funcCodeVar = jsvNewNativeString(lex->sourceVar->varData.nativeStr.ptr + s, (unsigned int)(lastTokenEnd - s)); } else { if (jsfGetFlag(JSF_PRETOKENISE)) { funcCodeVar = jslNewTokenisedStringFromLexer(&funcBegin, (size_t)lastTokenEnd); } else { funcCodeVar = jslNewStringFromLexer(&funcBegin, (size_t)lastTokenEnd); } } jsvUnLock2(jsvAddNamedChild(funcVar, funcCodeVar, JSPARSE_FUNCTION_CODE_NAME), funcCodeVar); JsVar *funcScopeVar = jspeiGetScopesAsVar(); if (funcScopeVar) { jsvUnLock2(jsvAddNamedChild(funcVar, funcScopeVar, JSPARSE_FUNCTION_SCOPE_NAME), funcScopeVar); } if (lineNumber) { JsVar *funcLineNumber = jsvNewFromInteger(lineNumber); if (funcLineNumber) { jsvUnLock2(jsvAddNamedChild(funcVar, funcLineNumber, JSPARSE_FUNCTION_LINENUMBER_NAME), funcLineNumber); } } } jslCharPosFree(&funcBegin); if (!expressionOnly) JSP_MATCH('}'); Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data) { u64 supported; u32 *lowp, *highp; switch (msr_index) { case MSR_IA32_VMX_TRUE_PINBASED_CTLS: lowp = &vmx->nested.msrs.pinbased_ctls_low; highp = &vmx->nested.msrs.pinbased_ctls_high; break; case MSR_IA32_VMX_TRUE_PROCBASED_CTLS: lowp = &vmx->nested.msrs.procbased_ctls_low; highp = &vmx->nested.msrs.procbased_ctls_high; break; case MSR_IA32_VMX_TRUE_EXIT_CTLS: lowp = &vmx->nested.msrs.exit_ctls_low; highp = &vmx->nested.msrs.exit_ctls_high; break; case MSR_IA32_VMX_TRUE_ENTRY_CTLS: lowp = &vmx->nested.msrs.entry_ctls_low; highp = &vmx->nested.msrs.entry_ctls_high; break; case MSR_IA32_VMX_PROCBASED_CTLS2: lowp = &vmx->nested.msrs.secondary_ctls_low; highp = &vmx->nested.msrs.secondary_ctls_high; break; default: BUG(); } supported = vmx_control_msr(*lowp, *highp); /* Check must-be-1 bits are still 1. */ if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0))) return -EINVAL; /* Check must-be-0 bits are still 0. */ if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32))) return -EINVAL; *lowp = data; *highp = data >> 32; return 0; } Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions VMX instructions executed inside a L1 VM will always trigger a VM exit even when executed with cpl 3. This means we must perform the privilege check in software. Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks") Cc: [email protected] Signed-off-by: Felix Wilhelm <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_ce_exception, 0, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; size_t fname_len, alias_len = 0; int arch_len, entry_len, is_data; zend_long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; zend_long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data); if (is_data) { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } ZVAL_STRINGL(&arg1, fname, fname_len); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); zval_ptr_dtor(&arg1); if (!phar_data->is_persistent) { phar_obj->archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_str_add_ptr(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive), phar_obj); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: void V8TestObject::BooleanAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_booleanAttribute_Getter"); test_object_v8_internal::BooleanAttributeAttributeGetter(info); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ptvcursor_add_invalid_check(ptvcursor_t *csr, int hf, gint len, guint64 invalid_val) { proto_item *ti; guint64 val = invalid_val; switch (len) { case 8: val = tvb_get_letoh64(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr)); break; case 4: val = tvb_get_letohl(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr)); break; case 2: val = tvb_get_letohs(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr)); break; case 1: val = tvb_get_guint8(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr)); break; default: DISSECTOR_ASSERT_NOT_REACHED(); } ti = ptvcursor_add(csr, hf, len, ENC_LITTLE_ENDIAN); if (val == invalid_val) proto_item_append_text(ti, " [invalid]"); } Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr. We now require that. Make it so. Bug: 12440 Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76 Reviewed-on: https://code.wireshark.org/review/15424 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) * 4 >= std::numeric_limits<int32>::max()) return false; // Prevent overflow of signed 32-bit ints. format_ = format; width_ = width; height_ = height; return backend_->Init(this, format, width, height, init_to_zero); } Commit Message: Security fix: integer overflow on checking image size Test is left in another CL (codereview.chromiu,.org/11274036) to avoid conflict there. Hope it's fine. BUG=160926 Review URL: https://chromiumcodereview.appspot.com/11410081 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167882 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-190 Target: 1 Example 2: Code: View* GetFocusedView() { return widget_->GetFocusManager()->GetFocusedView(); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void MojoAudioInputStream::OnStreamCreated( int stream_id, const base::SharedMemory* shared_memory, std::unique_ptr<base::CancelableSyncSocket> foreign_socket, bool initially_muted) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(stream_created_callback_); DCHECK(shared_memory); DCHECK(foreign_socket); base::SharedMemoryHandle foreign_memory_handle = shared_memory->GetReadOnlyHandle(); if (!base::SharedMemory::IsHandleValid(foreign_memory_handle)) { OnStreamError(/*not used*/ 0); return; } mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle( foreign_memory_handle, shared_memory->requested_size(), /*read_only*/ true); mojo::ScopedHandle socket_handle = mojo::WrapPlatformFile(foreign_socket->Release()); DCHECK(buffer_handle.is_valid()); DCHECK(socket_handle.is_valid()); base::ResetAndReturn(&stream_created_callback_) .Run(std::move(buffer_handle), std::move(socket_handle), initially_muted); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 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: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void tun_net_init(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: dev->netdev_ops = &tun_netdev_ops; /* Point-to-Point TUN Device */ dev->hard_header_len = 0; dev->addr_len = 0; dev->mtu = 1500; /* Zero header length */ dev->type = ARPHRD_NONE; dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST; dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; case TUN_TAP_DEV: dev->netdev_ops = &tap_netdev_ops; /* Ethernet TAP Device */ ether_setup(dev); random_ether_addr(dev->dev_addr); dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; } } 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 <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void ContainerNode::dispatchPostAttachCallbacks() { for (size_t i = 0; i < s_postAttachCallbackQueue->size(); ++i) { const CallbackInfo& info = (*s_postAttachCallbackQueue)[i]; NodeCallback callback = info.first; CallbackParameters params = info.second; callback(params.first.get(), params.second); } s_postAttachCallbackQueue->clear(); } Commit Message: https://bugs.webkit.org/show_bug.cgi?id=93587 Node::replaceChild() can create bad DOM topology with MutationEvent, Part 2 Reviewed by Kent Tamura. Source/WebCore: This is a followup of r124156. replaceChild() has yet another hidden MutationEvent trigger. This change added a guard for it. Test: fast/events/mutation-during-replace-child-2.html * dom/ContainerNode.cpp: (WebCore::ContainerNode::replaceChild): LayoutTests: * fast/events/mutation-during-replace-child-2-expected.txt: Added. * fast/events/mutation-during-replace-child-2.html: Added. git-svn-id: svn://svn.chromium.org/blink/trunk@125237 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: const Track* Tracks::GetTrackByNumber(long tn) const { if (tn < 0) return NULL; Track** i = m_trackEntries; Track** const j = m_trackEntriesEnd; while (i != j) { Track* const pTrack = *i++; if (pTrack == NULL) continue; if (tn == pTrack->GetNumber()) return pTrack; } return NULL; //not found } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadIPLImage(const ImageInfo *image_info,ExceptionInfo *exception) { /* Declare variables. */ Image *image; MagickBooleanType status; register PixelPacket *q; unsigned char magick[12], *pixels; ssize_t count; ssize_t y; size_t t_count=0; size_t length; IPLInfo ipl_info; QuantumFormatType quantum_format; QuantumInfo *quantum_info; QuantumType quantum_type; /* Open Image */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if ( image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent, GetMagickModule(), "%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read IPL image */ /* Determine endianness If we get back "iiii", we have LSB,"mmmm", MSB */ count=ReadBlob(image,4,magick); (void) count; if((LocaleNCompare((char *) magick,"iiii",4) == 0)) image->endian=LSBEndian; else{ if((LocaleNCompare((char *) magick,"mmmm",4) == 0)) image->endian=MSBEndian; else{ ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } /* Skip o'er the next 8 bytes (garbage) */ count=ReadBlob(image, 8, magick); /* Excellent, now we read the header unimpeded. */ count=ReadBlob(image,4,magick); if((LocaleNCompare((char *) magick,"data",4) != 0)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); ipl_info.size=ReadBlobLong(image); ipl_info.width=ReadBlobLong(image); ipl_info.height=ReadBlobLong(image); if((ipl_info.width == 0UL) || (ipl_info.height == 0UL)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); ipl_info.colors=ReadBlobLong(image); if(ipl_info.colors == 3){ SetImageColorspace(image,sRGBColorspace);} else { image->colorspace = GRAYColorspace; } ipl_info.z=ReadBlobLong(image); ipl_info.time=ReadBlobLong(image); ipl_info.byteType=ReadBlobLong(image); /* Initialize Quantum Info */ switch (ipl_info.byteType) { case 0: ipl_info.depth=8; quantum_format = UnsignedQuantumFormat; break; case 1: ipl_info.depth=16; quantum_format = SignedQuantumFormat; break; case 2: ipl_info.depth=16; quantum_format = UnsignedQuantumFormat; break; case 3: ipl_info.depth=32; quantum_format = SignedQuantumFormat; break; case 4: ipl_info.depth=32; quantum_format = FloatingPointQuantumFormat; break; case 5: ipl_info.depth=8; quantum_format = UnsignedQuantumFormat; break; case 6: ipl_info.depth=16; quantum_format = UnsignedQuantumFormat; break; case 10: ipl_info.depth=64; quantum_format = FloatingPointQuantumFormat; break; default: ipl_info.depth=16; quantum_format = UnsignedQuantumFormat; break; } /* Set number of scenes of image */ SetHeaderFromIPL(image, &ipl_info); /* Thats all we need if we are pinging. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } length=image->columns; quantum_type=GetQuantumType(image,exception); do { SetHeaderFromIPL(image, &ipl_info); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* printf("Length: %.20g, Memory size: %.20g\n", (double) length,(double) image->depth); */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,quantum_format); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); if(image->columns != ipl_info.width){ /* printf("Columns not set correctly! Wanted: %.20g, got: %.20g\n", (double) ipl_info.width, (double) image->columns); */ } /* Covert IPL binary to pixel packets */ if(ipl_info.colors == 1){ for(y = 0; y < (ssize_t) image->rows; y++){ (void) ReadBlob(image, length*image->depth/8, pixels); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else{ for(y = 0; y < (ssize_t) image->rows; y++){ (void) ReadBlob(image, length*image->depth/8, pixels); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } for(y = 0; y < (ssize_t) image->rows; y++){ (void) ReadBlob(image, length*image->depth/8, pixels); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } for(y = 0; y < (ssize_t) image->rows; y++){ (void) ReadBlob(image, length*image->depth/8, pixels); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } SetQuantumImageType(image,quantum_type); t_count++; quantum_info = DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if(t_count < ipl_info.z * ipl_info.time){ /* Proceed to next image. */ AcquireNextImage(image_info, image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (t_count < ipl_info.z*ipl_info.time); CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: status_t Parcel::readCharVector(std::vector<char16_t>* val) const { return readTypedVector(val, &Parcel::readChar); } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a (cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719) CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType debug, status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFErrorHandler error_handler, warning_handler; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) MagickSetThreadValue(tiff_exception,exception); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); image=DestroyImageList(image); return((Image *) NULL); } debug=IsEventLogging(); (void) debug; if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. */ for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: { (void) TIFFSetField(tiff,TIFFTAG_SGILOGDATAFMT,SGILOGDATAFMT_FLOAT); break; } case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJpegMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ if ((image->storage_class == PseudoClass) && (photometric == PHOTOMETRIC_PALETTE)) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; size_t number_pixels; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=columns*rows; tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels, sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) (number_pixels*sizeof(uint32)))) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } if (image->storage_class == PseudoClass) image->depth=GetImageDepth(image,exception); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); TIFFClose(tiff); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static int megasas_alloc_ctrl_mem(struct megasas_instance *instance) { instance->reply_map = kcalloc(nr_cpu_ids, sizeof(unsigned int), GFP_KERNEL); if (!instance->reply_map) return -ENOMEM; switch (instance->adapter_type) { case MFI_SERIES: if (megasas_alloc_mfi_ctrl_mem(instance)) goto fail; break; case AERO_SERIES: case VENTURA_SERIES: case THUNDERBOLT_SERIES: case INVADER_SERIES: if (megasas_alloc_fusion_context(instance)) goto fail; break; } return 0; fail: kfree(instance->reply_map); instance->reply_map = NULL; return -ENOMEM; } Commit Message: scsi: megaraid_sas: return error when create DMA pool failed when create DMA pool for cmd frames failed, we should return -ENOMEM, instead of 0. In some case in: megasas_init_adapter_fusion() -->megasas_alloc_cmds() -->megasas_create_frame_pool create DMA pool failed, --> megasas_free_cmds() [1] -->megasas_alloc_cmds_fusion() failed, then goto fail_alloc_cmds. -->megasas_free_cmds() [2] we will call megasas_free_cmds twice, [1] will kfree cmd_list, [2] will use cmd_list.it will cause a problem: Unable to handle kernel NULL pointer dereference at virtual address 00000000 pgd = ffffffc000f70000 [00000000] *pgd=0000001fbf893003, *pud=0000001fbf893003, *pmd=0000001fbf894003, *pte=006000006d000707 Internal error: Oops: 96000005 [#1] SMP Modules linked in: CPU: 18 PID: 1 Comm: swapper/0 Not tainted task: ffffffdfb9290000 ti: ffffffdfb923c000 task.ti: ffffffdfb923c000 PC is at megasas_free_cmds+0x30/0x70 LR is at megasas_free_cmds+0x24/0x70 ... Call trace: [<ffffffc0005b779c>] megasas_free_cmds+0x30/0x70 [<ffffffc0005bca74>] megasas_init_adapter_fusion+0x2f4/0x4d8 [<ffffffc0005b926c>] megasas_init_fw+0x2dc/0x760 [<ffffffc0005b9ab0>] megasas_probe_one+0x3c0/0xcd8 [<ffffffc0004a5abc>] local_pci_probe+0x4c/0xb4 [<ffffffc0004a5c40>] pci_device_probe+0x11c/0x14c [<ffffffc00053a5e4>] driver_probe_device+0x1ec/0x430 [<ffffffc00053a92c>] __driver_attach+0xa8/0xb0 [<ffffffc000538178>] bus_for_each_dev+0x74/0xc8 [<ffffffc000539e88>] driver_attach+0x28/0x34 [<ffffffc000539a18>] bus_add_driver+0x16c/0x248 [<ffffffc00053b234>] driver_register+0x6c/0x138 [<ffffffc0004a5350>] __pci_register_driver+0x5c/0x6c [<ffffffc000ce3868>] megasas_init+0xc0/0x1a8 [<ffffffc000082a58>] do_one_initcall+0xe8/0x1ec [<ffffffc000ca7be8>] kernel_init_freeable+0x1c8/0x284 [<ffffffc0008d90b8>] kernel_init+0x1c/0xe4 Signed-off-by: Jason Yan <[email protected]> Acked-by: Sumit Saxena <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + (nbytes + 1); length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); } Commit Message: CWE ID: CWE-682 Output:
1