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: gfx::Size LauncherView::GetPreferredSize() { IdealBounds ideal_bounds; CalculateIdealBounds(&ideal_bounds); if (is_horizontal_alignment()) { if (view_model_->view_size() >= 2) { return gfx::Size(view_model_->ideal_bounds(1).right() + kLeadingInset, kLauncherPreferredSize); } return gfx::Size(kLauncherPreferredSize * 2 + kLeadingInset * 2, kLauncherPreferredSize); } if (view_model_->view_size() >= 2) { return gfx::Size(kLauncherPreferredSize, view_model_->ideal_bounds(1).bottom() + kLeadingInset); } return gfx::Size(kLauncherPreferredSize, kLauncherPreferredSize * 2 + kLeadingInset * 2); } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void megasas_complete_outstanding_ioctls(struct megasas_instance *instance) { int i; struct megasas_cmd *cmd_mfi; struct megasas_cmd_fusion *cmd_fusion; struct fusion_context *fusion = instance->ctrl_context; /* Find all outstanding ioctls */ if (fusion) { for (i = 0; i < instance->max_fw_cmds; i++) { cmd_fusion = fusion->cmd_list[i]; if (cmd_fusion->sync_cmd_idx != (u32)ULONG_MAX) { cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx]; if (cmd_mfi->sync_cmd && (cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT)) { cmd_mfi->frame->hdr.cmd_status = MFI_STAT_WRONG_STATE; megasas_complete_cmd(instance, cmd_mfi, DID_OK); } } } } else { for (i = 0; i < instance->max_fw_cmds; i++) { cmd_mfi = instance->cmd_list[i]; if (cmd_mfi->sync_cmd && cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT) megasas_complete_cmd(instance, cmd_mfi, DID_OK); } } } 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: void TabSpecificContentSettings::OnContentBlocked( ContentSettingsType type, const std::string& resource_identifier) { DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION) << "Geolocation settings handled by OnGeolocationPermissionSet"; content_accessed_[type] = true; std::string identifier; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableResourceContentSettings)) { identifier = resource_identifier; } if (!identifier.empty()) AddBlockedResource(type, identifier); #if defined (OS_ANDROID) if (type == CONTENT_SETTINGS_TYPE_POPUPS) { content_blocked_[type] = false; content_blockage_indicated_to_user_[type] = false; } #endif if (!content_blocked_[type]) { content_blocked_[type] = true; content::NotificationService::current()->Notify( chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, content::Source<WebContents>(web_contents()), content::NotificationService::NoDetails()); } } Commit Message: Check the content setting type is valid. BUG=169770 Review URL: https://codereview.chromium.org/11875013 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176687 0039d316-1c4b-4281-b951-d872f2087c98 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 ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) { const char* name; size_t namelen; if (node->graft_path) { name = node->graft_path; namelen = node->graft_pathlen; } else if (node->actual_name) { name = node->actual_name; namelen = node->namelen; } else { name = node->name; namelen = node->namelen; } if (bufsize < namelen + 1) { return -1; } ssize_t pathlen = 0; if (node->parent && node->graft_path == NULL) { pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 2); if (pathlen < 0) { return -1; } buf[pathlen++] = '/'; } memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */ return pathlen + namelen; } Commit Message: Fix overflow in path building An incorrect size was causing an unsigned value to wrap, causing it to write past the end of the buffer. Bug: 28085658 Change-Id: Ie9625c729cca024d514ba2880ff97209d435a165 CWE ID: CWE-264 Target: 1 Example 2: Code: void RendererSchedulerImpl::VirtualTimePaused() { for (const auto& pair : task_runners_) { if (pair.first->queue_class() == MainThreadTaskQueue::QueueClass::kTimer) { DCHECK(!task_queue_throttler_->IsThrottled(pair.first.get())); DCHECK(!pair.first->HasActiveFence()); pair.first->InsertFence(TaskQueue::InsertFencePosition::kNow); } } for (auto& observer : main_thread_only().virtual_time_observers) { observer.OnVirtualTimePaused(virtual_time_domain_->Now() - main_thread_only().initial_virtual_time); } } Commit Message: [scheduler] Remove implicit fallthrough in switch Bail out early when a condition in the switch is fulfilled. This does not change behaviour due to RemoveTaskObserver being no-op when the task observer is not present in the list. [email protected] Bug: 177475 Change-Id: Ibc7772c79f8a8c8a1d63a997dabe1efda5d3a7bd Reviewed-on: https://chromium-review.googlesource.com/891187 Reviewed-by: Nico Weber <[email protected]> Commit-Queue: Alexander Timin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532649} 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: PlatformNotificationData ToPlatformNotificationData( const WebNotificationData& web_data) { PlatformNotificationData platform_data; platform_data.title = web_data.title; switch (web_data.direction) { case WebNotificationData::DirectionLeftToRight: platform_data.direction = PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT; break; case WebNotificationData::DirectionRightToLeft: platform_data.direction = PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT; break; case WebNotificationData::DirectionAuto: platform_data.direction = PlatformNotificationData::DIRECTION_AUTO; break; } platform_data.lang = base::UTF16ToUTF8(base::StringPiece16(web_data.lang)); platform_data.body = web_data.body; platform_data.tag = base::UTF16ToUTF8(base::StringPiece16(web_data.tag)); platform_data.icon = blink::WebStringToGURL(web_data.icon.string()); platform_data.vibration_pattern.assign(web_data.vibrate.begin(), web_data.vibrate.end()); platform_data.timestamp = base::Time::FromJsTime(web_data.timestamp); platform_data.silent = web_data.silent; platform_data.require_interaction = web_data.requireInteraction; platform_data.data.assign(web_data.data.begin(), web_data.data.end()); platform_data.actions.resize(web_data.actions.size()); for (size_t i = 0; i < web_data.actions.size(); ++i) { platform_data.actions[i].action = base::UTF16ToUTF8(base::StringPiece16(web_data.actions[i].action)); platform_data.actions[i].title = web_data.actions[i].title; } return platform_data; } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} 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: static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int ret; int copylen; ret = -EOPNOTSUPP; if (m->msg_flags&MSG_OOB) goto read_error; skb = skb_recv_datagram(sk, flags, 0 , &ret); if (!skb) goto read_error; copylen = skb->len; if (len < copylen) { m->msg_flags |= MSG_TRUNC; copylen = len; } ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen); if (ret) goto out_free; ret = (flags & MSG_TRUNC) ? skb->len : copylen; out_free: skb_free_datagram(sk, skb); caif_check_flow_release(sk); return ret; read_error: return ret; } Commit Message: caif: Fix missing msg_namelen update in caif_seqpkt_recvmsg() The current code does not fill the msg_name member in case it is set. It also does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about caif_seqpkt_recvmsg() not filling the msg_name in case it was set. Cc: Sjur Braendeland <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: SProcXvPutStill(ClientPtr client) { REQUEST(xvPutStillReq); REQUEST_SIZE_MATCH(xvPutStillReq); swaps(&stuff->length); swapl(&stuff->port); swapl(&stuff->drawable); swapl(&stuff->gc); swaps(&stuff->vid_x); swaps(&stuff->vid_y); swaps(&stuff->vid_w); swaps(&stuff->vid_h); swaps(&stuff->drw_x); swaps(&stuff->drw_y); swaps(&stuff->drw_w); swaps(&stuff->drw_h); return XvProcVector[xv_PutStill] (client); } 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: static const char *set_access_name(cmd_parms *cmd, void *dummy, const char *arg) { void *sconf = cmd->server->module_config; core_server_config *conf = ap_get_core_module_config(sconf); const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE); if (err != NULL) { return err; } conf->access_name = apr_pstrdup(cmd->pool, arg); return NULL; } Commit Message: core: Disallow Methods' registration at run time (.htaccess), they may be used only if registered at init time (httpd.conf). Calling ap_method_register() in children processes is not the right scope since it won't be shared for all requests. git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1807655 13f79535-47bb-0310-9956-ffa450edef68 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: process_db_args(krb5_context context, char **db_args, xargs_t *xargs, OPERATION optype) { int i=0; krb5_error_code st=0; char *arg=NULL, *arg_val=NULL; char **dptr=NULL; unsigned int arg_val_len=0; if (db_args) { for (i=0; db_args[i]; ++i) { arg = strtok_r(db_args[i], "=", &arg_val); if (strcmp(arg, TKTPOLICY_ARG) == 0) { dptr = &xargs->tktpolicydn; } else { if (strcmp(arg, USERDN_ARG) == 0) { if (optype == MODIFY_PRINCIPAL || xargs->dn != NULL || xargs->containerdn != NULL || xargs->linkdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->dn; } else if (strcmp(arg, CONTAINERDN_ARG) == 0) { if (optype == MODIFY_PRINCIPAL || xargs->dn != NULL || xargs->containerdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->containerdn; } else if (strcmp(arg, LINKDN_ARG) == 0) { if (xargs->dn != NULL || xargs->linkdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->linkdn; } else { st = EINVAL; k5_setmsg(context, st, _("unknown option: %s"), arg); goto cleanup; } xargs->dn_from_kbd = TRUE; if (arg_val == NULL || strlen(arg_val) == 0) { st = EINVAL; k5_setmsg(context, st, _("%s option value missing"), arg); goto cleanup; } } if (arg_val == NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option value missing"), arg); goto cleanup; } arg_val_len = strlen(arg_val) + 1; if (strcmp(arg, TKTPOLICY_ARG) == 0) { if ((st = krb5_ldap_name_to_policydn (context, arg_val, dptr)) != 0) goto cleanup; } else { *dptr = k5memdup(arg_val, arg_val_len, &st); if (*dptr == NULL) goto cleanup; } } } cleanup: return st; } Commit Message: Fix LDAP null deref on empty arg [CVE-2016-3119] In the LDAP KDB module's process_db_args(), strtok_r() may return NULL if there is an empty string in the db_args array. Check for this case and avoid dereferencing a null pointer. CVE-2016-3119: In MIT krb5 1.6 and later, an authenticated attacker with permission to modify a principal entry can cause kadmind to dereference a null pointer by supplying an empty DB argument to the modify_principal command, if kadmind is configured to use the LDAP KDB module. CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:H/RL:OF/RC:ND ticket: 8383 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: Target: 1 Example 2: Code: RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost( RenderWidgetHostImpl* receiving_widget) { if (!SiteIsolationPolicy::AreCrossProcessFramesPossible()) return receiving_widget; if (receiving_widget != GetMainFrame()->GetRenderWidgetHost()) return receiving_widget; FrameTreeNode* focused_frame = frame_tree_.GetFocusedFrame(); if (!focused_frame) return receiving_widget; RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView(); if (!view) return nullptr; return RenderWidgetHostImpl::From(view->GetRenderWidgetHost()); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} 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 crypto_report_one(struct crypto_alg *alg, struct crypto_user_alg *ualg, struct sk_buff *skb) { memcpy(&ualg->cru_name, &alg->cra_name, sizeof(ualg->cru_name)); memcpy(&ualg->cru_driver_name, &alg->cra_driver_name, sizeof(ualg->cru_driver_name)); memcpy(&ualg->cru_module_name, module_name(alg->cra_module), CRYPTO_MAX_ALG_NAME); ualg->cru_flags = alg->cra_flags; ualg->cru_refcnt = atomic_read(&alg->cra_refcnt); if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority)) goto nla_put_failure; if (alg->cra_flags & CRYPTO_ALG_LARVAL) { struct crypto_report_larval rl; snprintf(rl.type, CRYPTO_MAX_ALG_NAME, "%s", "larval"); if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL, sizeof(struct crypto_report_larval), &rl)) goto nla_put_failure; goto out; } if (alg->cra_type && alg->cra_type->report) { if (alg->cra_type->report(skb, alg)) goto nla_put_failure; goto out; } switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) { case CRYPTO_ALG_TYPE_CIPHER: if (crypto_report_cipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_COMPRESS: if (crypto_report_comp(skb, alg)) goto nla_put_failure; break; } out: 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 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: long Cluster::Parse(long long& pos, long& len) const { long status = Load(pos, len); if (status < 0) return status; assert(m_pos >= m_element_start); assert(m_timecode >= 0); const long long cluster_stop = (m_element_size < 0) ? -1 : m_element_start + m_element_size; if ((cluster_stop >= 0) && (m_pos >= cluster_stop)) return 1; //nothing else to do IMkvReader* const pReader = m_pSegment->m_pReader; long long total, avail; status = pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); pos = m_pos; for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) break; if ((total >= 0) && (pos >= total)) { if (m_element_size < 0) m_element_size = pos - m_element_start; break; } if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast<long>(id); if (id == 0) //weird return E_FILE_FORMAT_INVALID; if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster or Cues ID { if (m_element_size < 0) m_element_size = pos - m_element_start; break; } pos += len; //consume ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(size); const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; pos += len; //consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) //weird continue; const long long block_stop = pos + size; if (cluster_stop >= 0) { if (block_stop > cluster_stop) { if ((id == 0x20) || (id == 0x23)) return E_FILE_FORMAT_INVALID; pos = cluster_stop; break; } } else if ((total >= 0) && (block_stop > total)) { m_element_size = total - m_element_start; pos = total; break; } else if (block_stop > avail) { len = static_cast<long>(size); return E_BUFFER_NOT_FULL; } Cluster* const this_ = const_cast<Cluster*>(this); if (id == 0x20) //BlockGroup return this_->ParseBlockGroup(size, pos, len); if (id == 0x23) //SimpleBlock return this_->ParseSimpleBlock(size, pos, len); pos += size; //consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } assert(m_element_size > 0); m_pos = pos; assert((cluster_stop < 0) || (m_pos <= cluster_stop)); if (m_entries_count > 0) { const long idx = m_entries_count - 1; const BlockEntry* const pLast = m_entries[idx]; assert(pLast); const Block* const pBlock = pLast->GetBlock(); assert(pBlock); const long long start = pBlock->m_start; if ((total >= 0) && (start > total)) return -1; //defend against trucated stream const long long size = pBlock->m_size; const long long stop = start + size; assert((cluster_stop < 0) || (stop <= cluster_stop)); if ((total >= 0) && (stop > total)) return -1; //defend against trucated stream } return 1; //no more entries } 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 Target: 1 Example 2: Code: static void reset_packet(ASFPacket *asf_pkt) { asf_pkt->size_left = 0; asf_pkt->data_size = 0; asf_pkt->duration = 0; asf_pkt->flags = 0; asf_pkt->dts = 0; asf_pkt->duration = 0; av_packet_unref(&asf_pkt->avpkt); av_init_packet(&asf_pkt->avpkt); } Commit Message: avformat/asfdec_o: Check size_bmp more fully Fixes: integer overflow and out of array access Fixes: asfo-crash-46080c4341572a7137a162331af77f6ded45cbd7 Found-by: Paul Ch <[email protected]> Signed-off-by: Michael Niedermayer <[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 drop_privs(int nogroups) { EUID_ROOT(); gid_t gid = getgid(); if (gid == 0 || nogroups) { if (setgroups(0, NULL) < 0) errExit("setgroups"); if (arg_debug) printf("Username %s, no supplementary groups\n", cfg.username); } else { assert(cfg.username); gid_t groups[MAX_GROUPS]; int ngroups = MAX_GROUPS; int rv = getgrouplist(cfg.username, gid, groups, &ngroups); if (arg_debug && rv) { printf("Username %s, groups ", cfg.username); int i; for (i = 0; i < ngroups; i++) printf("%u, ", groups[i]); printf("\n"); } if (rv == -1) { fprintf(stderr, "Warning: cannot extract supplementary group list, dropping them\n"); if (setgroups(0, NULL) < 0) errExit("setgroups"); } else { rv = setgroups(ngroups, groups); if (rv) { fprintf(stderr, "Warning: cannot set supplementary group list, dropping them\n"); if (setgroups(0, NULL) < 0) errExit("setgroups"); } } } if (setgid(getgid()) < 0) errExit("setgid/getgid"); if (setuid(getuid()) < 0) errExit("setuid/getuid"); } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269 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 double outerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* There is a serious error in the 2 and 4 bit grayscale transform because * the gamma table value (8 bits) is simply shifted, not rounded, so the * error in 4 bit grayscale gamma is up to the value below. This is a hack * to allow pngvalid to succeed: * * TODO: fix this in libpng */ if (out_depth == 2) return .73182-.5; if (out_depth == 4) return .90644-.5; if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxout16; /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ else if (out_depth == 16) return pm->maxout8 * 257; else return pm->maxout8; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: static int msg_fetch_header(struct Context *ctx, struct ImapHeader *h, char *buf, FILE *fp) { unsigned int bytes; int rc = -1; /* default now is that string isn't FETCH response */ int parse_rc; struct ImapData *idata = ctx->data; if (buf[0] != '*') return rc; /* skip to message number */ buf = imap_next_word(buf); if (mutt_str_atoui(buf, &h->data->msn) < 0) return rc; /* find FETCH tag */ buf = imap_next_word(buf); if (mutt_str_strncasecmp("FETCH", buf, 5) != 0) return rc; rc = -2; /* we've got a FETCH response, for better or worse */ buf = strchr(buf, '('); if (!buf) return rc; buf++; /* FIXME: current implementation - call msg_parse_fetch - if it returns -2, * read header lines and call it again. Silly. */ parse_rc = msg_parse_fetch(h, buf); if (!parse_rc) return 0; if (parse_rc != -2 || !fp) return rc; if (imap_get_literal_count(buf, &bytes) == 0) { imap_read_literal(fp, idata, bytes, NULL); /* we may have other fields of the FETCH _after_ the literal * (eg Domino puts FLAGS here). Nothing wrong with that, either. * This all has to go - we should accept literals and nonliterals * interchangeably at any time. */ if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) return rc; if (msg_parse_fetch(h, idata->buf) == -1) return rc; } rc = 0; /* success */ /* subtract headers from message size - unfortunately only the subset of * headers we've requested. */ h->content_length -= bytes; return rc; } Commit Message: Don't overflow stack buffer in msg_parse_fetch 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: gsm_xsmp_client_disconnect (GsmXSMPClient *client) { if (client->priv->watch_id > 0) { g_source_remove (client->priv->watch_id); } if (client->priv->conn != NULL) { SmsCleanUp (client->priv->conn); } if (client->priv->ice_connection != NULL) { IceSetShutdownNegotiation (client->priv->ice_connection, FALSE); IceCloseConnection (client->priv->ice_connection); } if (client->priv->protocol_timeout > 0) { g_source_remove (client->priv->protocol_timeout); } } Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists We used to create the GsmXSMPClient before the XSMP connection is really accepted. This can lead to some issues, though. An example is: https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting: "What is happening is that a new client (probably metacity in your case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION phase, which causes a new GsmXSMPClient to be added to the client store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client has had a chance to establish a xsmp connection, which means that client->priv->conn will not be initialized at the point that xsmp_stop is called on the new unregistered client." The fix is to create the GsmXSMPClient object when there's a real XSMP connection. This implies moving the timeout that makes sure we don't have an empty client to the XSMP server. https://bugzilla.gnome.org/show_bug.cgi?id=598211 CWE ID: CWE-835 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 save_text_if_changed(const char *name, const char *new_value) { /* a text value can't be change if the file is not loaded */ /* returns NULL if the name is not found; otherwise nonzero */ if (!g_hash_table_lookup(g_loaded_texts, name)) return; const char *old_value = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : ""; if (!old_value) old_value = ""; if (strcmp(new_value, old_value) != 0) { struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); if (dd) dd_save_text(dd, name, new_value); dd_close(dd); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(/* don't update selected event */ 0); } } Commit Message: wizard: fix save users changes after reviewing dump dir files If the user reviewed the dump dir's files during reporting the crash, the changes was thrown away and original data was passed to the bugzilla bug report. report-gtk saves the first text view buffer and then reloads data from the reported problem directory, which causes that the changes made to those text views are thrown away. Function save_text_if_changed(), except of saving text, also reload the files from dump dir and update gui state from the dump dir. The commit moves the reloading and updating gui functions away from this function. Related to rhbz#1270235 Signed-off-by: Matej Habrnal <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: rb_update_iter_read_stamp(struct ring_buffer_iter *iter, struct ring_buffer_event *event) { u64 delta; switch (event->type_len) { case RINGBUF_TYPE_PADDING: return; case RINGBUF_TYPE_TIME_EXTEND: delta = event->array[0]; delta <<= TS_SHIFT; delta += event->time_delta; iter->read_stamp += delta; return; case RINGBUF_TYPE_TIME_STAMP: /* FIXME: not implemented */ return; case RINGBUF_TYPE_DATA: iter->read_stamp += event->time_delta; return; default: BUG(); } return; } Commit Message: ring-buffer: Prevent overflow of size in ring_buffer_resize() If the size passed to ring_buffer_resize() is greater than MAX_LONG - BUF_PAGE_SIZE then the DIV_ROUND_UP() will return zero. Here's the details: # echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb tracing_entries_write() processes this and converts kb to bytes. 18014398509481980 << 10 = 18446744073709547520 and this is passed to ring_buffer_resize() as unsigned long size. size = DIV_ROUND_UP(size, BUF_PAGE_SIZE); Where DIV_ROUND_UP(a, b) is (a + b - 1)/b BUF_PAGE_SIZE is 4080 and here 18446744073709547520 + 4080 - 1 = 18446744073709551599 where 18446744073709551599 is still smaller than 2^64 2^64 - 18446744073709551599 = 17 But now 18446744073709551599 / 4080 = 4521260802379792 and size = size * 4080 = 18446744073709551360 This is checked to make sure its still greater than 2 * 4080, which it is. Then we convert to the number of buffer pages needed. nr_page = DIV_ROUND_UP(size, BUF_PAGE_SIZE) but this time size is 18446744073709551360 and 2^64 - (18446744073709551360 + 4080 - 1) = -3823 Thus it overflows and the resulting number is less than 4080, which makes 3823 / 4080 = 0 an nr_pages is set to this. As we already checked against the minimum that nr_pages may be, this causes the logic to fail as well, and we crash the kernel. There's no reason to have the two DIV_ROUND_UP() (that's just result of historical code changes), clean up the code and fix this bug. Cc: [email protected] # 3.5+ Fixes: 83f40318dab00 ("ring-buffer: Make removal of ring buffer pages atomic") Signed-off-by: Steven Rostedt <[email protected]> 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: rpl_print(netdissect_options *ndo, const struct icmp6_hdr *hdr, const u_char *bp, u_int length) { int secured = hdr->icmp6_code & 0x80; int basecode= hdr->icmp6_code & 0x7f; if(secured) { ND_PRINT((ndo, ", (SEC) [worktodo]")); /* XXX * the next header pointer needs to move forward to * skip the secure part. */ return; } else { ND_PRINT((ndo, ", (CLR)")); } switch(basecode) { case ND_RPL_DAG_IS: ND_PRINT((ndo, "DODAG Information Solicitation")); if(ndo->ndo_vflag) { } break; case ND_RPL_DAG_IO: ND_PRINT((ndo, "DODAG Information Object")); if(ndo->ndo_vflag) { rpl_dio_print(ndo, bp, length); } break; case ND_RPL_DAO: ND_PRINT((ndo, "Destination Advertisement Object")); if(ndo->ndo_vflag) { rpl_dao_print(ndo, bp, length); } break; case ND_RPL_DAO_ACK: ND_PRINT((ndo, "Destination Advertisement Object Ack")); if(ndo->ndo_vflag) { rpl_daoack_print(ndo, bp, length); } break; default: ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code)); break; } return; #if 0 trunc: ND_PRINT((ndo," [|truncated]")); return; #endif } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. 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: status_t Camera3Device::createDefaultRequest(int templateId, CameraMetadata *request) { ATRACE_CALL(); ALOGV("%s: for template %d", __FUNCTION__, templateId); Mutex::Autolock il(mInterfaceLock); Mutex::Autolock l(mLock); switch (mStatus) { case STATUS_ERROR: CLOGE("Device has encountered a serious error"); return INVALID_OPERATION; case STATUS_UNINITIALIZED: CLOGE("Device is not initialized!"); return INVALID_OPERATION; case STATUS_UNCONFIGURED: case STATUS_CONFIGURED: case STATUS_ACTIVE: break; default: SET_ERR_L("Unexpected status: %d", mStatus); return INVALID_OPERATION; } if (!mRequestTemplateCache[templateId].isEmpty()) { *request = mRequestTemplateCache[templateId]; return OK; } const camera_metadata_t *rawRequest; ATRACE_BEGIN("camera3->construct_default_request_settings"); rawRequest = mHal3Device->ops->construct_default_request_settings( mHal3Device, templateId); ATRACE_END(); if (rawRequest == NULL) { ALOGI("%s: template %d is not supported on this camera device", __FUNCTION__, templateId); return BAD_VALUE; } *request = rawRequest; mRequestTemplateCache[templateId] = rawRequest; return OK; } Commit Message: Camera3Device: Validate template ID Validate template ID before creating a default request. Bug: 26866110 Bug: 27568958 Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d CWE ID: CWE-264 Target: 1 Example 2: Code: static void srpt_rdma_read_done(struct ib_cq *cq, struct ib_wc *wc) { struct srpt_rdma_ch *ch = cq->cq_context; struct srpt_send_ioctx *ioctx = container_of(wc->wr_cqe, struct srpt_send_ioctx, rdma_cqe); WARN_ON(ioctx->n_rdma <= 0); atomic_add(ioctx->n_rdma, &ch->sq_wr_avail); if (unlikely(wc->status != IB_WC_SUCCESS)) { pr_info("RDMA_READ for ioctx 0x%p failed with status %d\n", ioctx, wc->status); srpt_abort_cmd(ioctx); return; } if (srpt_test_and_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA, SRPT_STATE_DATA_IN)) target_execute_cmd(&ioctx->cmd); else pr_err("%s[%d]: wrong state = %d\n", __func__, __LINE__, srpt_get_cmd_state(ioctx)); } Commit Message: IB/srpt: Simplify srpt_handle_tsk_mgmt() Let the target core check task existence instead of the SRP target driver. Additionally, let the target core check the validity of the task management request instead of the ib_srpt driver. This patch fixes the following kernel crash: BUG: unable to handle kernel NULL pointer dereference at 0000000000000001 IP: [<ffffffffa0565f37>] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt] Oops: 0002 [#1] SMP Call Trace: [<ffffffffa05660ce>] srpt_process_completion+0xde/0x570 [ib_srpt] [<ffffffffa056669f>] srpt_compl_thread+0x13f/0x160 [ib_srpt] [<ffffffff8109726f>] kthread+0xcf/0xe0 [<ffffffff81613cfc>] ret_from_fork+0x7c/0xb0 Signed-off-by: Bart Van Assche <[email protected]> Fixes: 3e4f574857ee ("ib_srpt: Convert TMR path to target_submit_tmr") Tested-by: Alex Estrin <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Cc: Nicholas Bellinger <[email protected]> Cc: Sagi Grimberg <[email protected]> Cc: stable <[email protected]> Signed-off-by: Doug Ledford <[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: bool PrintCalled() const { return print_called_; } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} 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 int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top, unsigned char *buf, int idx, int width) { size_t i, j; if (top > b->top) top = b->top; /* this works because 'buf' is explicitly * zeroed */ for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) { buf[j] = ((unsigned char *)b->d)[i]; } return 1; unsigned char *buf, int idx, static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top, unsigned char *buf, int idx, int width) { size_t i, j; if (bn_wexpand(b, top) == NULL) return 0; for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) { ((unsigned char *)b->d)[i] = buf[j]; } b->top = top; if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS); return (0); } top = m->top; bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } BN_CTX_start(ctx); /* * Allocate a montgomery context if it was not supplied by the caller. If * this is not done, things will break in the montgomery part. */ if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } #ifdef RSAZ_ENABLED /* * If the size of the operands allow it, perform the optimized * RSAZ exponentiation. For further information see * crypto/bn/rsaz_exp.c and accompanying assembly modules. */ if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024) && rsaz_avx2_eligible()) { if (NULL == bn_wexpand(rr, 16)) goto err; RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d, mont->n0[0]); rr->top = 16; rr->neg = 0; bn_correct_top(rr); ret = 1; goto err; } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) { if (NULL == bn_wexpand(rr, 8)) goto err; RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d); rr->top = 8; rr->neg = 0; bn_correct_top(rr); ret = 1; goto err; } #endif /* Get the window size to use with size of p. */ window = BN_window_bits_for_ctime_exponent_size(bits); #if defined(SPARC_T4_MONT) if (window >= 5 && (top & 15) == 0 && top <= 64 && (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) == (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0])) window = 5; else #endif #if defined(OPENSSL_BN_ASM_MONT5) if (window >= 5) { window = 5; /* ~5% improvement for RSA2048 sign, and even * for RSA4096 */ if ((top & 7) == 0) powerbufLen += 2 * top * sizeof(m->d[0]); } #endif (void)0; /* * Allocate a buffer large enough to hold all of the pre-computed powers * of am, am itself and tmp. */ numPowers = 1 << window; powerbufLen += sizeof(m->d[0]) * (top * numPowers + ((2 * top) > numPowers ? (2 * top) : numPowers)); #ifdef alloca if (powerbufLen < 3072) powerbufFree = alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH); else #endif if ((powerbufFree = (unsigned char *)OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH)) == NULL) goto err; powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree); memset(powerbuf, 0, powerbufLen); #ifdef alloca if (powerbufLen < 3072) powerbufFree = NULL; #endif /* lay down tmp and am right after powers table */ tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers); am.d = tmp.d + top; tmp.top = am.top = 0; tmp.dmax = am.dmax = top; tmp.neg = am.neg = 0; tmp.flags = am.flags = BN_FLG_STATIC_DATA; /* prepare a^0 in Montgomery domain */ #if 1 /* by Shay Gueron's suggestion */ if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) { /* 2^(top*BN_BITS2) - m */ tmp.d[0] = (0 - m->d[0]) & BN_MASK2; for (i = 1; i < top; i++) tmp.d[i] = (~m->d[i]) & BN_MASK2; tmp.top = top; } else #endif if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx)) goto err; /* prepare a^1 in Montgomery domain */ if (a->neg || BN_ucmp(a, m) >= 0) { if (!BN_mod(&am, a, m, ctx)) goto err; if (!BN_to_montgomery(&am, &am, mont, ctx)) goto err; } else if (!BN_to_montgomery(&am, a, mont, ctx)) goto err; #if defined(SPARC_T4_MONT) if (t4) { typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); static const bn_pwr5_mont_f pwr5_funcs[4] = { bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16, bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32 }; bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1]; typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); static const bn_mul_mont_f mul_funcs[4] = { bn_mul_mont_t4_8, bn_mul_mont_t4_16, bn_mul_mont_t4_24, bn_mul_mont_t4_32 }; bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1]; void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num, void *table, size_t power); void bn_gather5_t4(BN_ULONG *out, size_t num, void *table, size_t power); void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num); BN_ULONG *np = mont->N.d, *n0 = mont->n0; int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less * than 32 */ /* * BN_to_montgomery can contaminate words above .top [in * BN_DEBUG[_DEBUG] build]... */ for (i = am.top; i < top; i++) am.d[i] = 0; for (i = tmp.top; i < top; i++) tmp.d[i] = 0; bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0); bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1); if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) && !(*mul_worker) (tmp.d, am.d, am.d, np, n0)) bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top); bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2); for (i = 3; i < 32; i++) { /* Calculate a^i = a^(i-1) * a */ if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) && !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0)) bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top); bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i); } /* switch to 64-bit domain */ np = alloca(top * sizeof(BN_ULONG)); top /= 2; bn_flip_t4(np, mont->N.d, top); bits--; for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); bn_gather5_t4(tmp.d, top, powerbuf, wvalue); /* * Scan the exponent one window at a time starting from the most * significant bits. */ while (bits >= 0) { if (bits < stride) stride = bits + 1; bits -= stride; wvalue = bn_get_bits(p, bits + 1); if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride)) continue; /* retry once and fall back */ if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride)) continue; bits += stride - 5; wvalue >>= stride - 5; wvalue &= 31; bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); } bn_flip_t4(tmp.d, tmp.d, top); top *= 2; /* back to 32-bit domain */ tmp.top = top; bn_correct_top(&tmp); OPENSSL_cleanse(np, top * sizeof(BN_ULONG)); } else #endif #if defined(OPENSSL_BN_ASM_MONT5) if (window == 5 && top > 1) { /* * This optimization uses ideas from http://eprint.iacr.org/2011/239, * specifically optimization of cache-timing attack countermeasures * and pre-computation optimization. */ /* * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as * 512-bit RSA is hardly relevant, we omit it to spare size... */ void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); void bn_scatter5(const BN_ULONG *inp, size_t num, void *table, size_t power); void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power); void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); int bn_get_bits5(const BN_ULONG *ap, int off); int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *not_used, const BN_ULONG *np, const BN_ULONG *n0, int num); BN_ULONG *np = mont->N.d, *n0 = mont->n0, *np2; /* * BN_to_montgomery can contaminate words above .top [in * BN_DEBUG[_DEBUG] build]... */ for (i = am.top; i < top; i++) am.d[i] = 0; for (i = tmp.top; i < top; i++) tmp.d[i] = 0; if (top & 7) np2 = np; else for (np2 = am.d + top, i = 0; i < top; i++) np2[2 * i] = np[i]; bn_scatter5(tmp.d, top, powerbuf, 0); bn_scatter5(am.d, am.top, powerbuf, 1); bn_mul_mont(tmp.d, am.d, am.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, 2); # if 0 for (i = 3; i < 32; i++) { /* Calculate a^i = a^(i-1) * a */ bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); } # else /* same as above, but uses squaring for 1/2 of operations */ for (i = 4; i < 32; i *= 2) { bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, i); } for (i = 3; i < 8; i += 2) { int j; bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); for (j = 2 * i; j < 32; j *= 2) { bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, j); } } for (; i < 16; i += 2) { bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, 2 * i); } for (; i < 32; i += 2) { bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); } # endif bits--; for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); bn_gather5(tmp.d, top, powerbuf, wvalue); /* * Scan the exponent one window at a time starting from the most * significant bits. */ if (top & 7) while (bits >= 0) { for (wvalue = 0, i = 0; i < 5; i++, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); } else { while (bits >= 0) { wvalue = bn_get_bits5(p->d, bits - 4); bits -= 5; bn_power5(tmp.d, tmp.d, powerbuf, np2, n0, top, wvalue); } } ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np2, n0, top); tmp.top = top; bn_correct_top(&tmp); if (ret) { if (!BN_copy(rr, &tmp)) ret = 0; goto err; /* non-zero ret means it's not error */ } } else #endif { if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, numPowers)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, numPowers)) goto err; /* * If the window size is greater than 1, then calculate * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even * powers could instead be computed as (a^(i/2))^2 to use the slight * performance advantage of sqr over mul). */ if (window > 1) { if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF (&tmp, top, powerbuf, 2, numPowers)) goto err; for (i = 3; i < numPowers; i++) { /* Calculate a^i = a^(i-1) * a */ if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF (&tmp, top, powerbuf, i, numPowers)) goto err; } } bits--; for (wvalue = 0, i = bits % window; i >= 0; i--, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); if (!MOD_EXP_CTIME_COPY_FROM_PREBUF (&tmp, top, powerbuf, wvalue, numPowers)) goto err; /* * Scan the exponent one window at a time starting from the most } else #endif { if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, numPowers)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, numPowers)) goto err; /* wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); } /* * Fetch the appropriate pre-computed value from the pre-buf if (window > 1) { if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF (&tmp, top, powerbuf, 2, numPowers)) goto err; for (i = 3; i < numPowers; i++) { /* Calculate a^i = a^(i-1) * a */ if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF (&tmp, top, powerbuf, i, numPowers)) goto err; } } for (i = 1; i < top; i++) bits--; for (wvalue = 0, i = bits % window; i >= 0; i--, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); if (!MOD_EXP_CTIME_COPY_FROM_PREBUF (&tmp, top, powerbuf, wvalue, numPowers)) goto err; /* err: if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont); if (powerbuf != NULL) { OPENSSL_cleanse(powerbuf, powerbufLen); if (powerbufFree) OPENSSL_free(powerbufFree); } BN_CTX_end(ctx); return (ret); } int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, /* * Fetch the appropriate pre-computed value from the pre-buf */ if (!MOD_EXP_CTIME_COPY_FROM_PREBUF (&am, top, powerbuf, wvalue, numPowers)) goto err; /* Multiply the result into the intermediate result */ #define BN_MOD_MUL_WORD(r, w, m) \ (BN_mul_word(r, (w)) && \ (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \ (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1)))) /* * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is * probably more overhead than always using BN_mod (which uses BN_copy if * a similar test returns true). */ /* * We can use BN_mod and do not need BN_nnmod because our accumulator is * never negative (the result of BN_mod does not depend on the sign of * the modulus). */ #define BN_TO_MONTGOMERY_WORD(r, w, mont) \ (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx)) if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return -1; } bn_check_top(p); bn_check_top(m); if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS); return (0); } if (m->top == 1) a %= m->d[0]; /* make sure that 'a' is reduced */ bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } if (a == 0) { BN_zero(rr); ret = 1; return ret; } BN_CTX_start(ctx); d = BN_CTX_get(ctx); r = BN_CTX_get(ctx); t = BN_CTX_get(ctx); if (d == NULL || r == NULL || t == NULL) goto err; if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } r_is_one = 1; /* except for Montgomery factor */ /* bits-1 >= 0 */ /* The result is accumulated in the product r*w. */ w = a; /* bit 'bits-1' of 'p' is always set */ for (b = bits - 2; b >= 0; b--) { /* First, square r*w. */ next_w = w * w; if ((next_w / w) != w) { /* overflow */ if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } next_w = 1; } w = next_w; if (!r_is_one) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } /* Second, multiply r*w by 'a' if exponent bit is set. */ if (BN_is_bit_set(p, b)) { next_w = w * a; if ((next_w / a) != w) { /* overflow */ if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } next_w = a; } w = next_w; } } /* Finally, set r:=r*w. */ if (w != 1) { if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } } if (r_is_one) { /* can happen only if a == 1 */ if (!BN_one(rr)) goto err; } else { if (!BN_from_montgomery(rr, r, mont, ctx)) goto err; } ret = 1; err: if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); return (ret); } Commit Message: CWE ID: CWE-200 Target: 1 Example 2: Code: static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct dentry *old; /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { dput(dentry); return ERR_PTR(-ENOENT); } old = dir->i_op->lookup(dir, dentry, flags); if (unlikely(old)) { dput(dentry); dentry = old; } return dentry; } Commit Message: fs: umount on symlink leaks mnt count Currently umount on symlink blocks following umount: /vz is separate mount # ls /vz/ -al | grep test drwxr-xr-x. 2 root root 4096 Jul 19 01:14 testdir lrwxrwxrwx. 1 root root 11 Jul 19 01:16 testlink -> /vz/testdir # umount -l /vz/testlink umount: /vz/testlink: not mounted (expected) # lsof /vz # umount /vz umount: /vz: device is busy. (unexpected) In this case mountpoint_last() gets an extra refcount on path->mnt Signed-off-by: Vasily Averin <[email protected]> Acked-by: Ian Kent <[email protected]> Acked-by: Jeff Layton <[email protected]> Cc: [email protected] Signed-off-by: Christoph Hellwig <[email protected]> CWE ID: CWE-59 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: struct bpf_map *bpf_map_get_with_uref(u32 ufd) { struct fd f = fdget(ufd); struct bpf_map *map; map = __bpf_map_get(f); if (IS_ERR(map)) return map; bpf_map_inc(map, true); fdput(f); return map; } Commit Message: bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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 BrowserWindowGtk::TabDetachedAt(TabContents* contents, int index) { if (index == browser_->active_index()) { infobar_container_->ChangeTabContents(NULL); UpdateDevToolsForContents(NULL); } contents_container_->DetachTab(contents); } 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 CLASS foveon_thumb() { int bwide; unsigned row, col, bitbuf=0, bit=1, c, i; char *buf; struct decode *dindex; short pred[3]; bwide = get4(); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); if (bwide > 0) { if (bwide < thumb_width*3) return; buf = (char *) malloc (bwide); merror (buf, "foveon_thumb()"); for (row=0; row < thumb_height; row++) { fread (buf, 1, bwide, ifp); fwrite (buf, 3, thumb_width, ofp); } free (buf); return; } foveon_decoder (256, 0); for (row=0; row < thumb_height; row++) { memset (pred, 0, sizeof pred); if (!bit) get4(); for (bit=col=0; col < thumb_width; col++) FORC3 { for (dindex=first_decode; dindex->branch[0]; ) { if ((bit = (bit-1) & 31) == 31) for (i=0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += dindex->leaf; fputc (pred[c], ofp); } } } Commit Message: Avoid overflow in ljpeg_start(). 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: unsigned long nr_iowait(void) { unsigned long i, sum = 0; for_each_possible_cpu(i) sum += atomic_read(&cpu_rq(i)->nr_iowait); return sum; } 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: xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) { register const xmlChar *cmp = other; register const xmlChar *in; const xmlChar *ret; GROW; in = ctxt->input->cur; while (*in != 0 && *in == *cmp) { ++in; ++cmp; ctxt->input->col++; } if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) { /* success */ ctxt->input->cur = in; return (const xmlChar*) 1; } /* failure (or end of input buffer), check with full function */ ret = xmlParseName (ctxt); /* strings coming from the dictionnary direct compare possible */ if (ret == other) { return (const xmlChar*) 1; } return ret; } 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: int perf_swevent_get_recursion_context(void) { struct swevent_htable *swhash = &__get_cpu_var(swevent_htable); return get_recursion_context(swhash->recursion); } 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: 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 Session_SetProcEnabled(preproc_session_t *session, uint32_t procId, bool enabled) { if (enabled) { if(session->enabledMsk == 0) { session->framesIn = 0; if (session->inResampler != NULL) { speex_resampler_reset_mem(session->inResampler); } session->framesOut = 0; if (session->outResampler != NULL) { speex_resampler_reset_mem(session->outResampler); } } session->enabledMsk |= (1 << procId); if (HasReverseStream(procId)) { session->framesRev = 0; if (session->revResampler != NULL) { speex_resampler_reset_mem(session->revResampler); } session->revEnabledMsk |= (1 << procId); } } else { session->enabledMsk &= ~(1 << procId); if (HasReverseStream(procId)) { session->revEnabledMsk &= ~(1 << procId); } } ALOGV("Session_SetProcEnabled proc %d, enabled %d enabledMsk %08x revEnabledMsk %08x", procId, enabled, session->enabledMsk, session->revEnabledMsk); session->processedMsk = 0; if (HasReverseStream(procId)) { session->revProcessedMsk = 0; } } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119 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_DetachItemFromArray( cJSON *array, int which ) { cJSON *c = array->child; while ( c && which > 0 ) { c = c->next; --which; } if ( ! c ) return 0; if ( c->prev ) c->prev->next = c->next; if ( c->next ) c->next->prev = c->prev; if ( c == array->child ) array->child = c->next; c->prev = c->next = 0; 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 RendererSchedulerImpl::AddWebViewScheduler( WebViewSchedulerImpl* web_view_scheduler) { main_thread_only().web_view_schedulers.insert(web_view_scheduler); } Commit Message: [scheduler] Remove implicit fallthrough in switch Bail out early when a condition in the switch is fulfilled. This does not change behaviour due to RemoveTaskObserver being no-op when the task observer is not present in the list. [email protected] Bug: 177475 Change-Id: Ibc7772c79f8a8c8a1d63a997dabe1efda5d3a7bd Reviewed-on: https://chromium-review.googlesource.com/891187 Reviewed-by: Nico Weber <[email protected]> Commit-Queue: Alexander Timin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532649} 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 ContextState::RestoreBufferBindings() const { if (vertex_attrib_manager.get()) { Buffer* element_array_buffer = vertex_attrib_manager->element_array_buffer(); api()->glBindBufferFn(GL_ELEMENT_ARRAY_BUFFER, GetBufferId(element_array_buffer)); } api()->glBindBufferFn(GL_ARRAY_BUFFER, GetBufferId(bound_array_buffer.get())); if (feature_info_->IsES3Capable()) { api()->glBindBufferFn(GL_COPY_READ_BUFFER, GetBufferId(bound_copy_read_buffer.get())); api()->glBindBufferFn(GL_COPY_WRITE_BUFFER, GetBufferId(bound_copy_write_buffer.get())); api()->glBindBufferFn(GL_PIXEL_PACK_BUFFER, GetBufferId(bound_pixel_pack_buffer.get())); UpdatePackParameters(); api()->glBindBufferFn(GL_PIXEL_UNPACK_BUFFER, GetBufferId(bound_pixel_unpack_buffer.get())); UpdateUnpackParameters(); api()->glBindBufferFn(GL_TRANSFORM_FEEDBACK_BUFFER, GetBufferId(bound_transform_feedback_buffer.get())); api()->glBindBufferFn(GL_UNIFORM_BUFFER, GetBufferId(bound_uniform_buffer.get())); } } Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data. In linux and android, we are seeing an issue where texture data from one tab overwrites the texture data of another tab. This is happening for apps which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D. Due to a bug in virtual context save/restore code for above texture formats, the texture data is not properly restored while switching tabs. Hence texture data from one tab overwrites other. This CL has fix for that issue, an update for existing test expectations and a new unit test for this bug. Bug: 788448 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: Ie933984cdd2d1381f42eb4638f730c8245207a28 Reviewed-on: https://chromium-review.googlesource.com/930327 Reviewed-by: Zhenyao Mo <[email protected]> Commit-Queue: vikas soni <[email protected]> Cr-Commit-Position: refs/heads/master@{#539111} 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: validate_group(struct perf_event *event) { struct perf_event *sibling, *leader = event->group_leader; struct pmu_hw_events fake_pmu; DECLARE_BITMAP(fake_used_mask, ARMPMU_MAX_HWEVENTS); /* * Initialise the fake PMU. We only need to populate the * used_mask for the purposes of validation. */ memset(fake_used_mask, 0, sizeof(fake_used_mask)); fake_pmu.used_mask = fake_used_mask; if (!validate_event(&fake_pmu, leader)) return -EINVAL; list_for_each_entry(sibling, &leader->sibling_list, group_entry) { if (!validate_event(&fake_pmu, sibling)) return -EINVAL; } if (!validate_event(&fake_pmu, event)) return -EINVAL; return 0; } Commit Message: arm64: perf: reject groups spanning multiple HW PMUs The perf core implicitly rejects events spanning multiple HW PMUs, as in these cases the event->ctx will differ. However this validation is performed after pmu::event_init() is called in perf_init_event(), and thus pmu::event_init() may be called with a group leader from a different HW PMU. The ARM64 PMU driver does not take this fact into account, and when validating groups assumes that it can call to_arm_pmu(event->pmu) for any HW event. When the event in question is from another HW PMU this is wrong, and results in dereferencing garbage. This patch updates the ARM64 PMU driver to first test for and reject events from other PMUs, moving the to_arm_pmu and related logic after this test. Fixes a crash triggered by perf_fuzzer on Linux-4.0-rc2, with a CCI PMU present: Bad mode in Synchronous Abort handler detected, code 0x86000006 -- IABT (current EL) CPU: 0 PID: 1371 Comm: perf_fuzzer Not tainted 3.19.0+ #249 Hardware name: V2F-1XV7 Cortex-A53x2 SMM (DT) task: ffffffc07c73a280 ti: ffffffc07b0a0000 task.ti: ffffffc07b0a0000 PC is at 0x0 LR is at validate_event+0x90/0xa8 pc : [<0000000000000000>] lr : [<ffffffc000090228>] pstate: 00000145 sp : ffffffc07b0a3ba0 [< (null)>] (null) [<ffffffc0000907d8>] armpmu_event_init+0x174/0x3cc [<ffffffc00015d870>] perf_try_init_event+0x34/0x70 [<ffffffc000164094>] perf_init_event+0xe0/0x10c [<ffffffc000164348>] perf_event_alloc+0x288/0x358 [<ffffffc000164c5c>] SyS_perf_event_open+0x464/0x98c Code: bad PC value Also cleans up the code to use the arm_pmu only when we know that we are dealing with an arm pmu event. Cc: Will Deacon <[email protected]> Acked-by: Mark Rutland <[email protected]> Acked-by: Peter Ziljstra (Intel) <[email protected]> Signed-off-by: Suzuki K. Poulose <[email protected]> Signed-off-by: Will Deacon <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: _dbus_disable_sigpipe (void) { signal (SIGPIPE, SIG_IGN); } 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: IOHandler::IOHandler(DevToolsIOContext* io_context) : DevToolsDomainHandler(IO::Metainfo::domainName), io_context_(io_context), process_host_(nullptr), weak_factory_(this) {} Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} 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 int __net_init sctp_net_init(struct net *net) { int status; /* * 14. Suggested SCTP Protocol Parameter Values */ /* The following protocol parameters are RECOMMENDED: */ /* RTO.Initial - 3 seconds */ net->sctp.rto_initial = SCTP_RTO_INITIAL; /* RTO.Min - 1 second */ net->sctp.rto_min = SCTP_RTO_MIN; /* RTO.Max - 60 seconds */ net->sctp.rto_max = SCTP_RTO_MAX; /* RTO.Alpha - 1/8 */ net->sctp.rto_alpha = SCTP_RTO_ALPHA; /* RTO.Beta - 1/4 */ net->sctp.rto_beta = SCTP_RTO_BETA; /* Valid.Cookie.Life - 60 seconds */ net->sctp.valid_cookie_life = SCTP_DEFAULT_COOKIE_LIFE; /* Whether Cookie Preservative is enabled(1) or not(0) */ net->sctp.cookie_preserve_enable = 1; /* Default sctp sockets to use md5 as their hmac alg */ #if defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_MD5) net->sctp.sctp_hmac_alg = "md5"; #elif defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_SHA1) net->sctp.sctp_hmac_alg = "sha1"; #else net->sctp.sctp_hmac_alg = NULL; #endif /* Max.Burst - 4 */ net->sctp.max_burst = SCTP_DEFAULT_MAX_BURST; /* Association.Max.Retrans - 10 attempts * Path.Max.Retrans - 5 attempts (per destination address) * Max.Init.Retransmits - 8 attempts */ net->sctp.max_retrans_association = 10; net->sctp.max_retrans_path = 5; net->sctp.max_retrans_init = 8; /* Sendbuffer growth - do per-socket accounting */ net->sctp.sndbuf_policy = 0; /* Rcvbuffer growth - do per-socket accounting */ net->sctp.rcvbuf_policy = 0; /* HB.interval - 30 seconds */ net->sctp.hb_interval = SCTP_DEFAULT_TIMEOUT_HEARTBEAT; /* delayed SACK timeout */ net->sctp.sack_timeout = SCTP_DEFAULT_TIMEOUT_SACK; /* Disable ADDIP by default. */ net->sctp.addip_enable = 0; net->sctp.addip_noauth = 0; net->sctp.default_auto_asconf = 0; /* Enable PR-SCTP by default. */ net->sctp.prsctp_enable = 1; /* Disable AUTH by default. */ net->sctp.auth_enable = 0; /* Set SCOPE policy to enabled */ net->sctp.scope_policy = SCTP_SCOPE_POLICY_ENABLE; /* Set the default rwnd update threshold */ net->sctp.rwnd_upd_shift = SCTP_DEFAULT_RWND_SHIFT; /* Initialize maximum autoclose timeout. */ net->sctp.max_autoclose = INT_MAX / HZ; status = sctp_sysctl_net_register(net); if (status) goto err_sysctl_register; /* Allocate and initialise sctp mibs. */ status = init_sctp_mibs(net); if (status) goto err_init_mibs; /* Initialize proc fs directory. */ status = sctp_proc_init(net); if (status) goto err_init_proc; sctp_dbg_objcnt_init(net); /* Initialize the control inode/socket for handling OOTB packets. */ if ((status = sctp_ctl_sock_init(net))) { pr_err("Failed to initialize the SCTP control sock\n"); goto err_ctl_sock_init; } /* Initialize the local address list. */ INIT_LIST_HEAD(&net->sctp.local_addr_list); spin_lock_init(&net->sctp.local_addr_lock); sctp_get_local_addr_list(net); /* Initialize the address event list */ INIT_LIST_HEAD(&net->sctp.addr_waitq); INIT_LIST_HEAD(&net->sctp.auto_asconf_splist); spin_lock_init(&net->sctp.addr_wq_lock); net->sctp.addr_wq_timer.expires = 0; setup_timer(&net->sctp.addr_wq_timer, sctp_addr_wq_timeout_handler, (unsigned long)net); return 0; err_ctl_sock_init: sctp_dbg_objcnt_exit(net); sctp_proc_exit(net); err_init_proc: cleanup_sctp_mibs(net); err_init_mibs: sctp_sysctl_net_unregister(net); err_sysctl_register: return status; } 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 Target: 1 Example 2: Code: device_linux_md_add_spare (Device *device, char *component, char **options, DBusGMethodInvocation *context) { if (!device->priv->device_is_linux_md) { throw_error (context, ERROR_FAILED, "Device is not a Linux md drive"); goto out; } daemon_local_check_auth (device->priv->daemon, device, "org.freedesktop.udisks.linux-md", "LinuxMdAddSpare", TRUE, device_linux_md_add_spare_authorized_cb, context, 2, g_strdup (component), g_free, g_strdupv (options), g_strfreev); out: return TRUE; } Commit Message: 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: bool Document::IsLoadCompleted() const { return ready_state_ == kComplete; } 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 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 GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness) { notImplemented(); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: DeliverToWindowOwner(DeviceIntPtr dev, WindowPtr win, xEvent *events, int count, Mask filter, GrabPtr grab) { /* if nobody ever wants to see this event, skip some work */ if (filter != CantBeFiltered && !((wOtherEventMasks(win) | win->eventMask) & filter)) return EVENT_SKIP; if (IsInterferingGrab(wClient(win), dev, events)) return EVENT_SKIP; if (!XaceHook(XACE_RECEIVE_ACCESS, wClient(win), win, events, count)) { int attempt = TryClientEvents(wClient(win), dev, events, count, win->eventMask, filter, grab); if (attempt > 0) return EVENT_DELIVERED; if (attempt < 0) return EVENT_REJECTED; } return EVENT_NOT_DELIVERED; } 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: nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readargs *args) { unsigned int len; int v; p = decode_fh(p, &args->fh); if (!p) return 0; args->offset = ntohl(*p++); len = args->count = ntohl(*p++); p++; /* totalcount - unused */ len = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2); /* set up somewhere to store response. * We take pages, put them on reslist and include in iovec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return xdr_argsize_check(rqstp, p); } 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 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 struct sk_buff *ipv6_gso_segment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); struct ipv6hdr *ipv6h; const struct net_offload *ops; int proto; struct frag_hdr *fptr; unsigned int unfrag_ip6hlen; unsigned int payload_len; u8 *prevhdr; int offset = 0; bool encap, udpfrag; int nhoff; bool gso_partial; skb_reset_network_header(skb); nhoff = skb_network_header(skb) - skb_mac_header(skb); if (unlikely(!pskb_may_pull(skb, sizeof(*ipv6h)))) goto out; encap = SKB_GSO_CB(skb)->encap_level > 0; if (encap) features &= skb->dev->hw_enc_features; SKB_GSO_CB(skb)->encap_level += sizeof(*ipv6h); ipv6h = ipv6_hdr(skb); __skb_pull(skb, sizeof(*ipv6h)); segs = ERR_PTR(-EPROTONOSUPPORT); proto = ipv6_gso_pull_exthdrs(skb, ipv6h->nexthdr); if (skb->encapsulation && skb_shinfo(skb)->gso_type & (SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6)) udpfrag = proto == IPPROTO_UDP && encap; else udpfrag = proto == IPPROTO_UDP && !skb->encapsulation; ops = rcu_dereference(inet6_offloads[proto]); if (likely(ops && ops->callbacks.gso_segment)) { skb_reset_transport_header(skb); segs = ops->callbacks.gso_segment(skb, features); } if (IS_ERR_OR_NULL(segs)) goto out; gso_partial = !!(skb_shinfo(segs)->gso_type & SKB_GSO_PARTIAL); for (skb = segs; skb; skb = skb->next) { ipv6h = (struct ipv6hdr *)(skb_mac_header(skb) + nhoff); if (gso_partial) payload_len = skb_shinfo(skb)->gso_size + SKB_GSO_CB(skb)->data_offset + skb->head - (unsigned char *)(ipv6h + 1); else payload_len = skb->len - nhoff - sizeof(*ipv6h); ipv6h->payload_len = htons(payload_len); skb->network_header = (u8 *)ipv6h - skb->head; if (udpfrag) { unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr); fptr = (struct frag_hdr *)((u8 *)ipv6h + unfrag_ip6hlen); fptr->frag_off = htons(offset); if (skb->next) fptr->frag_off |= htons(IP6_MF); offset += (ntohs(ipv6h->payload_len) - sizeof(struct frag_hdr)); } if (encap) skb_reset_inner_headers(skb); } out: return segs; } Commit Message: ipv6: Prevent overrun when parsing v6 header options The KASAN warning repoted below was discovered with a syzkaller program. The reproducer is basically: int s = socket(AF_INET6, SOCK_RAW, NEXTHDR_HOP); send(s, &one_byte_of_data, 1, MSG_MORE); send(s, &more_than_mtu_bytes_data, 2000, 0); The socket() call sets the nexthdr field of the v6 header to NEXTHDR_HOP, the first send call primes the payload with a non zero byte of data, and the second send call triggers the fragmentation path. The fragmentation code tries to parse the header options in order to figure out where to insert the fragment option. Since nexthdr points to an invalid option, the calculation of the size of the network header can made to be much larger than the linear section of the skb and data is read outside of it. This fix makes ip6_find_1stfrag return an error if it detects running out-of-bounds. [ 42.361487] ================================================================== [ 42.364412] BUG: KASAN: slab-out-of-bounds in ip6_fragment+0x11c8/0x3730 [ 42.365471] Read of size 840 at addr ffff88000969e798 by task ip6_fragment-oo/3789 [ 42.366469] [ 42.366696] CPU: 1 PID: 3789 Comm: ip6_fragment-oo Not tainted 4.11.0+ #41 [ 42.367628] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.1-1ubuntu1 04/01/2014 [ 42.368824] Call Trace: [ 42.369183] dump_stack+0xb3/0x10b [ 42.369664] print_address_description+0x73/0x290 [ 42.370325] kasan_report+0x252/0x370 [ 42.370839] ? ip6_fragment+0x11c8/0x3730 [ 42.371396] check_memory_region+0x13c/0x1a0 [ 42.371978] memcpy+0x23/0x50 [ 42.372395] ip6_fragment+0x11c8/0x3730 [ 42.372920] ? nf_ct_expect_unregister_notifier+0x110/0x110 [ 42.373681] ? ip6_copy_metadata+0x7f0/0x7f0 [ 42.374263] ? ip6_forward+0x2e30/0x2e30 [ 42.374803] ip6_finish_output+0x584/0x990 [ 42.375350] ip6_output+0x1b7/0x690 [ 42.375836] ? ip6_finish_output+0x990/0x990 [ 42.376411] ? ip6_fragment+0x3730/0x3730 [ 42.376968] ip6_local_out+0x95/0x160 [ 42.377471] ip6_send_skb+0xa1/0x330 [ 42.377969] ip6_push_pending_frames+0xb3/0xe0 [ 42.378589] rawv6_sendmsg+0x2051/0x2db0 [ 42.379129] ? rawv6_bind+0x8b0/0x8b0 [ 42.379633] ? _copy_from_user+0x84/0xe0 [ 42.380193] ? debug_check_no_locks_freed+0x290/0x290 [ 42.380878] ? ___sys_sendmsg+0x162/0x930 [ 42.381427] ? rcu_read_lock_sched_held+0xa3/0x120 [ 42.382074] ? sock_has_perm+0x1f6/0x290 [ 42.382614] ? ___sys_sendmsg+0x167/0x930 [ 42.383173] ? lock_downgrade+0x660/0x660 [ 42.383727] inet_sendmsg+0x123/0x500 [ 42.384226] ? inet_sendmsg+0x123/0x500 [ 42.384748] ? inet_recvmsg+0x540/0x540 [ 42.385263] sock_sendmsg+0xca/0x110 [ 42.385758] SYSC_sendto+0x217/0x380 [ 42.386249] ? SYSC_connect+0x310/0x310 [ 42.386783] ? __might_fault+0x110/0x1d0 [ 42.387324] ? lock_downgrade+0x660/0x660 [ 42.387880] ? __fget_light+0xa1/0x1f0 [ 42.388403] ? __fdget+0x18/0x20 [ 42.388851] ? sock_common_setsockopt+0x95/0xd0 [ 42.389472] ? SyS_setsockopt+0x17f/0x260 [ 42.390021] ? entry_SYSCALL_64_fastpath+0x5/0xbe [ 42.390650] SyS_sendto+0x40/0x50 [ 42.391103] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.391731] RIP: 0033:0x7fbbb711e383 [ 42.392217] RSP: 002b:00007ffff4d34f28 EFLAGS: 00000246 ORIG_RAX: 000000000000002c [ 42.393235] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fbbb711e383 [ 42.394195] RDX: 0000000000001000 RSI: 00007ffff4d34f60 RDI: 0000000000000003 [ 42.395145] RBP: 0000000000000046 R08: 00007ffff4d34f40 R09: 0000000000000018 [ 42.396056] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000400aad [ 42.396598] R13: 0000000000000066 R14: 00007ffff4d34ee0 R15: 00007fbbb717af00 [ 42.397257] [ 42.397411] Allocated by task 3789: [ 42.397702] save_stack_trace+0x16/0x20 [ 42.398005] save_stack+0x46/0xd0 [ 42.398267] kasan_kmalloc+0xad/0xe0 [ 42.398548] kasan_slab_alloc+0x12/0x20 [ 42.398848] __kmalloc_node_track_caller+0xcb/0x380 [ 42.399224] __kmalloc_reserve.isra.32+0x41/0xe0 [ 42.399654] __alloc_skb+0xf8/0x580 [ 42.400003] sock_wmalloc+0xab/0xf0 [ 42.400346] __ip6_append_data.isra.41+0x2472/0x33d0 [ 42.400813] ip6_append_data+0x1a8/0x2f0 [ 42.401122] rawv6_sendmsg+0x11ee/0x2db0 [ 42.401505] inet_sendmsg+0x123/0x500 [ 42.401860] sock_sendmsg+0xca/0x110 [ 42.402209] ___sys_sendmsg+0x7cb/0x930 [ 42.402582] __sys_sendmsg+0xd9/0x190 [ 42.402941] SyS_sendmsg+0x2d/0x50 [ 42.403273] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.403718] [ 42.403871] Freed by task 1794: [ 42.404146] save_stack_trace+0x16/0x20 [ 42.404515] save_stack+0x46/0xd0 [ 42.404827] kasan_slab_free+0x72/0xc0 [ 42.405167] kfree+0xe8/0x2b0 [ 42.405462] skb_free_head+0x74/0xb0 [ 42.405806] skb_release_data+0x30e/0x3a0 [ 42.406198] skb_release_all+0x4a/0x60 [ 42.406563] consume_skb+0x113/0x2e0 [ 42.406910] skb_free_datagram+0x1a/0xe0 [ 42.407288] netlink_recvmsg+0x60d/0xe40 [ 42.407667] sock_recvmsg+0xd7/0x110 [ 42.408022] ___sys_recvmsg+0x25c/0x580 [ 42.408395] __sys_recvmsg+0xd6/0x190 [ 42.408753] SyS_recvmsg+0x2d/0x50 [ 42.409086] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.409513] [ 42.409665] The buggy address belongs to the object at ffff88000969e780 [ 42.409665] which belongs to the cache kmalloc-512 of size 512 [ 42.410846] The buggy address is located 24 bytes inside of [ 42.410846] 512-byte region [ffff88000969e780, ffff88000969e980) [ 42.411941] The buggy address belongs to the page: [ 42.412405] page:ffffea000025a780 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0 [ 42.413298] flags: 0x100000000008100(slab|head) [ 42.413729] raw: 0100000000008100 0000000000000000 0000000000000000 00000001800c000c [ 42.414387] raw: ffffea00002a9500 0000000900000007 ffff88000c401280 0000000000000000 [ 42.415074] page dumped because: kasan: bad access detected [ 42.415604] [ 42.415757] Memory state around the buggy address: [ 42.416222] ffff88000969e880: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 42.416904] ffff88000969e900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 42.417591] >ffff88000969e980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 42.418273] ^ [ 42.418588] ffff88000969ea00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [ 42.419273] ffff88000969ea80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [ 42.419882] ================================================================== Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Craig Gallek <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: local size_t grow(size_t size) { size_t was, top; int shift; was = size; size += size >> 2; top = size; for (shift = 0; top > 7; shift++) top >>= 1; if (top == 7) size = (size_t)1 << (shift + 3); if (size < 16) size = 16; if (size <= was) size = (size_t)0 - 1; return size; } Commit Message: When decompressing with -N or -NT, strip any path from header name. This uses the path of the compressed file combined with the name from the header as the name of the decompressed output file. Any path information in the header name is stripped. This avoids a possible vulnerability where absolute or descending paths are put in the gzip header. CWE ID: CWE-22 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 RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params& params) { MaybeHandleDebugURL(params.url); if (!render_view_->webview()) return; render_view_->OnNavigate(params); bool is_reload = RenderViewImpl::IsReload(params); WebURLRequest::CachePolicy cache_policy = WebURLRequest::UseProtocolCachePolicy; if (render_view_->IsBackForwardToStaleEntry(params, is_reload)) return; if (render_view_->is_swapped_out_) { render_view_->webview()->setVisibilityState( render_view_->visibilityState(), false); is_reload = false; cache_policy = WebURLRequest::ReloadIgnoringCacheData; RenderThreadImpl::NotifyTimezoneChange(); render_view_->SetSwappedOut(false); is_swapped_out_ = false; } if (params.should_clear_history_list) { CHECK_EQ(params.pending_history_list_offset, -1); CHECK_EQ(params.current_history_list_offset, -1); CHECK_EQ(params.current_history_list_length, 0); } render_view_->history_list_offset_ = params.current_history_list_offset; render_view_->history_list_length_ = params.current_history_list_length; if (render_view_->history_list_length_ >= 0) { render_view_->history_page_ids_.resize( render_view_->history_list_length_, -1); } if (params.pending_history_list_offset >= 0 && params.pending_history_list_offset < render_view_->history_list_length_) { render_view_->history_page_ids_[params.pending_history_list_offset] = params.page_id; } GetContentClient()->SetActiveURL(params.url); WebFrame* frame = frame_; if (!params.frame_to_navigate.empty()) { frame = render_view_->webview()->findFrameByName( WebString::fromUTF8(params.frame_to_navigate)); CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate; } if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) { is_reload = false; cache_policy = WebURLRequest::ReloadIgnoringCacheData; } render_view_->pending_navigation_params_.reset( new FrameMsg_Navigate_Params(params)); if (is_reload) { bool reload_original_url = (params.navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL); bool ignore_cache = (params.navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE); if (reload_original_url) frame->reloadWithOverrideURL(params.url, true); else frame->reload(ignore_cache); } else if (params.page_state.IsValid()) { DCHECK_NE(params.page_id, -1); scoped_ptr<HistoryEntry> entry = PageStateToHistoryEntry(params.page_state); if (entry) { CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL)); render_view_->history_controller()->GoToEntry(entry.Pass(), cache_policy); } } else if (!params.base_url_for_data_url.is_empty()) { std::string mime_type, charset, data; if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) { frame->loadData( WebData(data.c_str(), data.length()), WebString::fromUTF8(mime_type), WebString::fromUTF8(charset), params.base_url_for_data_url, params.history_url_for_data_url, false); } else { CHECK(false) << "Invalid URL passed: " << params.url.possibly_invalid_spec(); } } else { WebURLRequest request(params.url); CHECK_EQ(params.page_id, -1); if (frame->isViewSourceModeEnabled()) request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad); if (params.referrer.url.is_valid()) { WebString referrer = WebSecurityPolicy::generateReferrerHeader( params.referrer.policy, params.url, WebString::fromUTF8(params.referrer.url.spec())); if (!referrer.isEmpty()) request.setHTTPReferrer(referrer, params.referrer.policy); } if (!params.extra_headers.empty()) { for (net::HttpUtil::HeadersIterator i(params.extra_headers.begin(), params.extra_headers.end(), "\n"); i.GetNext(); ) { request.addHTTPHeaderField(WebString::fromUTF8(i.name()), WebString::fromUTF8(i.values())); } } if (params.is_post) { request.setHTTPMethod(WebString::fromUTF8("POST")); WebHTTPBody http_body; http_body.initialize(); const char* data = NULL; if (params.browser_initiated_post_data.size()) { data = reinterpret_cast<const char*>( &params.browser_initiated_post_data.front()); } http_body.appendData( WebData(data, params.browser_initiated_post_data.size())); request.setHTTPBody(http_body); } frame->loadRequest(request); if (!params.browser_navigation_start.is_null() && frame->provisionalDataSource()) { base::TimeTicks navigation_start = std::min( base::TimeTicks::Now(), params.browser_navigation_start); double navigation_start_seconds = (navigation_start - base::TimeTicks()).InSecondsF(); frame->provisionalDataSource()->setNavigationStartTime( navigation_start_seconds); } } render_view_->pending_navigation_params_.reset(); } Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame. BUG=369553 [email protected] Review URL: https://codereview.chromium.org/263833020 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 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: long Segment::Load() { assert(m_clusters == NULL); assert(m_clusterSize == 0); assert(m_clusterCount == 0); const long long header_status = ParseHeaders(); if (header_status < 0) //error return static_cast<long>(header_status); if (header_status > 0) //underflow return E_BUFFER_NOT_FULL; assert(m_pInfo); assert(m_pTracks); for (;;) { const int status = LoadCluster(); if (status < 0) //error return status; if (status >= 1) //no more clusters return 0; } } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: static inline void sched_init_numa(void) { } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <[email protected]>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top 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 ssize_t rd_set_configfs_dev_params(struct se_device *dev, const char *page, ssize_t count) { struct rd_dev *rd_dev = RD_DEV(dev); char *orig, *ptr, *opts; substring_t args[MAX_OPT_ARGS]; int ret = 0, arg, token; opts = kstrdup(page, GFP_KERNEL); if (!opts) return -ENOMEM; orig = opts; while ((ptr = strsep(&opts, ",\n")) != NULL) { if (!*ptr) continue; token = match_token(ptr, tokens, args); switch (token) { case Opt_rd_pages: match_int(args, &arg); rd_dev->rd_page_count = arg; pr_debug("RAMDISK: Referencing Page" " Count: %u\n", rd_dev->rd_page_count); rd_dev->rd_flags |= RDF_HAS_PAGE_COUNT; break; case Opt_rd_nullio: match_int(args, &arg); if (arg != 1) break; pr_debug("RAMDISK: Setting NULLIO flag: %d\n", arg); rd_dev->rd_flags |= RDF_NULLIO; break; default: break; } } kfree(orig); return (!ret) ? count : ret; } Commit Message: target/rd: Refactor rd_build_device_space + rd_release_device_space This patch refactors rd_build_device_space() + rd_release_device_space() into rd_allocate_sgl_table() + rd_release_device_space() so that they may be used seperatly for setup + release of protection information scatterlists. Also add explicit memset of pages within rd_allocate_sgl_table() based upon passed 'init_payload' value. v2 changes: - Drop unused sg_table from rd_release_device_space (Wei) Cc: Martin K. Petersen <[email protected]> Cc: Christoph Hellwig <[email protected]> Cc: Hannes Reinecke <[email protected]> Cc: Sagi Grimberg <[email protected]> Cc: Or Gerlitz <[email protected]> Signed-off-by: Nicholas Bellinger <[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: void RenderWidgetHostViewAura::AcceleratedSurfaceRelease( uint64 surface_handle) { DCHECK(image_transport_clients_.find(surface_handle) != image_transport_clients_.end()); if (current_surface_ == surface_handle) { current_surface_ = 0; UpdateExternalTexture(); } image_transport_clients_.erase(surface_handle); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: JSValue jsTestObjShortSequenceAttr(ExecState* exec, JSValue slotBase, const Identifier&) { JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(slotBase)); UNUSED_PARAM(exec); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); JSValue result = jsArray(exec, castedThis->globalObject(), impl->shortSequenceAttr()); return result; } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: usage(const char *prog) { /* ANSI C-90 limits strings to 509 characters, so use a string array: */ size_t i; static const char *usage_string[] = { " Tests, optimizes and optionally fixes the zlib header in PNG files.", " Optionally, when fixing, strips ancilliary chunks from the file.", 0, "OPTIONS", " OPERATION", " By default files are just checked for readability with a summary of the", " of zlib issues founds for each compressed chunk and the IDAT stream in", " the file.", " --optimize (-o):", " Find the smallest deflate window size for the compressed data.", " --strip=[none|crc|unsafe|unused|transform|color|all]:", " none (default): Retain all chunks.", " crc: Remove chunks with a bad CRC.", " unsafe: Remove chunks that may be unsafe to retain if the image data", " is modified. This is set automatically if --max is given but", " may be cancelled by a later --strip=none.", " unused: Remove chunks not used by libpng when decoding an image.", " This retains any chunks that might be used by libpng image", " transformations.", " transform: unused+bKGD.", " color: transform+iCCP and cHRM.", " all: color+gAMA and sRGB.", " Only ancillary chunks are ever removed. In addition the tRNS and sBIT", " chunks are never removed as they affect exact interpretation of the", " image pixel values. The following known chunks are treated specially", " by the above options:", " gAMA, sRGB [all]: These specify the gamma encoding used for the pixel", " values.", " cHRM, iCCP [color]: These specify how colors are encoded. iCCP also", " specifies the exact encoding of a pixel value however in practice", " most programs will ignore it.", " bKGD [transform]: This is used by libpng transforms." " --max=<number>:", " Use IDAT chunks sized <number>. If no number is given the the IDAT", " chunks will be the maximum size permitted; 2^31-1 bytes. If the option", " is omitted the original chunk sizes will not be changed. When the", " option is given --strip=unsafe is set automatically, this may be", " cancelled if you know that all unknown unsafe-to-copy chunks really are", " safe to copy across an IDAT size change. This is true of all chunks", " that have ever been formally proposed as PNG extensions.", " MESSAGES", " By default the program only outputs summaries for each file.", " --quiet (-q):", " Do not output the summaries except for files which cannot be read. With", " two --quiets these are not output either.", " --errors (-e):", " Output errors from libpng and the program (except too-far-back).", " --warnings (-w):", " Output warnings from libpng.", " OUTPUT", " By default nothing is written.", " --out=<file>:", " Write the optimized/corrected version of the next PNG to <file>. This", " overrides the following two options", " --suffix=<suffix>:", " Set --out=<name><suffix> for all following files unless overridden on", " a per-file basis by explicit --out.", " --prefix=<prefix>:", " Set --out=<prefix><name> for all the following files unless overridden", " on a per-file basis by explicit --out.", " These two options can be used together to produce a suffix and prefix.", " INTERNAL OPTIONS", #if 0 /*NYI*/ #ifdef PNG_MAXIMUM_INFLATE_WINDOW " --test:", " Test the PNG_MAXIMUM_INFLATE_WINDOW option. Setting this disables", " output as this would produce a broken file.", #endif #endif 0, "EXIT CODES", " *** SUBJECT TO CHANGE ***", " The program exit code is value in the range 0..127 holding a bit mask of", " the following codes. Notice that the results for each file are combined", " together - check one file at a time to get a meaningful error code!", " 0x01: The zlib too-far-back error existed in at least one chunk.", " 0x02: At least once chunk had a CRC error.", " 0x04: A chunk length was incorrect.", " 0x08: The file was truncated.", " Errors less than 16 are potentially recoverable, for a single file if the", " exit code is less than 16 the file could be read (with corrections if a", " non-zero code is returned).", " 0x10: The file could not be read, even with corrections.", " 0x20: The output file could not be written.", " 0x40: An unexpected, potentially internal, error occured.", " If the command line arguments are incorrect the program exits with exit", " 255. Some older operating systems only support 7-bit exit codes, on those", " systems it is suggested that this program is first tested by supplying", " invalid arguments.", 0, "DESCRIPTION", " " PROGRAM_NAME ":", " checks each PNG file on the command line for errors. By default errors are", " not output and the program just returns an exit code and prints a summary.", " With the --quiet (-q) option the summaries are suppressed too and the", " program only outputs unexpected errors (internal errors and file open", " errors).", " Various known problems in PNG files are fixed while the file is being read", " The exit code says what problems were fixed. In particular the zlib error:", 0, " \"invalid distance too far back\"", 0, " caused by an incorrect optimization of a zlib stream is fixed in any", " compressed chunk in which it is encountered. An integrity problem of the", " PNG stream caused by a bug in libpng which wrote an incorrect chunk length", " is also fixed. Chunk CRC errors are automatically fixed up.", 0, " Setting one of the \"OUTPUT\" options causes the possibly modified file to", " be written to a new file.", 0, " Notice that some PNG files with the zlib optimization problem can still be", " read by libpng under some circumstances. This program will still detect", " and, if requested, correct the error.", 0, " The program will reliably process all files on the command line unless", " either an invalid argument causes the usage message (this message) to be", " produced or the program crashes.", 0, " The summary lines describe issues encountered with the zlib compressed", " stream of a chunk. They have the following format, which is SUBJECT TO", " CHANGE in the future:", 0, " chunk reason comp-level p1 p2 p3 p4 file", 0, " p1 through p4 vary according to the 'reason'. There are always 8 space", " separated fields. Reasons specific formats are:", 0, " chunk ERR status code read-errno write-errno message file", " chunk SKP comp-level file-bits zlib-rc compressed message file", " chunk ??? comp-level file-bits ok-bits compressed uncompress file", 0, " The various fields are", 0, "$1 chunk: The chunk type of a chunk in the file or 'HEAD' if a problem", " is reported by libpng at the start of the IDAT stream.", "$2 reason: One of:", " CHK: A zlib header checksum was detected and fixed.", " TFB: The zlib too far back error was detected and fixed.", " OK : No errors were detected in the zlib stream and optimization", " was not requested, or was not possible.", " OPT: The zlib stream window bits value could be improved (and was).", " SKP: The chunk was skipped because of a zlib issue (zlib-rc) with", " explanation 'message'", " ERR: The read of the file was aborted. The parameters explain why.", "$3 status: For 'ERR' the accumulate status code from 'EXIT CODES' above.", " This is printed as a 2 digit hexadecimal value", " comp-level: The recorded compression level (FLEVEL) of a zlib stream", " expressed as a string {supfast,stdfast,default,maximum}", "$4 code: The file exit code; where stop was called, as a fairly terse", " string {warning,libpng,zlib,invalid,read,write,unexpected}.", " file-bits: The zlib window bits recorded in the file.", "$5 read-errno: A system errno value from a read translated by strerror(3).", " zlib-rc: A zlib return code as a string (see zlib.h).", " ok-bits: The smallest zlib window bits value that works.", "$6 write-errno:A system errno value from a write translated by strerror(3).", " compressed: The count of compressed bytes in the zlib stream, when the", " reason is 'SKP'; this is a count of the bytes read from the", " stream when the fatal error was encountered.", "$7 message: An error message (spaces replaced by _, as in all parameters),", " uncompress: The count of bytes from uncompressing the zlib stream; this", " may not be the same as the number of bytes in the image.", "$8 file: The name of the file (this may contain spaces).", }; fprintf(stderr, "Usage: %s {[options] png-file}\n", prog); for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i) { if (usage_string[i] != 0) fputs(usage_string[i], stderr); fputc('\n', stderr); } exit(255); } 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: mem_log_init(const char* prog_name, const char *banner) { size_t log_name_len; char *log_name; if (__test_bit(LOG_CONSOLE_BIT, &debug)) { log_op = stderr; return; } if (log_op) fclose(log_op); log_name_len = 5 + strlen(prog_name) + 5 + 7 + 4 + 1; /* "/tmp/" + prog_name + "_mem." + PID + ".log" + '\0" */ log_name = malloc(log_name_len); if (!log_name) { log_message(LOG_INFO, "Unable to malloc log file name"); log_op = stderr; return; } snprintf(log_name, log_name_len, "/tmp/%s_mem.%d.log", prog_name, getpid()); log_op = fopen(log_name, "a"); if (log_op == NULL) { log_message(LOG_INFO, "Unable to open %s for appending", log_name); log_op = stderr; } else { int fd = fileno(log_op); /* We don't want any children to inherit the log file */ fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); /* Make the log output line buffered. This was to ensure that * children didn't inherit the buffer, but the CLOEXEC above * should resolve that. */ setlinebuf(log_op); fprintf(log_op, "\n"); } free(log_name); terminate_banner = banner; } 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: void OneClickSigninHelper::SetDoNotClearPendingEmailForTesting() { do_not_clear_pending_email_ = true; } Commit Message: During redirects in the one click sign in flow, check the current URL instead of original URL to validate gaia http headers. BUG=307159 Review URL: https://codereview.chromium.org/77343002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@236563 0039d316-1c4b-4281-b951-d872f2087c98 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: bool PluginServiceImpl::GetPluginInfo(int render_process_id, int render_view_id, ResourceContext* context, const GURL& url, const GURL& page_url, const std::string& mime_type, bool allow_wildcard, bool* is_stale, webkit::WebPluginInfo* info, std::string* actual_mime_type) { std::vector<webkit::WebPluginInfo> plugins; std::vector<std::string> mime_types; bool stale = GetPluginInfoArray( url, mime_type, allow_wildcard, &plugins, &mime_types); if (is_stale) *is_stale = stale; for (size_t i = 0; i < plugins.size(); ++i) { if (!filter_ || filter_->IsPluginEnabled(render_process_id, render_view_id, context, url, page_url, &plugins[i])) { *info = plugins[i]; if (actual_mime_type) *actual_mime_type = mime_types[i]; return true; } } return false; } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287 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: virtual void CancelHandwritingStrokes(int stroke_count) { if (!initialized_successfully_) return; chromeos::CancelHandwriting(input_method_status_connection_, stroke_count); } 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: 1 Example 2: Code: void HTMLFormElement::submitFromJavaScript() { submit(0, false, UserGestureIndicator::processingUserGesture(), SubmittedByJavaScript); } Commit Message: Fix a crash in HTMLFormElement::prepareForSubmission. BUG=297478 TEST=automated with ASAN. Review URL: https://chromiumcodereview.appspot.com/24910003 git-svn-id: svn://svn.chromium.org/blink/trunk@158428 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: void TextTrack::addCue(TextTrackCue* cue) { DCHECK(cue); if (std::isnan(cue->startTime()) || std::isnan(cue->endTime()) || cue->startTime() < 0 || cue->endTime() < 0) return; if (TextTrack* cue_track = cue->track()) cue_track->removeCue(cue, ASSERT_NO_EXCEPTION); cue->SetTrack(this); EnsureTextTrackCueList()->Add(cue); if (GetCueTimeline() && mode_ != DisabledKeyword()) GetCueTimeline()->AddCue(this, cue); } Commit Message: Support negative timestamps of TextTrackCue Ensure proper behaviour for negative timestamps of TextTrackCue. 1. Cues with negative startTime should become active from 0s. 2. Cues with negative startTime and endTime should never be active. Bug: 314032 Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d Reviewed-on: https://chromium-review.googlesource.com/863270 Commit-Queue: srirama chandra sekhar <[email protected]> Reviewed-by: Fredrik Söderquist <[email protected]> Cr-Commit-Position: refs/heads/master@{#529012} 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 DownloadFileManager::CancelDownloadOnRename( DownloadId global_id, net::Error rename_error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); DownloadFile* download_file = GetDownloadFile(global_id); if (!download_file) return; DownloadManager* download_manager = download_file->GetDownloadManager(); DCHECK(download_manager); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&DownloadManager::OnDownloadInterrupted, download_manager, global_id.local(), download_file->BytesSoFar(), download_file->GetHashState(), content::ConvertNetErrorToInterruptReason( rename_error, content::DOWNLOAD_INTERRUPT_FROM_DISK))); } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void free_buffers(VP8Context *s) { int i; if (s->thread_data) for (i = 0; i < MAX_THREADS; i++) { #if HAVE_THREADS pthread_cond_destroy(&s->thread_data[i].cond); pthread_mutex_destroy(&s->thread_data[i].lock); #endif av_freep(&s->thread_data[i].filter_strength); } av_freep(&s->thread_data); av_freep(&s->macroblocks_base); av_freep(&s->intra4x4_pred_mode_top); av_freep(&s->top_nnz); av_freep(&s->top_border); s->macroblocks = NULL; } Commit Message: avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <[email protected]> Signed-off-by: Michael Niedermayer <[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: Chapters::Atom::~Atom() { } 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 int sctp_init_sock(struct sock *sk) { struct net *net = sock_net(sk); struct sctp_sock *sp; pr_debug("%s: sk:%p\n", __func__, sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = net->sctp.max_burst; sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init; sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = net->sctp.rto_initial; sp->rtoinfo.srto_max = net->sctp.rto_max; sp->rtoinfo.srto_min = net->sctp.rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = net->sctp.hb_interval; sp->pathmaxrxt = net->sctp.max_retrans_path; sp->pathmtu = 0; /* allow default discovery */ sp->sackdelay = net->sctp.sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; sp->recvrcvinfo = 0; sp->recvnxtinfo = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ sp->ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!sp->ep) return -ENOMEM; sp->hmac = NULL; sk->sk_destruct = sctp_destruct_sock; SCTP_DBG_OBJCNT_INC(sock); local_bh_disable(); percpu_counter_inc(&sctp_sockets_allocated); sock_prot_inuse_add(net, sk->sk_prot, 1); if (net->sctp.default_auto_asconf) { list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; } else sp->do_auto_asconf = 0; local_bh_enable(); return 0; } Commit Message: sctp: fix ASCONF list handling ->auto_asconf_splist is per namespace and mangled by functions like sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization. Also, the call to inet_sk_copy_descendant() was backuping ->auto_asconf_list through the copy but was not honoring ->do_auto_asconf, which could lead to list corruption if it was different between both sockets. This commit thus fixes the list handling by using ->addr_wq_lock spinlock to protect the list. A special handling is done upon socket creation and destruction for that. Error handlig on sctp_init_sock() will never return an error after having initialized asconf, so sctp_destroy_sock() can be called without addrq_wq_lock. The lock now will be take on sctp_close_sock(), before locking the socket, so we don't do it in inverse order compared to sctp_addr_wq_timeout_handler(). Instead of taking the lock on sctp_sock_migrate() for copying and restoring the list values, it's preferred to avoid rewritting it by implementing sctp_copy_descendant(). Issue was found with a test application that kept flipping sysctl default_auto_asconf on and off, but one could trigger it by issuing simultaneous setsockopt() calls on multiple sockets or by creating/destroying sockets fast enough. This is only triggerable locally. Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).") Reported-by: Ji Jianwen <[email protected]> Suggested-by: Neil Horman <[email protected]> Suggested-by: Hannes Frederic Sowa <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static void ipmi_request_event(struct ipmi_smi *intf) { /* No event requests when in maintenance mode. */ if (intf->maintenance_mode_enable) return; if (!intf->in_shutdown) intf->handlers->request_events(intf->send_info); } Commit Message: ipmi: fix use-after-free of user->release_barrier.rda When we do the following test, we got oops in ipmi_msghandler driver while((1)) do service ipmievd restart & service ipmievd restart done --------------------------------------------------------------- [ 294.230186] Unable to handle kernel paging request at virtual address 0000803fea6ea008 [ 294.230188] Mem abort info: [ 294.230190] ESR = 0x96000004 [ 294.230191] Exception class = DABT (current EL), IL = 32 bits [ 294.230193] SET = 0, FnV = 0 [ 294.230194] EA = 0, S1PTW = 0 [ 294.230195] Data abort info: [ 294.230196] ISV = 0, ISS = 0x00000004 [ 294.230197] CM = 0, WnR = 0 [ 294.230199] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000a1c1b75a [ 294.230201] [0000803fea6ea008] pgd=0000000000000000 [ 294.230204] Internal error: Oops: 96000004 [#1] SMP [ 294.235211] Modules linked in: nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm iw_cm dm_mirror dm_region_hash dm_log dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce sha2_ce ses sha256_arm64 sha1_ce hibmc_drm hisi_sas_v2_hw enclosure sg hisi_sas_main sbsa_gwdt ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe ipmi_si mdio hns_dsaf ipmi_devintf ipmi_msghandler hns_enet_drv hns_mdio [ 294.277745] CPU: 3 PID: 0 Comm: swapper/3 Kdump: loaded Not tainted 5.0.0-rc2+ #113 [ 294.285511] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 294.292835] pstate: 80000005 (Nzcv daif -PAN -UAO) [ 294.297695] pc : __srcu_read_lock+0x38/0x58 [ 294.301940] lr : acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler] [ 294.307853] sp : ffff00001001bc80 [ 294.311208] x29: ffff00001001bc80 x28: ffff0000117e5000 [ 294.316594] x27: 0000000000000000 x26: dead000000000100 [ 294.321980] x25: dead000000000200 x24: ffff803f6bd06800 [ 294.327366] x23: 0000000000000000 x22: 0000000000000000 [ 294.332752] x21: ffff00001001bd04 x20: ffff80df33d19018 [ 294.338137] x19: ffff80df33d19018 x18: 0000000000000000 [ 294.343523] x17: 0000000000000000 x16: 0000000000000000 [ 294.348908] x15: 0000000000000000 x14: 0000000000000002 [ 294.354293] x13: 0000000000000000 x12: 0000000000000000 [ 294.359679] x11: 0000000000000000 x10: 0000000000100000 [ 294.365065] x9 : 0000000000000000 x8 : 0000000000000004 [ 294.370451] x7 : 0000000000000000 x6 : ffff80df34558678 [ 294.375836] x5 : 000000000000000c x4 : 0000000000000000 [ 294.381221] x3 : 0000000000000001 x2 : 0000803fea6ea000 [ 294.386607] x1 : 0000803fea6ea008 x0 : 0000000000000001 [ 294.391994] Process swapper/3 (pid: 0, stack limit = 0x0000000083087293) [ 294.398791] Call trace: [ 294.401266] __srcu_read_lock+0x38/0x58 [ 294.405154] acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler] [ 294.410716] deliver_response+0x80/0xf8 [ipmi_msghandler] [ 294.416189] deliver_local_response+0x28/0x68 [ipmi_msghandler] [ 294.422193] handle_one_recv_msg+0x158/0xcf8 [ipmi_msghandler] [ 294.432050] handle_new_recv_msgs+0xc0/0x210 [ipmi_msghandler] [ 294.441984] smi_recv_tasklet+0x8c/0x158 [ipmi_msghandler] [ 294.451618] tasklet_action_common.isra.5+0x88/0x138 [ 294.460661] tasklet_action+0x2c/0x38 [ 294.468191] __do_softirq+0x120/0x2f8 [ 294.475561] irq_exit+0x134/0x140 [ 294.482445] __handle_domain_irq+0x6c/0xc0 [ 294.489954] gic_handle_irq+0xb8/0x178 [ 294.497037] el1_irq+0xb0/0x140 [ 294.503381] arch_cpu_idle+0x34/0x1a8 [ 294.510096] do_idle+0x1d4/0x290 [ 294.516322] cpu_startup_entry+0x28/0x30 [ 294.523230] secondary_start_kernel+0x184/0x1d0 [ 294.530657] Code: d538d082 d2800023 8b010c81 8b020021 (c85f7c25) [ 294.539746] ---[ end trace 8a7a880dee570b29 ]--- [ 294.547341] Kernel panic - not syncing: Fatal exception in interrupt [ 294.556837] SMP: stopping secondary CPUs [ 294.563996] Kernel Offset: disabled [ 294.570515] CPU features: 0x002,21006008 [ 294.577638] Memory Limit: none [ 294.587178] Starting crashdump kernel... [ 294.594314] Bye! Because the user->release_barrier.rda is freed in ipmi_destroy_user(), but the refcount is not zero, when acquire_ipmi_user() uses user->release_barrier.rda in __srcu_read_lock(), it causes oops. Fix this by calling cleanup_srcu_struct() when the refcount is zero. Fixes: e86ee2d44b44 ("ipmi: Rework locking and shutdown for hot remove") Cc: [email protected] # 4.18 Signed-off-by: Yang Yingliang <[email protected]> Signed-off-by: Corey Minyard <[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 int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY); } (void) xfrm_policy_walk(net, walk, dump_one_policy, &info); return skb->len; } Commit Message: ipsec: Fix aborted xfrm policy dump crash An independent security researcher, Mohamed Ghannam, has reported this vulnerability to Beyond Security's SecuriTeam Secure Disclosure program. The xfrm_dump_policy_done function expects xfrm_dump_policy to have been called at least once or it will crash. This can be triggered if a dump fails because the target socket's receive buffer is full. This patch fixes it by using the cb->start mechanism to ensure that the initialisation is always done regardless of the buffer situation. Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list") Signed-off-by: Herbert Xu <[email protected]> Signed-off-by: Steffen Klassert <[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: pseudo_ulog( ClassAd *ad ) { ULogEvent *event = instantiateEvent(ad); int result = 0; char const *critical_error = NULL; MyString CriticalErrorBuf; bool event_already_logged = false; bool put_job_on_hold = false; char const *hold_reason = NULL; char *hold_reason_buf = NULL; int hold_reason_code = 0; int hold_reason_sub_code = 0; if(!event) { MyString add_str; ad->sPrint(add_str); dprintf( D_ALWAYS, "invalid event ClassAd in pseudo_ulog: %s\n", add_str.Value()); return -1; } if(ad->LookupInteger(ATTR_HOLD_REASON_CODE,hold_reason_code)) { put_job_on_hold = true; ad->LookupInteger(ATTR_HOLD_REASON_SUBCODE,hold_reason_sub_code); ad->LookupString(ATTR_HOLD_REASON,&hold_reason_buf); if(hold_reason_buf) { hold_reason = hold_reason_buf; } } if( event->eventNumber == ULOG_REMOTE_ERROR ) { RemoteErrorEvent *err = (RemoteErrorEvent *)event; if(!err->getExecuteHost() || !*err->getExecuteHost()) { char *execute_host = NULL; thisRemoteResource->getMachineName(execute_host); err->setExecuteHost(execute_host); delete[] execute_host; } if(err->isCriticalError()) { CriticalErrorBuf.sprintf( "Error from %s: %s", err->getExecuteHost(), err->getErrorText()); critical_error = CriticalErrorBuf.Value(); if(!hold_reason) { hold_reason = critical_error; } BaseShadow::log_except(critical_error); event_already_logged = true; } } if( !event_already_logged && !Shadow->uLog.writeEvent( event, ad ) ) { MyString add_str; ad->sPrint(add_str); dprintf( D_ALWAYS, "unable to log event in pseudo_ulog: %s\n", add_str.Value()); result = -1; } if(put_job_on_hold) { hold_reason = critical_error; if(!hold_reason) { hold_reason = "Job put on hold by remote host."; } Shadow->holdJobAndExit(hold_reason,hold_reason_code,hold_reason_sub_code); } if( critical_error ) { Shadow->exception_already_logged = true; EXCEPT(critical_error); } delete event; return result; } Commit Message: CWE ID: CWE-134 Target: 1 Example 2: Code: base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len) { int i; unsigned char a, b, c, d; *dst_len = 0; for (i = 0; i < src_len; i += 4) { a = b64reverse(src[i]); if (a >= 254) { return i; } b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]); if (b >= 254) { return i + 1; } c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]); if (c == 254) { return i + 2; } d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]); if (d == 254) { return i + 3; } dst[(*dst_len)++] = (a << 2) + (b >> 4); if (c != 255) { dst[(*dst_len)++] = (b << 4) + (c >> 2); if (d != 255) { dst[(*dst_len)++] = (c << 6) + d; } } } 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: int main(int argc, char **argv) { #ifdef sgi char tmpline[80]; #endif char *p, *bgstr = NULL; int rc, alen, flen; int error = 0; int timing = FALSE; int have_bg = FALSE; #ifdef FEATURE_LOOP int loop = FALSE; long loop_interval = -1; /* seconds (100,000 max) */ #endif double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ XEvent e; KeySym k; /* First initialize a few things, just to be sure--memset takes care of * default background color (black), booleans (FALSE), pointers (NULL), * etc. */ displayname = (char *)NULL; filename = (char *)NULL; memset(&rpng2_info, 0, sizeof(mainprog_info)); /* Set the default value for our display-system exponent, i.e., the * product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. This is not an * exhaustive list of LUT values (e.g., OpenStep has a lot of weird * ones), but it should cover 99% of the current possibilities. */ #if defined(NeXT) /* third-party utilities can modify the default LUT exponent */ LUT_exponent = 1.0 / 2.2; /* if (some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to * get the "gamma" value, so we do it the hard way */ infile = fopen("/etc/config/system.glGammaVal", "r"); if (infile) { double sgi_gamma; fgets(tmpline, 80, infile); fclose(infile); sgi_gamma = atof(tmpline); if (sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if (some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ if ((p = getenv("SCREEN_GAMMA")) != NULL) rpng2_info.display_exponent = atof(p); else rpng2_info.display_exponent = default_display_exponent; /* Now parse the command line for options and the PNG filename. */ while (*++argv && !error) { if (!strncmp(*argv, "-display", 2)) { if (!*++argv) ++error; else displayname = *argv; } else if (!strncmp(*argv, "-gamma", 2)) { if (!*++argv) ++error; else { rpng2_info.display_exponent = atof(*argv); if (rpng2_info.display_exponent <= 0.0) ++error; } } else if (!strncmp(*argv, "-bgcolor", 4)) { if (!*++argv) ++error; else { bgstr = *argv; if (strlen(bgstr) != 7 || bgstr[0] != '#') ++error; else { have_bg = TRUE; bg_image = FALSE; } } } else if (!strncmp(*argv, "-bgpat", 4)) { if (!*++argv) ++error; else { pat = atoi(*argv); if (pat >= 0 && pat < num_bgpat) { bg_image = TRUE; have_bg = FALSE; } else ++error; } } else if (!strncmp(*argv, "-usleep", 2)) { if (!*++argv) ++error; else { usleep_duration = (ulg)atol(*argv); demo_timing = TRUE; } } else if (!strncmp(*argv, "-pause", 2)) { pause_after_pass = TRUE; } else if (!strncmp(*argv, "-timing", 2)) { timing = TRUE; #ifdef FEATURE_LOOP } else if (!strncmp(*argv, "-loop", 2)) { loop = TRUE; if (!argv[1] || !is_number(argv[1])) loop_interval = 2; else { ++argv; loop_interval = atol(*argv); if (loop_interval < 0) loop_interval = 2; else if (loop_interval > 100000) /* bit more than one day */ loop_interval = 100000; } #endif } else { if (**argv != '-') { filename = *argv; if (argv[1]) /* shouldn't be any more args after filename */ ++error; } else ++error; /* not expecting any other options */ } } if (!filename) ++error; /* print usage screen if any errors up to this point */ if (error) { fprintf(stderr, "\n%s %s: %s\n\n", PROGNAME, VERSION, appname); readpng2_version_info(); fprintf(stderr, "\n" "Usage: %s [-display xdpy] [-gamma exp] [-bgcolor bg | -bgpat pat]\n" #ifdef FEATURE_LOOP " %*s [-usleep dur | -timing] [-pause] [-loop [sec]] file.png\n\n" #else " %*s [-usleep dur | -timing] [-pause] file.png\n\n" #endif " xdpy\tname of the target X display (e.g., ``hostname:0'')\n" " exp \ttransfer-function exponent (``gamma'') of the display\n" "\t\t system in floating-point format (e.g., ``%.1f''); equal\n" "\t\t to the product of the lookup-table exponent (varies)\n" "\t\t and the CRT exponent (usually 2.2); must be positive\n" " bg \tdesired background color in 7-character hex RGB format\n" "\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n" "\t\t used with transparent images; overrides -bgpat\n" " pat \tdesired background pattern number (0-%d); used with\n" "\t\t transparent images; overrides -bgcolor\n" #ifdef FEATURE_LOOP " -loop\tloops through background images after initial display\n" "\t\t is complete (depends on -bgpat)\n" " sec \tseconds to display each background image (default = 2)\n" #endif " dur \tduration in microseconds to wait after displaying each\n" "\t\t row (for demo purposes)\n" " -timing\tenables delay for every block read, to simulate modem\n" "\t\t download of image (~36 Kbps)\n" " -pause\tpauses after displaying each pass until mouse clicked\n" "\nPress Q, Esc or mouse button 1 (within image window, after image\n" "is displayed) to quit.\n" "\n", PROGNAME, (int)strlen(PROGNAME), " ", default_display_exponent, num_bgpat-1); exit(1); } if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename); ++error; } else { incount = fread(inbuf, 1, INBUFSIZE, infile); if (incount < 8 || !readpng2_check_sig(inbuf, 8)) { fprintf(stderr, PROGNAME ": [%s] is not a PNG file: incorrect signature\n", filename); ++error; } else if ((rc = readpng2_init(&rpng2_info)) != 0) { switch (rc) { case 2: fprintf(stderr, PROGNAME ": [%s] has bad IHDR (libpng longjmp)\n", filename); break; case 4: fprintf(stderr, PROGNAME ": insufficient memory\n"); break; default: fprintf(stderr, PROGNAME ": unknown readpng2_init() error\n"); break; } ++error; } else { Trace((stderr, "about to call XOpenDisplay()\n")) display = XOpenDisplay(displayname); if (!display) { readpng2_cleanup(&rpng2_info); fprintf(stderr, PROGNAME ": can't open X display [%s]\n", displayname? displayname : "default"); ++error; } } if (error) fclose(infile); } if (error) { fprintf(stderr, PROGNAME ": aborting.\n"); exit(2); } /* set the title-bar string, but make sure buffer doesn't overflow */ alen = strlen(appname); flen = strlen(filename); if (alen + flen + 3 > 1023) sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023)); else sprintf(titlebar, "%s: %s", appname, filename); /* set some final rpng2_info variables before entering main data loop */ if (have_bg) { unsigned r, g, b; /* this approach quiets compiler warnings */ sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b); rpng2_info.bg_red = (uch)r; rpng2_info.bg_green = (uch)g; rpng2_info.bg_blue = (uch)b; } else rpng2_info.need_bgcolor = TRUE; rpng2_info.state = kPreInit; rpng2_info.mainprog_init = rpng2_x_init; rpng2_info.mainprog_display_row = rpng2_x_display_row; rpng2_info.mainprog_finish_display = rpng2_x_finish_display; /* OK, this is the fun part: call readpng2_decode_data() at the start of * the loop to deal with our first buffer of data (read in above to verify * that the file is a PNG image), then loop through the file and continue * calling the same routine to handle each chunk of data. It in turn * passes the data to libpng, which will invoke one or more of our call- * backs as decoded data become available. We optionally call sleep() for * one second per iteration to simulate downloading the image via an analog * modem. */ for (;;) { Trace((stderr, "about to call readpng2_decode_data()\n")) if (readpng2_decode_data(&rpng2_info, inbuf, incount)) ++error; Trace((stderr, "done with readpng2_decode_data()\n")) if (error || incount != INBUFSIZE || rpng2_info.state == kDone) { if (rpng2_info.state == kDone) { Trace((stderr, "done decoding PNG image\n")) } else if (ferror(infile)) { fprintf(stderr, PROGNAME ": error while reading PNG image file\n"); exit(3); } else if (feof(infile)) { fprintf(stderr, PROGNAME ": end of file reached " "(unexpectedly) while reading PNG image file\n"); exit(3); } else /* if (error) */ { /* will print error message below */ } break; } if (timing) sleep(1); incount = fread(inbuf, 1, INBUFSIZE, infile); } /* clean up PNG stuff and report any decoding errors */ fclose(infile); Trace((stderr, "about to call readpng2_cleanup()\n")) readpng2_cleanup(&rpng2_info); if (error) { fprintf(stderr, PROGNAME ": libpng error while decoding PNG image\n"); exit(3); } #ifdef FEATURE_LOOP if (loop && bg_image) { Trace((stderr, "entering -loop loop (FEATURE_LOOP)\n")) for (;;) { int i, use_sleep; struct timeval now, then; /* get current time and add loop_interval to get target time */ if (gettimeofday(&then, NULL) == 0) { then.tv_sec += loop_interval; use_sleep = FALSE; } else use_sleep = TRUE; /* do quick check for a quit event but don't wait for it */ /* GRR BUG: should also check for Expose events and redraw... */ if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e)) if (QUIT(e,k)) break; /* generate next background image */ if (++pat >= num_bgpat) pat = 0; rpng2_x_reload_bg_image(); /* wait for timeout, using whatever means are available */ if (use_sleep || gettimeofday(&now, NULL) != 0) { for (i = loop_interval; i > 0; --i) { sleep(1); /* GRR BUG: also need to check for Expose (and redraw!) */ if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e) && QUIT(e,k)) break; } } else { /* Y2038 BUG! */ if (now.tv_sec < then.tv_sec || (now.tv_sec == then.tv_sec && now.tv_usec < then.tv_usec)) { int quit = FALSE; long seconds_to_go = then.tv_sec - now.tv_sec; long usleep_usec; /* basically chew up most of remaining loop-interval with * calls to sleep(1) interleaved with checks for quit * events, but also recalc time-to-go periodically; when * done, clean up any remaining time with usleep() call * (could also use SIGALRM, but signals are a pain...) */ while (seconds_to_go-- > 1) { int seconds_done = 0; for (i = seconds_to_go; i > 0 && !quit; --i) { sleep(1); /* GRR BUG: need to check for Expose and redraw */ if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e) && QUIT(e,k)) quit = TRUE; if (++seconds_done > 1000) break; /* time to redo seconds_to_go meas. */ } if (quit) break; /* OK, more than 1000 seconds since last check: * correct the time-to-go measurement for drift */ if (gettimeofday(&now, NULL) == 0) { if (now.tv_sec >= then.tv_sec) break; seconds_to_go = then.tv_sec - now.tv_sec; } else ++seconds_to_go; /* restore what we subtracted */ } if (quit) break; /* breaks outer do-loop, skips redisplay */ /* since difference between "now" and "then" is already * eaten up to within a couple of seconds, don't need to * worry about overflow--but might have overshot (neg.) */ if (gettimeofday(&now, NULL) == 0) { usleep_usec = 1000000L*(then.tv_sec - now.tv_sec) + then.tv_usec - now.tv_usec; if (usleep_usec > 0) usleep((ulg)usleep_usec); } } } /* composite image against new background and display (note that * we do not take into account the time spent doing this...) */ rpng2_x_redisplay_image (0, 0, rpng2_info.width, rpng2_info.height); } } else /* FALL THROUGH and do the normal thing */ #endif /* FEATURE_LOOP */ /* wait for the user to tell us when to quit */ if (rpng2_info.state >= kWindowInit) { Trace((stderr, "entering final wait-for-quit-event loop\n")) do { XNextEvent(display, &e); if (e.type == Expose) { XExposeEvent *ex = (XExposeEvent *)&e; rpng2_x_redisplay_image (ex->x, ex->y, ex->width, ex->height); } } while (!QUIT(e,k)); } else { fprintf(stderr, PROGNAME ": init callback never called: probable " "libpng error while decoding PNG metadata\n"); exit(4); } /* we're done: clean up all image and X resources and go away */ Trace((stderr, "about to call rpng2_x_cleanup()\n")) rpng2_x_cleanup(); return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: 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: t1_decoder_parse_charstrings( T1_Decoder decoder, FT_Byte* charstring_base, FT_UInt charstring_len ) { FT_Error error; T1_Decoder_Zone zone; FT_Byte* ip; FT_Byte* limit; T1_Builder builder = &decoder->builder; FT_Pos x, y, orig_x, orig_y; FT_Int known_othersubr_result_cnt = 0; FT_Int unknown_othersubr_result_cnt = 0; FT_Bool large_int; FT_Fixed seed; T1_Hints_Funcs hinter; #ifdef FT_DEBUG_LEVEL_TRACE FT_Bool bol = TRUE; #endif /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_Offset)(char*)&seed ^ (FT_Offset)(char*)&decoder ^ (FT_Offset)(char*)&charstring_base ) & FT_ULONG_MAX ); seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* First of all, initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; builder->parse_state = T1_Parse_Start; hinter = (T1_Hints_Funcs)builder->hints_funcs; /* a font that reads BuildCharArray without setting */ /* its values first is buggy, but ... */ FT_ASSERT( ( decoder->len_buildchar == 0 ) == ( decoder->buildchar == NULL ) ); if ( decoder->buildchar && decoder->len_buildchar > 0 ) FT_ARRAY_ZERO( decoder->buildchar, decoder->len_buildchar ); FT_TRACE4(( "\n" "Start charstring\n" )); zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = FT_Err_Ok; x = orig_x = builder->pos_x; y = orig_y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); large_int = FALSE; /* now, execute loop */ while ( ip < limit ) { FT_Long* top = decoder->top; T1_Operator op = op_none; FT_Int32 value = 0; FT_ASSERT( known_othersubr_result_cnt == 0 || unknown_othersubr_result_cnt == 0 ); #ifdef FT_DEBUG_LEVEL_TRACE if ( bol ) { FT_TRACE5(( " (%d)", decoder->top - decoder->stack )); bol = FALSE; } #endif /*********************************************************************/ /* */ /* Decode operator or operand */ /* */ /* */ /* first of all, decompress operator or value */ switch ( *ip++ ) { case 1: op = op_hstem; break; case 3: op = op_vstem; break; case 4: op = op_vmoveto; break; case 5: op = op_rlineto; break; case 6: op = op_hlineto; break; case 7: op = op_vlineto; break; case 8: op = op_rrcurveto; break; case 9: op = op_closepath; break; case 10: op = op_callsubr; break; case 11: op = op_return; break; case 13: op = op_hsbw; break; case 14: op = op_endchar; break; case 15: /* undocumented, obsolete operator */ op = op_unknown15; break; case 21: op = op_rmoveto; break; case 22: op = op_hmoveto; break; case 30: op = op_vhcurveto; break; case 31: op = op_hvcurveto; break; case 12: if ( ip >= limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid escape (12+EOF)\n" )); goto Syntax_Error; } switch ( *ip++ ) { case 0: op = op_dotsection; break; case 1: op = op_vstem3; break; case 2: op = op_hstem3; break; case 6: op = op_seac; break; case 7: op = op_sbw; break; case 12: op = op_div; break; case 16: op = op_callothersubr; break; case 17: op = op_pop; break; case 33: op = op_setcurrentpoint; break; default: FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid escape (12+%d)\n", ip[-1] )); goto Syntax_Error; } break; case 255: /* four bytes integer */ if ( ip + 4 > limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected EOF in integer\n" )); goto Syntax_Error; } value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) | ( (FT_UInt32)ip[1] << 16 ) | ( (FT_UInt32)ip[2] << 8 ) | (FT_UInt32)ip[3] ); ip += 4; /* According to the specification, values > 32000 or < -32000 must */ /* be followed by a `div' operator to make the result be in the */ /* range [-32000;32000]. We expect that the second argument of */ /* `div' is not a large number. Additionally, we don't handle */ /* stuff like `<large1> <large2> <num> div <num> div' or */ /* <large1> <large2> <num> div div'. This is probably not allowed */ /* anyway. */ if ( value > 32000 || value < -32000 ) { if ( large_int ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no `div' after large integer\n" )); } else large_int = TRUE; } else { if ( !large_int ) value = (FT_Int32)( (FT_UInt32)value << 16 ); } break; default: if ( ip[-1] >= 32 ) { if ( ip[-1] < 247 ) value = (FT_Int32)ip[-1] - 139; else { if ( ++ip > limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected EOF in integer\n" )); goto Syntax_Error; } if ( ip[-2] < 251 ) value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108; else value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 ); } if ( !large_int ) value = (FT_Int32)( (FT_UInt32)value << 16 ); } else { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid byte (%d)\n", ip[-1] )); goto Syntax_Error; } } if ( unknown_othersubr_result_cnt > 0 ) { switch ( op ) { case op_callsubr: case op_return: case op_none: case op_pop: break; default: /* all operands have been transferred by previous pops */ unknown_othersubr_result_cnt = 0; break; } } if ( large_int && !( op == op_none || op == op_div ) ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no `div' after large integer\n" )); large_int = FALSE; } /*********************************************************************/ /* */ /* Push value on stack, or process operator */ /* */ /* */ if ( op == op_none ) { if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS ) { FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" )); goto Syntax_Error; } #ifdef FT_DEBUG_LEVEL_TRACE if ( large_int ) FT_TRACE4(( " %d", value )); else FT_TRACE4(( " %d", value / 65536 )); #endif *top++ = value; decoder->top = top; } else if ( op == op_callothersubr ) /* callothersubr */ { FT_Int subr_no; FT_Int arg_cnt; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( " callothersubr\n" )); bol = TRUE; #endif if ( top - decoder->stack < 2 ) goto Stack_Underflow; top -= 2; subr_no = Fix2Int( top[1] ); arg_cnt = Fix2Int( top[0] ); /***********************************************************/ /* */ /* remove all operands to callothersubr from the stack */ /* */ /* for handled othersubrs, where we know the number of */ /* arguments, we increase the stack by the value of */ /* known_othersubr_result_cnt */ /* */ /* for unhandled othersubrs the following pops adjust the */ /* stack pointer as necessary */ if ( arg_cnt > top - decoder->stack ) goto Stack_Underflow; top -= arg_cnt; known_othersubr_result_cnt = 0; unknown_othersubr_result_cnt = 0; /* XXX TODO: The checks to `arg_count == <whatever>' */ /* might not be correct; an othersubr expects a certain */ /* number of operands on the PostScript stack (as opposed */ /* to the T1 stack) but it doesn't have to put them there */ /* by itself; previous othersubrs might have left the */ /* operands there if they were not followed by an */ /* appropriate number of pops */ /* */ /* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */ /* accept a font that contains charstrings like */ /* */ /* 100 200 2 20 callothersubr */ /* 300 1 20 callothersubr pop */ /* */ /* Perhaps this is the reason why BuildCharArray exists. */ switch ( subr_no ) { case 0: /* end flex feature */ if ( arg_cnt != 3 ) goto Unexpected_OtherSubr; if ( !decoder->flex_state || decoder->num_flex_vectors != 7 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected flex end\n" )); goto Syntax_Error; } /* the two `results' are popped by the following setcurrentpoint */ top[0] = x; top[1] = y; known_othersubr_result_cnt = 2; break; case 1: /* start flex feature */ if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 6 ) ) ) goto Fail; decoder->flex_state = 1; decoder->num_flex_vectors = 0; break; case 2: /* add flex vectors */ { FT_Int idx; if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; if ( !decoder->flex_state ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " missing flex start\n" )); goto Syntax_Error; } /* note that we should not add a point for index 0; */ /* this will move our current position to the flex */ /* point without adding any point to the outline */ idx = decoder->num_flex_vectors++; if ( idx > 0 && idx < 7 ) t1_builder_add_point( builder, x, y, (FT_Byte)( idx == 3 || idx == 6 ) ); } break; break; case 12: case 13: /* counter control hints, clear stack */ top = decoder->stack; break; case 14: case 15: case 16: case 17: case 18: /* multiple masters */ { PS_Blend blend = decoder->blend; FT_UInt num_points, nn, mm; FT_Long* delta; FT_Long* values; if ( !blend ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected multiple masters operator\n" )); goto Syntax_Error; } num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 ); if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " incorrect number of multiple masters arguments\n" )); goto Syntax_Error; } /* We want to compute */ /* */ /* a0*w0 + a1*w1 + ... + ak*wk */ /* */ /* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */ /* */ /* However, given that w0 + w1 + ... + wk == 1, we can */ /* rewrite it easily as */ /* */ /* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */ /* */ /* where k == num_designs-1. */ /* */ /* I guess that's why it's written in this `compact' */ /* form. */ /* */ delta = top + num_points; values = top; for ( nn = 0; nn < num_points; nn++ ) { FT_Long tmp = values[0]; for ( mm = 1; mm < blend->num_designs; mm++ ) tmp += FT_MulFix( *delta++, blend->weight_vector[mm] ); *values++ = tmp; } known_othersubr_result_cnt = (FT_Int)num_points; break; } case 19: /* <idx> 1 19 callothersubr */ /* => replace elements starting from index cvi( <idx> ) */ /* of BuildCharArray with WeightVector */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 1 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[0] ); if ( idx < 0 || (FT_UInt)idx + blend->num_designs > decoder->len_buildchar ) goto Unexpected_OtherSubr; ft_memcpy( &decoder->buildchar[idx], blend->weight_vector, blend->num_designs * sizeof ( blend->weight_vector[0] ) ); } break; case 20: /* <arg1> <arg2> 2 20 callothersubr pop */ /* ==> push <arg1> + <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] += top[1]; /* XXX (over|under)flow */ known_othersubr_result_cnt = 1; break; case 21: /* <arg1> <arg2> 2 21 callothersubr pop */ /* ==> push <arg1> - <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] -= top[1]; /* XXX (over|under)flow */ known_othersubr_result_cnt = 1; break; case 22: /* <arg1> <arg2> 2 22 callothersubr pop */ /* ==> push <arg1> * <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] = FT_MulFix( top[0], top[1] ); known_othersubr_result_cnt = 1; break; case 23: /* <arg1> <arg2> 2 23 callothersubr pop */ /* ==> push <arg1> / <arg2> onto T1 stack */ if ( arg_cnt != 2 || top[1] == 0 ) goto Unexpected_OtherSubr; top[0] = FT_DivFix( top[0], top[1] ); known_othersubr_result_cnt = 1; break; case 24: /* <val> <idx> 2 24 callothersubr */ /* ==> set BuildCharArray[cvi( <idx> )] = <val> */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 2 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[1] ); if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar ) goto Unexpected_OtherSubr; decoder->buildchar[idx] = top[0]; } break; case 25: /* <idx> 1 25 callothersubr pop */ /* ==> push BuildCharArray[cvi( idx )] */ /* onto T1 stack */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 1 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[0] ); if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar ) goto Unexpected_OtherSubr; top[0] = decoder->buildchar[idx]; } known_othersubr_result_cnt = 1; break; #if 0 case 26: /* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */ /* leave mark on T1 stack */ /* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */ XXX which routine has left its mark on the (PostScript) stack?; break; #endif case 27: /* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */ /* ==> push <res1> onto T1 stack if <val1> <= <val2>, */ /* otherwise push <res2> */ if ( arg_cnt != 4 ) goto Unexpected_OtherSubr; if ( top[2] > top[3] ) top[0] = top[1]; known_othersubr_result_cnt = 1; break; case 28: /* 0 28 callothersubr pop */ /* => push random value from interval [0, 1) onto stack */ if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; { FT_Fixed Rand; Rand = seed; if ( Rand >= 0x8000L ) Rand++; top[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; } known_othersubr_result_cnt = 1; break; default: if ( arg_cnt >= 0 && subr_no >= 0 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unknown othersubr [%d %d], wish me luck\n", arg_cnt, subr_no )); unknown_othersubr_result_cnt = arg_cnt; break; } /* fall through */ Unexpected_OtherSubr: FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid othersubr [%d %d]\n", arg_cnt, subr_no )); goto Syntax_Error; } top += known_othersubr_result_cnt; decoder->top = top; } else /* general operator */ { FT_Int num_args = t1_args_count[op]; FT_ASSERT( num_args >= 0 ); if ( top - decoder->stack < num_args ) goto Stack_Underflow; /* XXX Operators usually take their operands from the */ /* bottom of the stack, i.e., the operands are */ /* decoder->stack[0], ..., decoder->stack[num_args - 1]; */ /* only div, callsubr, and callothersubr are different. */ /* In practice it doesn't matter (?). */ #ifdef FT_DEBUG_LEVEL_TRACE switch ( op ) { case op_callsubr: case op_div: case op_callothersubr: case op_pop: case op_return: break; default: if ( top - decoder->stack != num_args ) FT_TRACE0(( "t1_decoder_parse_charstrings:" " too much operands on the stack" " (seen %d, expected %d)\n", top - decoder->stack, num_args )); break; } #endif /* FT_DEBUG_LEVEL_TRACE */ top -= num_args; switch ( op ) { case op_endchar: FT_TRACE4(( " endchar\n" )); t1_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, (FT_UInt)builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ error = hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); if ( error ) goto Fail; } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* the compiler should optimize away this empty loop but ... */ #ifdef FT_DEBUG_LEVEL_TRACE if ( decoder->len_buildchar > 0 ) { FT_UInt i; FT_TRACE4(( "BuildCharArray = [ " )); for ( i = 0; i < decoder->len_buildchar; i++ ) FT_TRACE4(( "%d ", decoder->buildchar[i] )); FT_TRACE4(( "]\n" )); } #endif /* FT_DEBUG_LEVEL_TRACE */ FT_TRACE4(( "\n" )); /* return now! */ return FT_Err_Ok; case op_hsbw: FT_TRACE4(( " hsbw" )); builder->parse_state = T1_Parse_Have_Width; builder->left_bearing.x += top[0]; builder->advance.x = top[1]; builder->advance.y = 0; orig_x = x = builder->pos_x + top[0]; orig_y = y = builder->pos_y; FT_UNUSED( orig_y ); /* the `metrics_only' indicates that we only want to compute */ /* the glyph's metrics (lsb + advance width), not load the */ /* rest of it; so exit immediately */ if ( builder->metrics_only ) return FT_Err_Ok; break; case op_seac: return t1operator_seac( decoder, top[0], top[1], top[2], Fix2Int( top[3] ), Fix2Int( top[4] ) ); case op_sbw: FT_TRACE4(( " sbw" )); builder->parse_state = T1_Parse_Have_Width; builder->left_bearing.x += top[0]; builder->left_bearing.y += top[1]; builder->advance.x = top[2]; builder->advance.y = top[3]; x = builder->pos_x + top[0]; y = builder->pos_y + top[1]; /* the `metrics_only' indicates that we only want to compute */ /* the glyph's metrics (lsb + advance width), not load the */ /* rest of it; so exit immediately */ if ( builder->metrics_only ) return FT_Err_Ok; break; case op_closepath: FT_TRACE4(( " closepath" )); /* if there is no path, `closepath' is a no-op */ if ( builder->parse_state == T1_Parse_Have_Path || builder->parse_state == T1_Parse_Have_Moveto ) t1_builder_close_contour( builder ); builder->parse_state = T1_Parse_Have_Width; break; case op_hlineto: FT_TRACE4(( " hlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; x += top[0]; goto Add_Line; case op_hmoveto: FT_TRACE4(( " hmoveto" )); x += top[0]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_hvcurveto: FT_TRACE4(( " hvcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; x += top[0]; t1_builder_add_point( builder, x, y, 0 ); x += top[1]; y += top[2]; t1_builder_add_point( builder, x, y, 0 ); y += top[3]; t1_builder_add_point( builder, x, y, 1 ); break; case op_rlineto: FT_TRACE4(( " rlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; x += top[0]; y += top[1]; Add_Line: if ( FT_SET_ERROR( t1_builder_add_point1( builder, x, y ) ) ) goto Fail; break; case op_rmoveto: FT_TRACE4(( " rmoveto" )); x += top[0]; y += top[1]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_rrcurveto: FT_TRACE4(( " rrcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; x += top[0]; y += top[1]; t1_builder_add_point( builder, x, y, 0 ); x += top[2]; y += top[3]; t1_builder_add_point( builder, x, y, 0 ); x += top[4]; y += top[5]; t1_builder_add_point( builder, x, y, 1 ); break; case op_vhcurveto: FT_TRACE4(( " vhcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; y += top[0]; t1_builder_add_point( builder, x, y, 0 ); x += top[1]; y += top[2]; t1_builder_add_point( builder, x, y, 0 ); x += top[3]; t1_builder_add_point( builder, x, y, 1 ); break; case op_vlineto: FT_TRACE4(( " vlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; y += top[0]; goto Add_Line; case op_vmoveto: FT_TRACE4(( " vmoveto" )); y += top[0]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_div: FT_TRACE4(( " div" )); /* if `large_int' is set, we divide unscaled numbers; */ /* otherwise, we divide numbers in 16.16 format -- */ /* in both cases, it is the same operation */ *top = FT_DivFix( top[0], top[1] ); top++; large_int = FALSE; break; case op_callsubr: { FT_Int idx; FT_TRACE4(( " callsubr" )); idx = Fix2Int( top[0] ); if ( decoder->subrs_hash ) { size_t* val = ft_hash_num_lookup( idx, decoder->subrs_hash ); if ( val ) idx = *val; else idx = -1; } if ( idx < 0 || idx >= decoder->num_subrs ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid subrs index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; /* The Type 1 driver stores subroutines without the seed bytes. */ /* The CID driver stores subroutines with seed bytes. This */ /* case is taken care of when decoder->subrs_len == 0. */ zone->base = decoder->subrs[idx]; if ( decoder->subrs_len ) zone->limit = zone->base + decoder->subrs_len[idx]; else { /* We are using subroutines from a CID font. We must adjust */ /* for the seed bytes. */ zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 ); zone->limit = decoder->subrs[idx + 1]; } zone->cursor = zone->base; if ( !zone->base ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; break; } case op_pop: FT_TRACE4(( " pop" )); if ( known_othersubr_result_cnt > 0 ) { known_othersubr_result_cnt--; /* ignore, we pushed the operands ourselves */ break; } if ( unknown_othersubr_result_cnt == 0 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no more operands for othersubr\n" )); goto Syntax_Error; } unknown_othersubr_result_cnt--; top++; /* `push' the operand to callothersubr onto the stack */ break; case op_return: FT_TRACE4(( " return" )); if ( zone <= decoder->zones ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected return\n" )); goto Syntax_Error; } zone--; ip = zone->cursor; limit = zone->limit; decoder->zone = zone; break; case op_dotsection: FT_TRACE4(( " dotsection" )); break; case op_hstem: FT_TRACE4(( " hstem" )); /* record horizontal hint */ if ( hinter ) { /* top[0] += builder->left_bearing.y; */ hinter->stem( hinter->hints, 1, top ); } break; case op_hstem3: FT_TRACE4(( " hstem3" )); /* record horizontal counter-controlled hints */ if ( hinter ) hinter->stem3( hinter->hints, 1, top ); break; case op_vstem: FT_TRACE4(( " vstem" )); /* record vertical hint */ if ( hinter ) { top[0] += orig_x; hinter->stem( hinter->hints, 0, top ); } break; case op_vstem3: FT_TRACE4(( " vstem3" )); /* record vertical counter-controlled hints */ if ( hinter ) { FT_Pos dx = orig_x; top[0] += dx; top[2] += dx; top[4] += dx; hinter->stem3( hinter->hints, 0, top ); } break; case op_setcurrentpoint: FT_TRACE4(( " setcurrentpoint" )); /* From the T1 specification, section 6.4: */ /* */ /* The setcurrentpoint command is used only in */ /* conjunction with results from OtherSubrs procedures. */ /* known_othersubr_result_cnt != 0 is already handled */ /* above. */ /* Note, however, that both Ghostscript and Adobe */ /* Distiller handle this situation by silently ignoring */ /* the inappropriate `setcurrentpoint' instruction. So */ /* we do the same. */ #if 0 if ( decoder->flex_state != 1 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected `setcurrentpoint'\n" )); goto Syntax_Error; } else ... #endif x = top[0]; y = top[1]; decoder->flex_state = 0; break; case op_unknown15: FT_TRACE4(( " opcode_15" )); /* nothing to do except to pop the two arguments */ break; default: FT_ERROR(( "t1_decoder_parse_charstrings:" " unhandled opcode %d\n", op )); goto Syntax_Error; } /* XXX Operators usually clear the operand stack; */ /* only div, callsubr, callothersubr, pop, and */ /* return are different. */ /* In practice it doesn't matter (?). */ decoder->top = top; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( "\n" )); bol = TRUE; #endif } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( "..end..\n\n" )); Fail: return error; Syntax_Error: return FT_THROW( Syntax_Error ); Stack_Underflow: return FT_THROW( Stack_Underflow ); } Commit Message: CWE ID: CWE-787 Target: 1 Example 2: Code: static void reg_set_min_max(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { /* If the dst_reg is a pointer, we can't learn anything about its * variable offset from the compare (unless src_reg were a pointer into * the same object, but we don't bother with that. * Since false_reg and true_reg have the same type by construction, we * only need to check one of them for pointerness. */ if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JSET: false_reg->var_off = tnum_and(false_reg->var_off, tnum_const(~val)); if (is_power_of_2(val)) true_reg->var_off = tnum_or(true_reg->var_off, tnum_const(val)); break; case BPF_JGT: false_reg->umax_value = min(false_reg->umax_value, val); true_reg->umin_value = max(true_reg->umin_value, val + 1); break; case BPF_JSGT: false_reg->smax_value = min_t(s64, false_reg->smax_value, val); true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); break; case BPF_JLT: false_reg->umin_value = max(false_reg->umin_value, val); true_reg->umax_value = min(true_reg->umax_value, val - 1); break; case BPF_JSLT: false_reg->smin_value = max_t(s64, false_reg->smin_value, val); true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); break; case BPF_JGE: false_reg->umax_value = min(false_reg->umax_value, val - 1); true_reg->umin_value = max(true_reg->umin_value, val); break; case BPF_JSGE: false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); true_reg->smin_value = max_t(s64, true_reg->smin_value, val); break; case BPF_JLE: false_reg->umin_value = max(false_reg->umin_value, val + 1); true_reg->umax_value = min(true_reg->umax_value, val); break; case BPF_JSLE: false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); true_reg->smax_value = min_t(s64, true_reg->smax_value, val); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") took care of rejecting alu op on pointer when e.g. pointer came from two different map values with different map properties such as value size, Jann reported that a case was not covered yet when a given alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from different branches where we would incorrectly try to sanitize based on the pointer's limit. Catch this corner case and reject the program instead. Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> CWE ID: CWE-189 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 RunMemCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 5000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) { input_block[j] = rnd.Rand8() - rnd.Rand8(); input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255; } if (i == 0) for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = 255; if (i == 1) for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = -255; fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { EXPECT_EQ(output_block[j], output_ref_block[j]); EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j])) << "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE"; } } } 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: ssl_do_connect (server * serv) { char buf[128]; g_sess = serv->server_session; if (SSL_connect (serv->ssl) <= 0) { char err_buf[128]; int err; g_sess = NULL; if ((err = ERR_get_error ()) > 0) { ERR_error_string (err, err_buf); snprintf (buf, sizeof (buf), "(%d) %s", err, err_buf); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); if (ERR_GET_REASON (err) == SSL_R_WRONG_VERSION_NUMBER) PrintText (serv->server_session, _("Are you sure this is a SSL capable server and port?\n")); server_cleanup (serv); if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } } g_sess = NULL; if (SSL_is_init_finished (serv->ssl)) { struct cert_info cert_info; struct chiper_info *chiper_info; int verify_error; int i; if (!_SSL_get_cert_info (&cert_info, serv->ssl)) { snprintf (buf, sizeof (buf), "* Certification info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Subject:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.subject_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.subject_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Issuer:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.issuer_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.issuer_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Public key algorithm: %s (%d bits)", cert_info.algorithm, cert_info.algorithm_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); /*if (cert_info.rsa_tmp_bits) { snprintf (buf, sizeof (buf), " Public key algorithm uses ephemeral key with %d bits", cert_info.rsa_tmp_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); }*/ snprintf (buf, sizeof (buf), " Sign algorithm %s", cert_info.sign_algorithm/*, cert_info.sign_algorithm_bits*/); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Valid since %s to %s", cert_info.notbefore, cert_info.notafter); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } else { snprintf (buf, sizeof (buf), " * No Certificate"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } chiper_info = _SSL_get_cipher_info (serv->ssl); /* static buffer */ snprintf (buf, sizeof (buf), "* Cipher info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Version: %s, cipher %s (%u bits)", chiper_info->version, chiper_info->chiper, chiper_info->chiper_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); verify_error = SSL_get_verify_result (serv->ssl); switch (verify_error) { case X509_V_OK: /* snprintf (buf, sizeof (buf), "* Verify OK (?)"); */ /* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */ break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_CERT_HAS_EXPIRED: if (serv->accept_invalid_cert) { snprintf (buf, sizeof (buf), "* Verify E: %s.? (%d) -- Ignored", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); break; } default: snprintf (buf, sizeof (buf), "%s.? (%d)", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); return (0); } server_stopconnecting (serv); /* activate gtk poll */ server_connected (serv); return (0); /* remove it (0) */ } else { if (serv->ssl->session && serv->ssl->session->time + SSLTMOUT < time (NULL)) { snprintf (buf, sizeof (buf), "SSL handshake timed out"); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } return (1); /* call it more (1) */ } } Commit Message: ssl: Validate hostnames Closes #524 CWE ID: CWE-310 Target: 1 Example 2: Code: int SetLayerId(int frame_num, int num_temp_layers) { int layer_id = 0; if (num_temp_layers == 2) { if (frame_num % 2 == 0) { layer_id = 0; } else { layer_id = 1; } } else if (num_temp_layers == 3) { if (frame_num % 4 == 0) { layer_id = 0; } else if ((frame_num - 2) % 4 == 0) { layer_id = 1; } else if ((frame_num - 1) % 2 == 0) { layer_id = 2; } } return layer_id; } 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: 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 char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } Commit Message: ccpp: stop reading hs_error.log from /tmp The file might contain anything and there is no way to verify its contents. Related: #1211835 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-59 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: cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path is absolute"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); } Commit Message: Fixes for Issue #745 and Issue #746 from Doran Moppert. CWE ID: CWE-20 Target: 1 Example 2: Code: bool WebGLRenderingContextBase::ValidateHTMLVideoElement( const SecurityOrigin* security_origin, const char* function_name, HTMLVideoElement* video, ExceptionState& exception_state) { if (!video || !video->videoWidth() || !video->videoHeight()) { SynthesizeGLError(GL_INVALID_VALUE, function_name, "no video"); return false; } if (WouldTaintOrigin(video, security_origin)) { exception_state.ThrowSecurityError( "The video element contains cross-origin data, and may not be loaded."); return false; } return true; } Commit Message: Tighten about IntRect use in WebGL with overflow detection BUG=784183 TEST=test case in the bug in ASAN build [email protected] 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: Ie25ca328af99de7828e28e6a6e3d775f1bebc43f Reviewed-on: https://chromium-review.googlesource.com/811826 Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#522213} 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: IntSize RenderLayerScrollableArea::overhangAmount() const { return IntSize(); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 [email protected] Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416 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 __net_get_random_once(void *buf, int nbytes, bool *done, struct static_key *done_key) { static DEFINE_SPINLOCK(lock); unsigned long flags; spin_lock_irqsave(&lock, flags); if (*done) { spin_unlock_irqrestore(&lock, flags); return false; } get_random_bytes(buf, nbytes); *done = true; spin_unlock_irqrestore(&lock, flags); __net_random_once_disable_jump(done_key); return true; } Commit Message: net: avoid dependency of net_get_random_once on nop patching net_get_random_once depends on the static keys infrastructure to patch up the branch to the slow path during boot. This was realized by abusing the static keys api and defining a new initializer to not enable the call site while still indicating that the branch point should get patched up. This was needed to have the fast path considered likely by gcc. The static key initialization during boot up normally walks through all the registered keys and either patches in ideal nops or enables the jump site but omitted that step on x86 if ideal nops where already placed at static_key branch points. Thus net_get_random_once branches not always became active. This patch switches net_get_random_once to the ordinary static_key api and thus places the kernel fast path in the - by gcc considered - unlikely path. Microbenchmarks on Intel and AMD x86-64 showed that the unlikely path actually beats the likely path in terms of cycle cost and that different nop patterns did not make much difference, thus this switch should not be noticeable. Fixes: a48e42920ff38b ("net: introduce new macro net_get_random_once") Reported-by: Tuomas Räsänen <[email protected]> Cc: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: add_link(struct archive_read *a, struct xar *xar, struct xar_file *file) { struct hdlink *hdlink; for (hdlink = xar->hdlink_list; hdlink != NULL; hdlink = hdlink->next) { if (hdlink->id == file->link) { file->hdnext = hdlink->files; hdlink->cnt++; hdlink->files = file; return (ARCHIVE_OK); } } hdlink = malloc(sizeof(*hdlink)); if (hdlink == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } file->hdnext = NULL; hdlink->id = file->link; hdlink->cnt = 1; hdlink->files = file; hdlink->next = xar->hdlink_list; xar->hdlink_list = hdlink; return (ARCHIVE_OK); } Commit Message: Do something sensible for empty strings to make fuzzers happy. 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: int mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; } Commit Message: Security: fix Lua cmsgpack library stack overflow. During an auditing effort, the Apple Vulnerability Research team discovered a critical Redis security issue affecting the Lua scripting part of Redis. -- Description of the problem Several years ago I merged a pull request including many small changes at the Lua MsgPack library (that originally I authored myself). The Pull Request entered Redis in commit 90b6337c1, in 2014. Unfortunately one of the changes included a variadic Lua function that lacked the check for the available Lua C stack. As a result, calling the "pack" MsgPack library function with a large number of arguments, results into pushing into the Lua C stack a number of new values proportional to the number of arguments the function was called with. The pushed values, moreover, are controlled by untrusted user input. This in turn causes stack smashing which we believe to be exploitable, while not very deterministic, but it is likely that an exploit could be created targeting specific versions of Redis executables. However at its minimum the issue results in a DoS, crashing the Redis server. -- Versions affected Versions greater or equal to Redis 2.8.18 are affected. -- Reproducing Reproduce with this (based on the original reproduction script by Apple security team): https://gist.github.com/antirez/82445fcbea6d9b19f97014cc6cc79f8a -- Verification of the fix The fix was tested in the following way: 1) I checked that the problem is no longer observable running the trigger. 2) The Lua code was analyzed to understand the stack semantics, and that actually enough stack is allocated in all the cases of mp_pack() calls. 3) The mp_pack() function was modified in order to show exactly what items in the stack were being set, to make sure that there is no silent overflow even after the fix. -- Credits Thank you to the Apple team and to the other persons that helped me checking the patch and coordinating this communication. 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: char* engrave_tombstone(pid_t pid, pid_t tid, int signal, int original_si_code, uintptr_t abort_msg_address, bool dump_sibling_threads, bool* detach_failed, int* total_sleep_time_usec) { log_t log; log.current_tid = tid; log.crashed_tid = tid; if ((mkdir(TOMBSTONE_DIR, 0755) == -1) && (errno != EEXIST)) { _LOG(&log, logtype::ERROR, "failed to create %s: %s\n", TOMBSTONE_DIR, strerror(errno)); } if (chown(TOMBSTONE_DIR, AID_SYSTEM, AID_SYSTEM) == -1) { _LOG(&log, logtype::ERROR, "failed to change ownership of %s: %s\n", TOMBSTONE_DIR, strerror(errno)); } int fd = -1; char* path = NULL; if (selinux_android_restorecon(TOMBSTONE_DIR, 0) == 0) { path = find_and_open_tombstone(&fd); } else { _LOG(&log, logtype::ERROR, "Failed to restore security context, not writing tombstone.\n"); } if (fd < 0) { _LOG(&log, logtype::ERROR, "Skipping tombstone write, nothing to do.\n"); *detach_failed = false; return NULL; } log.tfd = fd; int amfd = activity_manager_connect(); log.amfd = amfd; *detach_failed = dump_crash(&log, pid, tid, signal, original_si_code, abort_msg_address, dump_sibling_threads, total_sleep_time_usec); ALOGI("\nTombstone written to: %s\n", path); close(amfd); close(fd); return path; } Commit Message: Don't create tombstone directory. Partial backport of cf79748. Bug: http://b/26403620 Change-Id: Ib877ab6cfab6aef079830c5a50ba81141ead35ee CWE ID: CWE-264 Target: 1 Example 2: Code: static zend_object_value spl_heap_object_clone(zval *zobject TSRMLS_DC) /* {{{ */ { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_heap_object *intern; old_object = zend_objects_get_address(zobject TSRMLS_CC); new_obj_val = spl_heap_object_new_ex(old_object->ce, &intern, zobject, 1 TSRMLS_CC); new_object = &intern->std; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); return new_obj_val; } /* }}} */ 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: static inline int mount_entry_on_systemfs(struct mntent *mntent) { return mount_entry_on_generic(mntent, mntent->mnt_dir); } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59 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 UDPSocketLibevent::InternalConnect(const IPEndPoint& address) { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) { Close(); return ERR_ADDRESS_INVALID; } rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len)); if (rv < 0) { int result = MapSystemError(errno); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; } Commit Message: Map posix error codes in bind better, and fix one windows mapping. r=wtc BUG=330233 Review URL: https://codereview.chromium.org/101193008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 1 Example 2: Code: HFSIterator::~HFSIterator() {} Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 [email protected], [email protected], [email protected], [email protected] Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} 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 AppLayerProtoDetectTest05(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\n<HTML><BODY>Blahblah</BODY></HTML>"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "220 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } Commit Message: proto/detect: workaround dns misdetected as dcerpc The DCERPC UDP detection would misfire on DNS with transaction ID 0x0400. This would happen as the protocol detection engine gives preference to pattern based detection over probing parsers for performance reasons. This hack/workaround fixes this specific case by still running the probing parser if DCERPC has been detected on UDP. The probing parser result will take precedence. Bug #2736. 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_MINIT_FUNCTION(spl_array) { REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject); REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate); REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable); REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable); memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_handler_ArrayObject.clone_obj = spl_array_object_clone; spl_handler_ArrayObject.read_dimension = spl_array_read_dimension; spl_handler_ArrayObject.write_dimension = spl_array_write_dimension; spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension; spl_handler_ArrayObject.has_dimension = spl_array_has_dimension; spl_handler_ArrayObject.count_elements = spl_array_object_count_elements; spl_handler_ArrayObject.get_properties = spl_array_get_properties; spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info; spl_handler_ArrayObject.read_property = spl_array_read_property; spl_handler_ArrayObject.write_property = spl_array_write_property; spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr; spl_handler_ArrayObject.has_property = spl_array_has_property; spl_handler_ArrayObject.unset_property = spl_array_unset_property; spl_handler_ArrayObject.compare_objects = spl_array_compare_objects; REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable); memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers)); spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator); REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator); spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY); return SUCCESS; } Commit Message: Fixed ##72433: Use After Free Vulnerability in PHP's GC algorithm and unserialize CWE ID: CWE-416 Target: 1 Example 2: Code: SparseArrayState(v8::Handle<v8::Array> array, v8::Handle<v8::Array> propertyNames, StateBase* next, v8::Isolate* isolate) : AbstractObjectState(array, next) { m_propertyNames = v8::Local<v8::Array>::New(isolate, propertyNames); } Commit Message: Replace further questionable HashMap::add usages in bindings BUG=390928 [email protected] Review URL: https://codereview.chromium.org/411273002 git-svn-id: svn://svn.chromium.org/blink/trunk@178823 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: status_t BnGraphicBufferConsumer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case ACQUIRE_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); BufferItem item; int64_t presentWhen = data.readInt64(); status_t result = acquireBuffer(&item, presentWhen); status_t err = reply->write(item); if (err) return err; reply->writeInt32(result); return NO_ERROR; } break; case DETACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int slot = data.readInt32(); int result = detachBuffer(slot); reply->writeInt32(result); return NO_ERROR; } break; case ATTACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); sp<GraphicBuffer> buffer = new GraphicBuffer(); data.read(*buffer.get()); int slot; int result = attachBuffer(&slot, buffer); reply->writeInt32(slot); reply->writeInt32(result); return NO_ERROR; } break; case RELEASE_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int buf = data.readInt32(); uint64_t frameNumber = data.readInt64(); sp<Fence> releaseFence = new Fence(); status_t err = data.read(*releaseFence); if (err) return err; status_t result = releaseBuffer(buf, frameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence); reply->writeInt32(result); return NO_ERROR; } break; case CONSUMER_CONNECT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() ); bool controlledByApp = data.readInt32(); status_t result = consumerConnect(consumer, controlledByApp); reply->writeInt32(result); return NO_ERROR; } break; case CONSUMER_DISCONNECT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); status_t result = consumerDisconnect(); reply->writeInt32(result); return NO_ERROR; } break; case GET_RELEASED_BUFFERS: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint64_t slotMask; status_t result = getReleasedBuffers(&slotMask); reply->writeInt64(slotMask); reply->writeInt32(result); return NO_ERROR; } break; case SET_DEFAULT_BUFFER_SIZE: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t w = data.readInt32(); uint32_t h = data.readInt32(); status_t result = setDefaultBufferSize(w, h); reply->writeInt32(result); return NO_ERROR; } break; case SET_DEFAULT_MAX_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t bufferCount = data.readInt32(); status_t result = setDefaultMaxBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } break; case DISABLE_ASYNC_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); status_t result = disableAsyncBuffer(); reply->writeInt32(result); return NO_ERROR; } break; case SET_MAX_ACQUIRED_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t maxAcquiredBuffers = data.readInt32(); status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers); reply->writeInt32(result); return NO_ERROR; } break; case SET_CONSUMER_NAME: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); setConsumerName( data.readString8() ); return NO_ERROR; } break; case SET_DEFAULT_BUFFER_FORMAT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t defaultFormat = data.readInt32(); status_t result = setDefaultBufferFormat(defaultFormat); reply->writeInt32(result); return NO_ERROR; } break; case SET_CONSUMER_USAGE_BITS: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t usage = data.readInt32(); status_t result = setConsumerUsageBits(usage); reply->writeInt32(result); return NO_ERROR; } break; case SET_TRANSFORM_HINT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t hint = data.readInt32(); status_t result = setTransformHint(hint); reply->writeInt32(result); return NO_ERROR; } break; case DUMP: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); String8 result = data.readString8(); String8 prefix = data.readString8(); static_cast<IGraphicBufferConsumer*>(this)->dump(result, prefix); reply->writeString8(result); return NO_ERROR; } } return BBinder::onTransact(code, data, reply, flags); } Commit Message: IGraphicBufferConsumer: fix ATTACH_BUFFER info leak Bug: 26338113 Change-Id: I019c4df2c6adbc944122df96968ddd11a02ebe33 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: void ParamTraits<SkBitmap>::Write(base::Pickle* m, const SkBitmap& p) { size_t fixed_size = sizeof(SkBitmap_Data); SkBitmap_Data bmp_data; bmp_data.InitSkBitmapDataForTransfer(p); m->WriteData(reinterpret_cast<const char*>(&bmp_data), static_cast<int>(fixed_size)); size_t pixel_size = p.computeByteSize(); m->WriteData(reinterpret_cast<const char*>(p.getPixels()), static_cast<int>(pixel_size)); } Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices. Using memcpy() to serialize a POD struct is highly discouraged. Just use the standard IPC param traits macros for doing it. Bug: 779428 Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334 Reviewed-on: https://chromium-review.googlesource.com/899649 Reviewed-by: Tom Sepez <[email protected]> Commit-Queue: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#534562} CWE ID: CWE-125 Target: 1 Example 2: Code: void OxideQQuickWebView::stop() { Q_D(OxideQQuickWebView); if (!d->proxy_) { return; } d->proxy_->stop(); } 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: bool WebPage::touchEvent(const Platform::TouchEvent& event) { #if DEBUG_TOUCH_EVENTS BBLOG(LogLevelCritical, "%s", event.toString().c_str()); #endif #if ENABLE(TOUCH_EVENTS) if (!d->m_mainFrame) return false; if (d->m_page->defersLoading()) return false; PluginView* pluginView = d->m_fullScreenPluginView.get(); if (pluginView) return d->dispatchTouchEventToFullScreenPlugin(pluginView, event); Platform::TouchEvent tEvent = event; for (unsigned i = 0; i < event.m_points.size(); i++) { tEvent.m_points[i].m_pos = d->mapFromTransformed(tEvent.m_points[i].m_pos); tEvent.m_points[i].m_screenPos = tEvent.m_points[i].m_screenPos; } if (event.isSingleTap()) d->m_pluginMayOpenNewTab = true; else if (tEvent.m_type == Platform::TouchEvent::TouchStart || tEvent.m_type == Platform::TouchEvent::TouchCancel) d->m_pluginMayOpenNewTab = false; if (tEvent.m_type == Platform::TouchEvent::TouchStart) { d->clearCachedHitTestResult(); d->m_touchEventHandler->doFatFingers(tEvent.m_points[0]); Element* elementUnderFatFinger = d->m_touchEventHandler->lastFatFingersResult().nodeAsElementIfApplicable(); if (elementUnderFatFinger) d->m_touchEventHandler->drawTapHighlight(); } bool handled = false; if (!event.m_type != Platform::TouchEvent::TouchInjected) handled = d->m_mainFrame->eventHandler()->handleTouchEvent(PlatformTouchEvent(&tEvent)); if (d->m_preventDefaultOnTouchStart) { if (tEvent.m_type == Platform::TouchEvent::TouchEnd || tEvent.m_type == Platform::TouchEvent::TouchCancel) d->m_preventDefaultOnTouchStart = false; return true; } if (handled) { if (tEvent.m_type == Platform::TouchEvent::TouchStart) d->m_preventDefaultOnTouchStart = true; return true; } if (event.isTouchHold()) d->m_touchEventHandler->doFatFingers(tEvent.m_points[0]); #endif return false; } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 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: static inline int btif_hl_select_wake_reset(void){ char sig_recv = 0; BTIF_TRACE_DEBUG("btif_hl_select_wake_reset"); recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL); return(int)sig_recv; } 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: 1 Example 2: Code: const Entry* current_record() const { return &current_record_; } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 [email protected], [email protected], [email protected], [email protected] Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} 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: png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { png_byte compression_type; png_bytep pC; png_charp profile; png_uint_32 skip = 0; png_uint_32 profile_size, profile_length; png_size_t slength, prefix_length, data_length; png_debug(1, "in png_handle_iCCP"); if (!(png_ptr->mode & PNG_HAVE_IHDR)) png_error(png_ptr, "Missing IHDR before iCCP"); else if (png_ptr->mode & PNG_HAVE_IDAT) { png_warning(png_ptr, "Invalid iCCP after IDAT"); png_crc_finish(png_ptr, length); return; } else if (png_ptr->mode & PNG_HAVE_PLTE) /* Should be an error, but we can cope with it */ png_warning(png_ptr, "Out of place iCCP chunk"); if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)) { png_warning(png_ptr, "Duplicate iCCP chunk"); png_crc_finish(png_ptr, length); return; } #ifdef PNG_MAX_MALLOC_64K if (length > (png_uint_32)65535L) { png_warning(png_ptr, "iCCP chunk too large to fit in memory"); skip = length - (png_uint_32)65535L; length = (png_uint_32)65535L; } #endif png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1); slength = (png_size_t)length; png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); if (png_crc_finish(png_ptr, skip)) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; return; } png_ptr->chunkdata[slength] = 0x00; for (profile = png_ptr->chunkdata; *profile; profile++) /* Empty loop to find end of name */ ; ++profile; /* There should be at least one zero (the compression type byte) * following the separator, and we should be on it */ if ( profile >= png_ptr->chunkdata + slength - 1) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Malformed iCCP chunk"); return; } /* Compression_type should always be zero */ compression_type = *profile++; if (compression_type) { png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk"); compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8 wrote nonzero) */ } prefix_length = profile - png_ptr->chunkdata; png_decompress_chunk(png_ptr, compression_type, slength, prefix_length, &data_length); profile_length = data_length - prefix_length; if ( prefix_length > data_length || profile_length < 4) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Profile size field missing from iCCP chunk"); return; } /* Check the profile_size recorded in the first 32 bits of the ICC profile */ pC = (png_bytep)(png_ptr->chunkdata + prefix_length); profile_size = ((*(pC ))<<24) | ((*(pC + 1))<<16) | ((*(pC + 2))<< 8) | ((*(pC + 3)) ); if (profile_size < profile_length) profile_length = profile_size; if (profile_size > profile_length) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Ignoring truncated iCCP profile."); return; } png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata, compression_type, png_ptr->chunkdata + prefix_length, profile_length); png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; } 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: int btsock_thread_post_cmd(int h, int type, const unsigned char* data, int size, uint32_t user_id) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized"); return FALSE; } sock_cmd_t cmd = {CMD_USER_PRIVATE, 0, type, size, user_id}; APPL_TRACE_DEBUG("post cmd type:%d, size:%d, h:%d, ", type, size, h); sock_cmd_t* cmd_send = &cmd; int size_send = sizeof(cmd); if(data && size) { size_send = sizeof(cmd) + size; cmd_send = (sock_cmd_t*)alloca(size_send); if(cmd_send) { *cmd_send = cmd; memcpy(cmd_send + 1, data, size); } else { APPL_TRACE_ERROR("alloca failed at h:%d, cmd type:%d, size:%d", h, type, size_send); return FALSE; } } return send(ts[h].cmd_fdw, cmd_send, size_send, 0) == size_send; } 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: 1 Example 2: Code: void StreamTcpSessionPktFree (Packet *p) { SCEnter(); TcpSession *ssn = (TcpSession *)p->flow->protoctx; if (ssn == NULL) SCReturn; StreamTcpReturnStreamSegments(&ssn->client); StreamTcpReturnStreamSegments(&ssn->server); SCReturn; } Commit Message: stream: support RST getting lost/ignored In case of a valid RST on a SYN, the state is switched to 'TCP_CLOSED'. However, the target of the RST may not have received it, or may not have accepted it. Also, the RST may have been injected, so the supposed sender may not actually be aware of the RST that was sent in it's name. In this case the previous behavior was to switch the state to CLOSED and accept no further TCP updates or stream reassembly. This patch changes this. It still switches the state to CLOSED, as this is by far the most likely to be correct. However, it will reconsider the state if the receiver continues to talk. To do this on each state change the previous state will be recorded in TcpSession::pstate. If a non-RST packet is received after a RST, this TcpSession::pstate is used to try to continue the conversation. If the (supposed) sender of the RST is also continueing the conversation as normal, it's highly likely it didn't send the RST. In this case a stream event is generated. Ticket: #2501 Reported-By: Kirill Shipulin 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 PDFiumEngine::FinishPaint(int progressive_index, pp::ImageData* image_data) { DCHECK_GE(progressive_index, 0); DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size()); DCHECK(image_data); int page_index = progressive_paints_[progressive_index].page_index; const pp::Rect& dirty_in_screen = progressive_paints_[progressive_index].rect; FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap; int start_x, start_y, size_x, size_y; GetPDFiumRect(page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y); FPDF_FFLDraw(form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x, size_y, current_rotation_, GetRenderingFlags()); FillPageSides(progressive_index); PaintPageShadow(progressive_index, image_data); DrawSelections(progressive_index, image_data); FPDF_RenderPage_Close(pages_[page_index]->GetPage()); FPDFBitmap_Destroy(bitmap); progressive_paints_.erase(progressive_paints_.begin() + progressive_index); client_->DocumentPaintOccurred(); } Commit Message: [pdf] Use a temporary list when unloading pages When traversing the |deferred_page_unloads_| list and handling the unloads it's possible for new pages to get added to the list which will invalidate the iterator. This CL swaps the list with an empty list and does the iteration on the list copy. New items that are unloaded while handling the defers will be unloaded at a later point. Bug: 780450 Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac Reviewed-on: https://chromium-review.googlesource.com/758916 Commit-Queue: dsinclair <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#515056} 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 Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char* Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) //should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = new (std::nothrow) char[len+1]; if (dst == NULL) return -1; strcpy(dst, src); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: void f2fs_invalidate_page(struct page *page, unsigned int offset, unsigned int length) { struct inode *inode = page->mapping->host; struct f2fs_sb_info *sbi = F2FS_I_SB(inode); if (inode->i_ino >= F2FS_ROOT_INO(sbi) && (offset % PAGE_SIZE || length != PAGE_SIZE)) return; if (PageDirty(page)) { if (inode->i_ino == F2FS_META_INO(sbi)) { dec_page_count(sbi, F2FS_DIRTY_META); } else if (inode->i_ino == F2FS_NODE_INO(sbi)) { dec_page_count(sbi, F2FS_DIRTY_NODES); } else { inode_dec_dirty_pages(inode); remove_dirty_inode(inode); } } /* This is atomic written page, keep Private */ if (IS_ATOMIC_WRITTEN_PAGE(page)) return; set_page_private(page, 0); ClearPagePrivate(page); } Commit Message: f2fs: fix a dead loop in f2fs_fiemap() A dead loop can be triggered in f2fs_fiemap() using the test case as below: ... fd = open(); fallocate(fd, 0, 0, 4294967296); ioctl(fd, FS_IOC_FIEMAP, fiemap_buf); ... It's caused by an overflow in __get_data_block(): ... bh->b_size = map.m_len << inode->i_blkbits; ... map.m_len is an unsigned int, and bh->b_size is a size_t which is 64 bits on 64 bits archtecture, type conversion from an unsigned int to a size_t will result in an overflow. In the above-mentioned case, bh->b_size will be zero, and f2fs_fiemap() will call get_data_block() at block 0 again an again. Fix this by adding a force conversion before left shift. Signed-off-by: Wei Fang <[email protected]> Acked-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> 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: static int __net_init netdev_init(struct net *net) { if (net != &init_net) INIT_LIST_HEAD(&net->dev_base_head); net->dev_name_head = netdev_create_hash(); if (net->dev_name_head == NULL) goto err_name; net->dev_index_head = netdev_create_hash(); if (net->dev_index_head == NULL) goto err_idx; return 0; err_idx: kfree(net->dev_name_head); err_name: return -ENOMEM; } 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 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 __skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps, struct sock *sk, int tstype) { struct sk_buff *skb; bool tsonly; if (!sk) return; tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY; if (!skb_may_tx_timestamp(sk, tsonly)) return; if (tsonly) { #ifdef CONFIG_INET if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) && sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) skb = tcp_get_timestamping_opt_stats(sk); else #endif skb = alloc_skb(0, GFP_ATOMIC); } else { skb = skb_clone(orig_skb, GFP_ATOMIC); } if (!skb) return; if (tsonly) { skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags; skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey; } if (hwtstamps) *skb_hwtstamps(skb) = *hwtstamps; else skb->tstamp = ktime_get_real(); __skb_complete_tx_timestamp(skb, sk, tstype); } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: static void tcp_try_keep_open(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int state = TCP_CA_Open; if (tcp_left_out(tp) || tcp_any_retrans_done(sk)) state = TCP_CA_Disorder; if (inet_csk(sk)->icsk_ca_state != state) { tcp_set_ca_state(sk, state); tp->high_seq = tp->snd_nxt; } } Commit Message: tcp: drop SYN+FIN messages Denys Fedoryshchenko reported that SYN+FIN attacks were bringing his linux machines to their limits. Dont call conn_request() if the TCP flags includes SYN flag Reported-by: Denys Fedoryshchenko <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[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: const CuePoint* Cues::GetLast() const { if (m_cue_points == NULL) return NULL; if (m_count <= 0) return NULL; #if 0 LoadCuePoint(); //init cues const size_t count = m_count + m_preload_count; if (count == 0) //weird return NULL; const size_t index = count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); pCP->Load(m_pSegment->m_pReader); assert(pCP->GetTimeCode() >= 0); #else const long index = m_count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); assert(pCP->GetTimeCode() >= 0); #endif return pCP; } 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 void InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y, ExceptionInfo *exception) { size_t bit; ssize_t x; register Quantum *q; Quantum index; index=0; switch (depth) { case 1: /* Convert bitmap scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } (void) SyncAuthenticPixels(image,exception); break; } case 2: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } } p++; } (void) SyncAuthenticPixels(image,exception); break; } case 4: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } (void) SyncAuthenticPixels(image,exception); break; } case 8: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p,exception); SetPixelIndex(image,index,q); p++; q+=GetPixelChannels(image); } (void) SyncAuthenticPixels(image,exception); break; } } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1162 CWE ID: CWE-787 Target: 1 Example 2: Code: void WebGLRenderingContextBase::vertexAttrib3fv(GLuint index, const Vector<GLfloat>& v) { if (isContextLost()) return; if (v.size() < 3) { SynthesizeGLError(GL_INVALID_VALUE, "vertexAttrib3fv", "invalid array"); return; } ContextGL()->VertexAttrib3fv(index, v.data()); SetVertexAttribType(index, kFloat32ArrayType); } 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 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 qeth_qdio_start_poll(struct ccw_device *ccwdev, int queue, unsigned long card_ptr) { struct qeth_card *card = (struct qeth_card *)card_ptr; if (card->dev && (card->dev->flags & IFF_UP)) napi_schedule(&card->napi); } Commit Message: qeth: avoid buffer overflow in snmp ioctl Check user-defined length in snmp ioctl request and allow request only if it fits into a qeth command buffer. Signed-off-by: Ursula Braun <[email protected]> Signed-off-by: Frank Blaschka <[email protected]> Reviewed-by: Heiko Carstens <[email protected]> Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Cc: <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: PHP_FUNCTION( locale_get_keywords ) { UEnumeration* e = NULL; UErrorCode status = U_ZERO_ERROR; const char* kw_key = NULL; int32_t kw_key_len = 0; const char* loc_name = NULL; int loc_name_len = 0; /* ICU expects the buffer to be allocated before calling the function and so the buffer size has been explicitly specified ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 hence the kw_value buffer size is 100 */ char* kw_value = NULL; int32_t kw_value_len = 100; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Get the keywords */ e = uloc_openKeywords( loc_name, &status ); if( e != NULL ) { /* Traverse it, filling the return array. */ array_init( return_value ); while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){ kw_value = ecalloc( 1 , kw_value_len ); /* Get the keyword value for each keyword */ kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status ); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; kw_value = erealloc( kw_value , kw_value_len+1); kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status ); } else if(!U_FAILURE(status)) { kw_value = erealloc( kw_value , kw_value_len+1); } if (U_FAILURE(status)) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC ); if( kw_value){ efree( kw_value ); } zval_dtor(return_value); RETURN_FALSE; } add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0); } /* end of while */ } /* end of if e!=NULL */ uenum_close( e ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125 Target: 1 Example 2: Code: bool WebMediaPlayerImpl::HasSingleSecurityOrigin() const { if (demuxer_found_hls_) { return false; } if (data_source_) return data_source_->HasSingleOrigin(); return true; } 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 PassOwnPtr<FrameProgressTracker> create(Frame* frame) { return adoptPtr(new FrameProgressTracker(frame)); } Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created. BUG=281256 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23620020 git-svn-id: svn://svn.chromium.org/blink/trunk@157196 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: MediaStreamManagerTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) { audio_manager_ = std::make_unique<MockAudioManager>(); audio_system_ = std::make_unique<media::AudioSystemImpl>(audio_manager_.get()); auto video_capture_provider = std::make_unique<MockVideoCaptureProvider>(); video_capture_provider_ = video_capture_provider.get(); media_stream_manager_ = std::make_unique<MediaStreamManager>( audio_system_.get(), audio_manager_->GetTaskRunner(), std::move(video_capture_provider)); base::RunLoop().RunUntilIdle(); ON_CALL(*video_capture_provider_, DoGetDeviceInfosAsync(_)) .WillByDefault(Invoke( [](VideoCaptureProvider::GetDeviceInfosCallback& result_callback) { std::vector<media::VideoCaptureDeviceInfo> stub_results; base::ResetAndReturn(&result_callback).Run(stub_results); })); } Commit Message: Fix MediaObserver notifications in MediaStreamManager. This CL fixes the stream type used to notify MediaObserver about cancelled MediaStream requests. Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate that all stream types should be cancelled. However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this way and the request to update the UI is ignored. This CL sends a separate notification for each stream type so that the UI actually gets updated for all stream types in use. Bug: 816033 Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405 Reviewed-on: https://chromium-review.googlesource.com/939630 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#540122} CWE ID: CWE-20 Target: 1 Example 2: Code: static ssize_t tty_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct tty_struct *tty = file_tty(file); struct tty_ldisc *ld; ssize_t ret; if (tty_paranoia_check(tty, file_inode(file), "tty_write")) return -EIO; if (!tty || !tty->ops->write || (test_bit(TTY_IO_ERROR, &tty->flags))) return -EIO; /* Short term debug to catch buggy drivers */ if (tty->ops->write_room == NULL) tty_err(tty, "missing write_room method\n"); ld = tty_ldisc_ref_wait(tty); if (!ld->ops->write) ret = -EIO; else ret = do_tty_write(ld->ops->write, tty, file, buf, count); tty_ldisc_deref(ld); return ret; } Commit Message: tty: Fix unsafe ldisc reference via ioctl(TIOCGETD) ioctl(TIOCGETD) retrieves the line discipline id directly from the ldisc because the line discipline id (c_line) in termios is untrustworthy; userspace may have set termios via ioctl(TCSETS*) without actually changing the line discipline via ioctl(TIOCSETD). However, directly accessing the current ldisc via tty->ldisc is unsafe; the ldisc ptr dereferenced may be stale if the line discipline is changing via ioctl(TIOCSETD) or hangup. Wait for the line discipline reference (just like read() or write()) to retrieve the "current" line discipline id. Cc: <[email protected]> Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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: bool OMXNodeInstance::handleMessage(omx_message &msg) { const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (msg.type == omx_message::FILL_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.extended_buffer_data.buffer); { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( FBD, WITH_STATS(FULL_BUFFER( msg.u.extended_buffer_data.buffer, buffer, msg.fenceFd))); unbumpDebugLevel_l(kPortIndexOutput); } BufferMeta *buffer_meta = static_cast<BufferMeta *>(buffer->pAppPrivate); if (buffer->nOffset + buffer->nFilledLen < buffer->nOffset || buffer->nOffset + buffer->nFilledLen > buffer->nAllocLen) { CLOG_ERROR(onFillBufferDone, OMX_ErrorBadParameter, FULL_BUFFER(NULL, buffer, msg.fenceFd)); } buffer_meta->CopyFromOMX(buffer); if (bufferSource != NULL) { bufferSource->codecBufferFilled(buffer); msg.u.extended_buffer_data.timestamp = buffer->nTimeStamp; } } else if (msg.type == omx_message::EMPTY_BUFFER_DONE) { OMX_BUFFERHEADERTYPE *buffer = findBufferHeader(msg.u.buffer_data.buffer); { Mutex::Autolock _l(mDebugLock); mInputBuffersWithCodec.remove(buffer); CLOG_BUMPED_BUFFER( EBD, WITH_STATS(EMPTY_BUFFER(msg.u.buffer_data.buffer, buffer, msg.fenceFd))); } if (bufferSource != NULL) { bufferSource->codecBufferEmptied(buffer, msg.fenceFd); return true; } } return false; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 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: pch_write_line (lin line, FILE *file) { bool after_newline = p_line[line][p_len[line] - 1] == '\n'; if (! fwrite (p_line[line], sizeof (*p_line[line]), p_len[line], file)) write_fatal (); return after_newline; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: void InlineLoginHandlerImpl::CloseTab(bool show_account_management) { content::WebContents* tab = web_ui()->GetWebContents(); Browser* browser = chrome::FindBrowserWithWebContents(tab); if (browser) { TabStripModel* tab_strip_model = browser->tab_strip_model(); if (tab_strip_model) { int index = tab_strip_model->GetIndexOfWebContents(tab); if (index != TabStripModel::kNoTab) { tab_strip_model->ExecuteContextMenuCommand( index, TabStripModel::CommandCloseTab); } } if (show_account_management) { browser->window()->ShowAvatarBubbleFromAvatarButton( BrowserWindow::AVATAR_BUBBLE_MODE_ACCOUNT_MANAGEMENT, signin::ManageAccountsParams(), signin_metrics::AccessPoint::ACCESS_POINT_AVATAR_BUBBLE_SIGN_IN, false); } } } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} 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: flush_signal_handlers(struct task_struct *t, int force_default) { int i; struct k_sigaction *ka = &t->sighand->action[0]; for (i = _NSIG ; i != 0 ; i--) { if (force_default || ka->sa.sa_handler != SIG_IGN) ka->sa.sa_handler = SIG_DFL; ka->sa.sa_flags = 0; sigemptyset(&ka->sa.sa_mask); ka++; } } Commit Message: signal: always clear sa_restorer on execve When the new signal handlers are set up, the location of sa_restorer is not cleared, leaking a parent process's address space location to children. This allows for a potential bypass of the parent's ASLR by examining the sa_restorer value returned when calling sigaction(). Based on what should be considered "secret" about addresses, it only matters across the exec not the fork (since the VMAs haven't changed until the exec). But since exec sets SIG_DFL and keeps sa_restorer, this is where it should be fixed. Given the few uses of sa_restorer, a "set" function was not written since this would be the only use. Instead, we use __ARCH_HAS_SA_RESTORER, as already done in other places. Example of the leak before applying this patch: $ cat /proc/$$/maps ... 7fb9f3083000-7fb9f3238000 r-xp 00000000 fd:01 404469 .../libc-2.15.so ... $ ./leak ... 7f278bc74000-7f278be29000 r-xp 00000000 fd:01 404469 .../libc-2.15.so ... 1 0 (nil) 0x7fb9f30b94a0 2 4000000 (nil) 0x7f278bcaa4a0 3 4000000 (nil) 0x7f278bcaa4a0 4 0 (nil) 0x7fb9f30b94a0 ... [[email protected]: use SA_RESTORER for backportability] Signed-off-by: Kees Cook <[email protected]> Reported-by: Emese Revfy <[email protected]> Cc: Emese Revfy <[email protected]> Cc: PaX Team <[email protected]> Cc: Al Viro <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: Serge Hallyn <[email protected]> Cc: Julien Tinnes <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[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: void SoftG711::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nFilledLen > kMaxNumSamplesPerFrame) { ALOGE("input buffer too large (%d).", inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; } const uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset; if (mIsMLaw) { DecodeMLaw( reinterpret_cast<int16_t *>(outHeader->pBuffer), inputptr, inHeader->nFilledLen); } else { DecodeALaw( reinterpret_cast<int16_t *>(outHeader->pBuffer), inputptr, inHeader->nFilledLen); } outHeader->nTimeStamp = inHeader->nTimeStamp; outHeader->nOffset = 0; outHeader->nFilledLen = inHeader->nFilledLen * sizeof(int16_t); outHeader->nFlags = 0; inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } } Commit Message: codecs: check OMX buffer size before use in (gsm|g711)dec Bug: 27793163 Bug: 27793367 Change-Id: Iec3de8a237ee2379d87a8371c13e543878c6652c CWE ID: CWE-119 Target: 1 Example 2: Code: bool DocumentLoader::isLoadingInAPISense() const { if (frameLoader()->state() != FrameStateComplete) { if (m_frame->settings()->needsIsLoadingInAPISenseQuirk() && !m_subresourceLoaders.isEmpty()) return true; Document* doc = m_frame->document(); if ((isLoadingMainResource() || !m_frame->document()->loadEventFinished()) && isLoading()) return true; if (m_cachedResourceLoader->requestCount()) return true; if (doc->processingLoadEvent()) return true; if (doc->hasActiveParser()) return true; } return frameLoader()->subframeIsLoading(); } Commit Message: Unreviewed, rolling out r147402. http://trac.webkit.org/changeset/147402 https://bugs.webkit.org/show_bug.cgi?id=112903 Source/WebCore: * dom/Document.cpp: (WebCore::Document::processHttpEquiv): * loader/DocumentLoader.cpp: (WebCore::DocumentLoader::responseReceived): LayoutTests: * http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html: * http/tests/security/XFrameOptions/x-frame-options-deny.html: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: * http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt: * platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt: git-svn-id: svn://svn.chromium.org/blink/trunk@147450 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: bool omx_vdec::allocate_input_done(void) { bool bRet = false; unsigned i=0; if (m_inp_mem_ptr == NULL) { return bRet; } if (m_inp_mem_ptr ) { for (; i<drv_ctx.ip_buf.actualcount; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } } if (i == drv_ctx.ip_buf.actualcount) { bRet = true; DEBUG_PRINT_HIGH("Allocate done for all i/p buffers"); } if (i==drv_ctx.ip_buf.actualcount && m_inp_bEnabled) { m_inp_bPopulated = OMX_TRUE; } return bRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e 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: bit_catenate(VarBit *arg1, VarBit *arg2) { VarBit *result; int bitlen1, bitlen2, bytelen, bit1pad, bit2shift; bits8 *pr, *pa; bitlen1 = VARBITLEN(arg1); bitlen2 = VARBITLEN(arg2); bytelen = VARBITTOTALLEN(bitlen1 + bitlen2); result = (VarBit *) palloc(bytelen); SET_VARSIZE(result, bytelen); VARBITLEN(result) = bitlen1 + bitlen2; /* Copy the first bitstring in */ memcpy(VARBITS(result), VARBITS(arg1), VARBITBYTES(arg1)); /* Copy the second bit string */ bit1pad = VARBITPAD(arg1); if (bit1pad == 0) { memcpy(VARBITS(result) + VARBITBYTES(arg1), VARBITS(arg2), VARBITBYTES(arg2)); } else if (bitlen2 > 0) { /* We need to shift all the bits to fit */ bit2shift = BITS_PER_BYTE - bit1pad; pr = VARBITS(result) + VARBITBYTES(arg1) - 1; for (pa = VARBITS(arg2); pa < VARBITEND(arg2); pa++) { *pr |= ((*pa >> bit2shift) & BITMASK); pr++; if (pr < VARBITEND(result)) *pr = (*pa << bit1pad) & BITMASK; } } return result; } 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: CCLayerTreeHostTestSetNeedsRedraw() : m_numCommits(0) , m_numDraws(0) { } Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests https://bugs.webkit.org/show_bug.cgi?id=70161 Reviewed by David Levin. Source/WebCore: Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was destroyed. This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the CCThreadProxy have been drained. Covered by the now-enabled CCLayerTreeHostTest* unit tests. * WebCore.gypi: * platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added. (WebCore::CCScopedMainThreadProxy::create): (WebCore::CCScopedMainThreadProxy::postTask): (WebCore::CCScopedMainThreadProxy::shutdown): (WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy): (WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown): * platform/graphics/chromium/cc/CCThreadProxy.cpp: (WebCore::CCThreadProxy::CCThreadProxy): (WebCore::CCThreadProxy::~CCThreadProxy): (WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread): * platform/graphics/chromium/cc/CCThreadProxy.h: Source/WebKit/chromium: Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor thread scheduling draws by itself. * tests/CCLayerTreeHostTest.cpp: (::CCLayerTreeHostTest::timeout): (::CCLayerTreeHostTest::clearTimeout): (::CCLayerTreeHostTest::CCLayerTreeHostTest): (::CCLayerTreeHostTest::onEndTest): (::CCLayerTreeHostTest::TimeoutTask::TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::clearTest): (::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::Run): (::CCLayerTreeHostTest::runTest): (::CCLayerTreeHostTest::doBeginTest): (::CCLayerTreeHostTestThreadOnly::runTest): (::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread): git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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 scsi_dma_restart_bh(void *opaque) { SCSIDiskState *s = opaque; SCSIRequest *req; SCSIDiskReq *r; qemu_bh_delete(s->bh); s->bh = NULL; QTAILQ_FOREACH(req, &s->qdev.requests, next) { r = DO_UPCAST(SCSIDiskReq, req, req); if (r->status & SCSI_REQ_STATUS_RETRY) { int status = r->status; int ret; r->status &= ~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK); switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) { case SCSI_REQ_STATUS_RETRY_READ: scsi_read_data(&r->req); break; case SCSI_REQ_STATUS_RETRY_WRITE: scsi_write_data(&r->req); break; case SCSI_REQ_STATUS_RETRY_FLUSH: ret = scsi_disk_emulate_command(r, r->iov.iov_base); if (ret == 0) { scsi_req_complete(&r->req, GOOD); } } } } } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[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 Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: { if (header.bits_per_pixel != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case StaticColor: case PseudoColor: { if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) || (header.ncolors == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case TrueColor: case DirectColor: { if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) && (header.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: { if (header.pixmap_depth != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case XYPixmap: case ZPixmap: { if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.bitmap_pad) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_unit) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.byte_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_bit_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (header.ncolors > 65535) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); length=(size_t) (header.header_size-sz_XWDheader); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; colors=(XColor *) AcquireQuantumMemory((size_t) header.ncolors, sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask,exception); SetPixelRed(image,ScaleShortToQuantum( colors[(ssize_t) index].red),q); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask,exception); SetPixelGreen(image,ScaleShortToQuantum( colors[(ssize_t) index].green),q); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask,exception); SetPixelBlue(image,ScaleShortToQuantum( colors[(ssize_t) index].blue),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(image,ScaleShortToQuantum((unsigned short) color),q); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(image,ScaleShortToQuantum((unsigned short) color), q); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(image,ScaleShortToQuantum((unsigned short) color),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleShortToQuantum( colors[i].red); image->colormap[i].green=(MagickRealType) ScaleShortToQuantum( colors[i].green); image->colormap[i].blue=(MagickRealType) ScaleShortToQuantum( colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=(Quantum) ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y),exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1553 CWE ID: CWE-125 Target: 1 Example 2: Code: static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, void *val, int bytes) { struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0]; memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len)); return X86EMUL_CONTINUE; } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 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 RenderWidgetHostImpl::ForwardEmulatedGestureEvent( const blink::WebGestureEvent& gesture_event) { ForwardGestureEvent(gesture_event); } Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI BUG=590284 Review URL: https://codereview.chromium.org/1747183002 Cr-Commit-Position: refs/heads/master@{#378844} 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 ssize_t driver_override_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct platform_device *pdev = to_platform_device(dev); char *driver_override, *old = pdev->driver_override, *cp; if (count > PATH_MAX) return -EINVAL; driver_override = kstrndup(buf, count, GFP_KERNEL); if (!driver_override) return -ENOMEM; cp = strchr(driver_override, '\n'); if (cp) *cp = '\0'; if (strlen(driver_override)) { pdev->driver_override = driver_override; } else { kfree(driver_override); pdev->driver_override = NULL; } kfree(old); return count; } Commit Message: driver core: platform: fix race condition with driver_override The driver_override implementation is susceptible to race condition when different threads are reading vs storing a different driver override. Add locking to avoid race condition. Fixes: 3d713e0e382e ("driver core: platform: add device binding path 'driver_override'") Cc: [email protected] Signed-off-by: Adrian Salido <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: int git_smart__negotiate_fetch(git_transport *transport, git_repository *repo, const git_remote_head * const *wants, size_t count) { transport_smart *t = (transport_smart *)transport; gitno_buffer *buf = &t->buffer; git_buf data = GIT_BUF_INIT; git_revwalk *walk = NULL; int error = -1, pkt_type; unsigned int i; git_oid oid; if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0) return error; if ((error = fetch_setup_walk(&walk, repo)) < 0) goto on_error; /* * Our support for ACK extensions is simply to parse them. On * the first ACK we will accept that as enough common * objects. We give up if we haven't found an answer in the * first 256 we send. */ i = 0; while (i < 256) { error = git_revwalk_next(&oid, walk); if (error < 0) { if (GIT_ITEROVER == error) break; goto on_error; } git_pkt_buffer_have(&oid, &data); i++; if (i % 20 == 0) { if (t->cancelled.val) { giterr_set(GITERR_NET, "The fetch was cancelled by the user"); error = GIT_EUSER; goto on_error; } git_pkt_buffer_flush(&data); if (git_buf_oom(&data)) { error = -1; goto on_error; } if ((error = git_smart__negotiation_step(&t->parent, data.ptr, data.size)) < 0) goto on_error; git_buf_clear(&data); if (t->caps.multi_ack || t->caps.multi_ack_detailed) { if ((error = store_common(t)) < 0) goto on_error; } else { pkt_type = recv_pkt(NULL, buf); if (pkt_type == GIT_PKT_ACK) { break; } else if (pkt_type == GIT_PKT_NAK) { continue; } else if (pkt_type < 0) { /* recv_pkt returned an error */ error = pkt_type; goto on_error; } else { giterr_set(GITERR_NET, "Unexpected pkt type"); error = -1; goto on_error; } } } if (t->common.length > 0) break; if (i % 20 == 0 && t->rpc) { git_pkt_ack *pkt; unsigned int j; if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0) goto on_error; git_vector_foreach(&t->common, j, pkt) { if ((error = git_pkt_buffer_have(&pkt->oid, &data)) < 0) goto on_error; } if (git_buf_oom(&data)) { error = -1; goto on_error; } } } /* Tell the other end that we're done negotiating */ if (t->rpc && t->common.length > 0) { git_pkt_ack *pkt; unsigned int j; if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0) goto on_error; git_vector_foreach(&t->common, j, pkt) { if ((error = git_pkt_buffer_have(&pkt->oid, &data)) < 0) goto on_error; } if (git_buf_oom(&data)) { error = -1; goto on_error; } } if ((error = git_pkt_buffer_done(&data)) < 0) goto on_error; if (t->cancelled.val) { giterr_set(GITERR_NET, "The fetch was cancelled by the user"); error = GIT_EUSER; goto on_error; } if ((error = git_smart__negotiation_step(&t->parent, data.ptr, data.size)) < 0) goto on_error; git_buf_free(&data); git_revwalk_free(walk); /* Now let's eat up whatever the server gives us */ if (!t->caps.multi_ack && !t->caps.multi_ack_detailed) { pkt_type = recv_pkt(NULL, buf); if (pkt_type < 0) { return pkt_type; } else if (pkt_type != GIT_PKT_ACK && pkt_type != GIT_PKT_NAK) { giterr_set(GITERR_NET, "Unexpected pkt type"); return -1; } } else { error = wait_while_ack(buf); } return error; on_error: git_revwalk_free(walk); git_buf_free(&data); return error; } Commit Message: smart_pkt: treat empty packet lines as error The Git protocol does not specify what should happen in the case of an empty packet line (that is a packet line "0004"). We currently indicate success, but do not return a packet in the case where we hit an empty line. The smart protocol was not prepared to handle such packets in all cases, though, resulting in a `NULL` pointer dereference. Fix the issue by returning an error instead. As such kind of packets is not even specified by upstream, this is the right thing to do. 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: void Cues::PreloadCuePoint( long& cue_points_size, long long pos) const { assert(m_count == 0); if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2*cue_points_size; CuePoint** const qq = new CuePoint*[n]; CuePoint** q = qq; //beginning of target CuePoint** p = m_cue_points; //beginning of source CuePoint** const pp = p + m_preload_count; //end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new CuePoint(m_preload_count, pos); m_cue_points[m_preload_count++] = pCP; } Commit Message: 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: void RunScrollbarThumbDragLatencyTest() { #if !defined(OS_ANDROID) blink::WebFloatPoint scrollbar_thumb(795, 30); blink::WebMouseEvent mouse_down = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseDown, scrollbar_thumb.x, scrollbar_thumb.y, 0); mouse_down.button = blink::WebMouseEvent::Button::kLeft; mouse_down.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_down); blink::WebMouseEvent mouse_move = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseMove, scrollbar_thumb.x, scrollbar_thumb.y + 10, 0); mouse_move.button = blink::WebMouseEvent::Button::kLeft; mouse_move.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_move); RunUntilInputProcessed(GetWidgetHost()); mouse_move.SetPositionInWidget(scrollbar_thumb.x, scrollbar_thumb.y + 20); mouse_move.SetPositionInScreen(scrollbar_thumb.x, scrollbar_thumb.y + 20); GetWidgetHost()->ForwardMouseEvent(mouse_move); RunUntilInputProcessed(GetWidgetHost()); blink::WebMouseEvent mouse_up = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseUp, scrollbar_thumb.x, scrollbar_thumb.y + 20, 0); mouse_up.button = blink::WebMouseEvent::Button::kLeft; mouse_up.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_up); RunUntilInputProcessed(GetWidgetHost()); FetchHistogramsFromChildProcesses(); const std::string scroll_types[] = {"ScrollBegin", "ScrollUpdate"}; for (const std::string& scroll_type : scroll_types) { EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.TimeToScrollUpdateSwapBegin4")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.RendererSwapToBrowserNotified2")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.BrowserNotifiedToBeforeGpuSwap2")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.GpuSwap2")); std::string thread_name = DoesScrollbarScrollOnMainThread() ? "Main" : "Impl"; EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.TimeToHandled2_" + thread_name)); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.HandledToRendererSwap2_" + thread_name)); } #endif // !defined(OS_ANDROID) } Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures" This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2. Reason for revert: Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the culprit for flakes in the build cycles as shown on: https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818 Sample Failed Step: content_browsertests on Ubuntu-16.04 Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency Original change's description: > Add explicit flag for compositor scrollbar injected gestures > > The original change to enable scrollbar latency for the composited > scrollbars incorrectly used an existing member to try and determine > whether a GestureScrollUpdate was the first one in an injected sequence > or not. is_first_gesture_scroll_update_ was incorrect because it is only > updated when input is actually dispatched to InputHandlerProxy, and the > flag is cleared for all GSUs before the location where it was being > read. > > This bug was missed because of incorrect tests. The > VerifyRecordedSamplesForHistogram method doesn't actually assert or > expect anything - the return value must be inspected. > > As part of fixing up the tests, I made a few other changes to get them > passing consistently across all platforms: > - turn on main thread scrollbar injection feature (in case it's ever > turned off we don't want the tests to start failing) > - enable mock scrollbars > - disable smooth scrolling > - don't run scrollbar tests on Android > > The composited scrollbar button test is disabled due to a bug in how > the mock theme reports its button sizes, which throws off the region > detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed > crbug.com/974063 for this issue). > > Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950 > > Bug: 954007 > Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7 > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741 > Commit-Queue: Daniel Libby <[email protected]> > Reviewed-by: David Bokan <[email protected]> > Cr-Commit-Position: refs/heads/master@{#669086} Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 954007 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114 Cr-Commit-Position: refs/heads/master@{#669150} CWE ID: CWE-281 Target: 1 Example 2: Code: static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu) { /* return the page table to be shadowed - in our case, EPT12 */ return get_vmcs12(vcpu)->ept_pointer; } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[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: static inline int do_exception(struct pt_regs *regs, int access, unsigned long trans_exc_code) { struct task_struct *tsk; struct mm_struct *mm; struct vm_area_struct *vma; unsigned long address; unsigned int flags; int fault; if (notify_page_fault(regs)) return 0; tsk = current; mm = tsk->mm; /* * Verify that the fault happened in user space, that * we are not in an interrupt and that there is a * user context. */ fault = VM_FAULT_BADCONTEXT; if (unlikely(!user_space_fault(trans_exc_code) || in_atomic() || !mm)) goto out; address = trans_exc_code & __FAIL_ADDR_MASK; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address); flags = FAULT_FLAG_ALLOW_RETRY; if (access == VM_WRITE || (trans_exc_code & store_indication) == 0x400) flags |= FAULT_FLAG_WRITE; retry: down_read(&mm->mmap_sem); fault = VM_FAULT_BADMAP; vma = find_vma(mm, address); if (!vma) goto out_up; if (unlikely(vma->vm_start > address)) { if (!(vma->vm_flags & VM_GROWSDOWN)) goto out_up; if (expand_stack(vma, address)) goto out_up; } /* * Ok, we have a good vm_area for this memory access, so * we can handle it.. */ fault = VM_FAULT_BADACCESS; if (unlikely(!(vma->vm_flags & access))) goto out_up; if (is_vm_hugetlb_page(vma)) address &= HPAGE_MASK; /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault. */ fault = handle_mm_fault(mm, vma, address, flags); if (unlikely(fault & VM_FAULT_ERROR)) goto out_up; /* * Major/minor page fault accounting is only done on the * initial attempt. If we go through a retry, it is extremely * likely that the page will be found in page cache at that point. */ if (flags & FAULT_FLAG_ALLOW_RETRY) { if (fault & VM_FAULT_MAJOR) { tsk->maj_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, address); } else { tsk->min_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, address); } if (fault & VM_FAULT_RETRY) { /* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk * of starvation. */ flags &= ~FAULT_FLAG_ALLOW_RETRY; goto retry; } } /* * The instruction that caused the program check will * be repeated. Don't signal single step via SIGTRAP. */ clear_tsk_thread_flag(tsk, TIF_PER_TRAP); fault = 0; out_up: up_read(&mm->mmap_sem); out: return fault; } 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 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: error::Error GLES2DecoderImpl::HandleDrawElements( uint32 immediate_data_size, const gles2::DrawElements& c) { if (!bound_element_array_buffer_ || bound_element_array_buffer_->IsDeleted()) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: No element array buffer bound"); return error::kNoError; } GLenum mode = c.mode; GLsizei count = c.count; GLenum type = c.type; int32 offset = c.index_offset; if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: count < 0"); return error::kNoError; } if (offset < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: offset < 0"); return error::kNoError; } if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: mode GL_INVALID_ENUM"); return error::kNoError; } if (!validators_->index_type.IsValid(type)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: type GL_INVALID_ENUM"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawElements")) { return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed; if (!bound_element_array_buffer_->GetMaxValueForRange( offset, count, type, &max_vertex_accessed)) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: range out of bounds for buffer"); return error::kNoError; } if (IsDrawValid(max_vertex_accessed)) { bool simulated_attrib_0 = SimulateAttrib0(max_vertex_accessed); bool simulated_fixed_attribs = false; if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) { bool textures_set = SetBlackTextureForNonRenderableTextures(); ApplyDirtyState(); const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset); glDrawElements(mode, count, type, indices); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements."; return error::kLostContext; } } return error::kNoError; } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 [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 Target: 1 Example 2: Code: virDomainInterfaceAddresses(virDomainPtr dom, virDomainInterfacePtr **ifaces, unsigned int source, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "ifaces=%p, source=%d, flags=%x", ifaces, source, flags); virResetLastError(); if (ifaces) *ifaces = NULL; virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(ifaces, error); if (source == VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT) virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainInterfaceAddresses) { int ret; ret = dom->conn->driver->domainInterfaceAddresses(dom, ifaces, source, flags); if (ret < 0) goto error; return ret; } virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__); error: virDispatchError(dom->conn); return -1; } Commit Message: virDomainGetTime: Deny on RO connections We have a policy that if API may end up talking to a guest agent it should require RW connection. We don't obey the rule in virDomainGetTime(). Signed-off-by: Michal Privoznik <[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: GfxRadialShading::~GfxRadialShading() { int i; for (i = 0; i < nFuncs; ++i) { delete funcs[i]; } } Commit Message: CWE ID: CWE-189 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: scoped_refptr<BrowserContext> BrowserContextImpl::GetOffTheRecordContext() { if (!otr_context_) { OTRBrowserContextImpl* context = new OTRBrowserContextImpl( this, static_cast<BrowserContextIODataImpl *>(io_data())); otr_context_ = context->GetWeakPtr(); } return make_scoped_refptr(otr_context_.get()); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: int fpm_stdio_init_final() /* {{{ */ { if (fpm_use_error_log()) { /* prevent duping if logging to syslog */ if (fpm_globals.error_log_fd > 0 && fpm_globals.error_log_fd != STDERR_FILENO) { /* there might be messages to stderr from other parts of the code, we need to log them all */ if (0 > dup2(fpm_globals.error_log_fd, STDERR_FILENO)) { zlog(ZLOG_SYSERROR, "failed to init stdio: dup2()"); return -1; } } #ifdef HAVE_SYSLOG_H else if (fpm_globals.error_log_fd == ZLOG_SYSLOG) { /* dup to /dev/null when using syslog */ dup2(STDOUT_FILENO, STDERR_FILENO); } #endif } zlog_set_launched(); return 0; } /* }}} */ Commit Message: Fixed bug #73342 Directly listen on socket, instead of duping it to STDIN and listening on that. 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: bool Cues::LoadCuePoint() const { const long long stop = m_start + m_size; if (m_pos >= stop) return false; // nothing else to do Init(); IMkvReader* const pReader = m_pSegment->m_pReader; while (m_pos < stop) { const long long idpos = m_pos; long len; const long long id = ReadUInt(pReader, m_pos, len); assert(id >= 0); // TODO assert((m_pos + len) <= stop); m_pos += len; // consume ID const long long size = ReadUInt(pReader, m_pos, len); assert(size >= 0); assert((m_pos + len) <= stop); m_pos += len; // consume Size field assert((m_pos + size) <= stop); if (id != 0x3B) { // CuePoint ID m_pos += size; // consume payload assert(m_pos <= stop); continue; } assert(m_preload_count > 0); CuePoint* const pCP = m_cue_points[m_count]; assert(pCP); assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) return false; pCP->Load(pReader); ++m_count; --m_preload_count; m_pos += size; // consume payload assert(m_pos <= stop); return true; // yes, we loaded a cue point } } 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: static int __init balloon_init(void) { if (!xen_domain()) return -ENODEV; pr_info("Initialising balloon driver\n"); #ifdef CONFIG_XEN_PV balloon_stats.current_pages = xen_pv_domain() ? min(xen_start_info->nr_pages - xen_released_pages, max_pfn) : get_num_physpages(); #else balloon_stats.current_pages = get_num_physpages(); #endif balloon_stats.target_pages = balloon_stats.current_pages; balloon_stats.balloon_low = 0; balloon_stats.balloon_high = 0; balloon_stats.total_pages = balloon_stats.current_pages; balloon_stats.schedule_delay = 1; balloon_stats.max_schedule_delay = 32; balloon_stats.retry_count = 1; balloon_stats.max_retry_count = RETRY_UNLIMITED; #ifdef CONFIG_XEN_BALLOON_MEMORY_HOTPLUG set_online_page_callback(&xen_online_page); register_memory_notifier(&xen_memory_nb); register_sysctl_table(xen_root); #endif #ifdef CONFIG_XEN_PV { int i; /* * Initialize the balloon with pages from the extra memory * regions (see arch/x86/xen/setup.c). */ for (i = 0; i < XEN_EXTRA_MEM_MAX_REGIONS; i++) if (xen_extra_mem[i].n_pfns) balloon_add_region(xen_extra_mem[i].start_pfn, xen_extra_mem[i].n_pfns); } #endif /* Init the xen-balloon driver. */ xen_balloon_init(); return 0; } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400 Target: 1 Example 2: Code: MagickPrivate MagickBooleanType FxEvaluateExpression(FxInfo *fx_info, double *alpha,ExceptionInfo *exception) { MagickBooleanType status; status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha, exception); return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/296 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 nfs4_update_session(struct nfs4_session *session, struct nfs41_create_session_res *res) { nfs4_copy_sessionid(&session->sess_id, &res->sessionid); /* Mark client id and session as being confirmed */ session->clp->cl_exchange_flags |= EXCHGID4_FLAG_CONFIRMED_R; set_bit(NFS4_SESSION_ESTABLISHED, &session->session_state); session->flags = res->flags; memcpy(&session->fc_attrs, &res->fc_attrs, sizeof(session->fc_attrs)); if (res->flags & SESSION4_BACK_CHAN) memcpy(&session->bc_attrs, &res->bc_attrs, sizeof(session->bc_attrs)); } Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client ---Steps to Reproduce-- <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) <nfs-client> # mount -t nfs nfs-server:/nfs/ /mnt/ # ll /mnt/*/ <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) # service nfs restart <nfs-client> # ll /mnt/*/ --->>>>> oops here [ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null) [ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0 [ 5123.104131] Oops: 0000 [#1] [ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd] [ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214 [ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014 [ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000 [ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246 [ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240 [ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908 [ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000 [ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800 [ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240 [ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000 [ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0 [ 5123.112888] Stack: [ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000 [ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6 [ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800 [ 5123.115264] Call Trace: [ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4] [ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4] [ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4] [ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0 [ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70 [ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33 [ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.122308] RSP <ffff88005877fdb8> [ 5123.122942] CR2: 0000000000000000 Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops") Cc: [email protected] # v3.13+ Signed-off-by: Kinglong Mee <[email protected]> Signed-off-by: Trond Myklebust <[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: long Track::Create( Segment* pSegment, const Info& info, long long element_start, long long element_size, Track*& pResult) { if (pResult) return -1; Track* const pTrack = new (std::nothrow) Track(pSegment, element_start, element_size); if (pTrack == NULL) return -1; //generic error const int status = info.Copy(pTrack->m_info); if (status) // error { delete pTrack; return status; } pResult = pTrack; return 0; //success } 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 Target: 1 Example 2: Code: static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p) { } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <[email protected]> Analyzed-by: Vincent Guittot <[email protected]> Reported-by: Zhipeng Xie <[email protected]> Reported-by: Sargun Dhillon <[email protected]> Reported-by: Xie XiuQi <[email protected]> Tested-by: Zhipeng Xie <[email protected]> Tested-by: Sargun Dhillon <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Acked-by: Vincent Guittot <[email protected]> Cc: <[email protected]> # v4.13+ Cc: Bin Li <[email protected]> Cc: Mike Galbraith <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Tejun Heo <[email protected]> Cc: Thomas Gleixner <[email protected]> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[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: void DOMHandler::Wire(UberDispatcher* dispatcher) { DOM::Dispatcher::wire(dispatcher, this); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} 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(imageaffinematrixget) { double affine[6]; long type; zval *options = NULL; zval **tmp; int res = GD_FALSE, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) { return; } switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; if (!options || Z_TYPE_P(options) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_DOUBLE) { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); x = Z_DVAL(dval); } else { x = Z_DVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_DOUBLE) { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); y = Z_DVAL(dval); } else { y = Z_DVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; if (!options) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number is expected as option"); RETURN_FALSE; } if(Z_TYPE_P(options) != IS_DOUBLE) { zval dval; dval = *options; zval_copy_ctor(&dval); convert_to_double(&dval); angle = Z_DVAL(dval); } else { angle = Z_DVAL_P(options); } if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type); RETURN_FALSE; } if (res == GD_FALSE) { RETURN_FALSE; } else { array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, affine[i]); } } } Commit Message: Fix bug#72697 - select_colors write out-of-bounds CWE ID: CWE-787 Target: 1 Example 2: Code: BufferQueueConsumer::~BufferQueueConsumer() {} Commit Message: Add SN logging Bug 27046057 Change-Id: Iede7c92e59e60795df1ec7768ebafd6b090f1c27 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: void RenderWidgetHostViewGtk::OnDestroy(GtkWidget* widget) { DCHECK(is_fullscreen_); host_->Shutdown(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: 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: Core(const OAuthProviderInfo& info, net::URLRequestContextGetter* request_context_getter) : provider_info_(info), request_context_getter_(request_context_getter), delegate_(NULL) { } 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: bool TemplateURL::MatchesData(const TemplateURL* t_url, const TemplateURLData* data, const SearchTermsData& search_terms_data) { if (!t_url || !data) return !t_url && !data; return (t_url->short_name() == data->short_name()) && t_url->HasSameKeywordAs(*data, search_terms_data) && (t_url->url() == data->url()) && (t_url->suggestions_url() == data->suggestions_url) && (t_url->instant_url() == data->instant_url) && (t_url->image_url() == data->image_url) && (t_url->new_tab_url() == data->new_tab_url) && (t_url->search_url_post_params() == data->search_url_post_params) && (t_url->suggestions_url_post_params() == data->suggestions_url_post_params) && (t_url->instant_url_post_params() == data->instant_url_post_params) && (t_url->image_url_post_params() == data->image_url_post_params) && (t_url->favicon_url() == data->favicon_url) && (t_url->safe_for_autoreplace() == data->safe_for_autoreplace) && (t_url->show_in_default_list() == data->show_in_default_list) && (t_url->input_encodings() == data->input_encodings) && (t_url->alternate_urls() == data->alternate_urls) && (t_url->search_terms_replacement_key() == data->search_terms_replacement_key); } Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} 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 __init acpi_custom_method_init(void) { if (!acpi_debugfs_dir) return -ENOENT; cm_dentry = debugfs_create_file("custom_method", S_IWUSR, acpi_debugfs_dir, NULL, &cm_fops); if (!cm_dentry) return -ENODEV; return 0; } Commit Message: ACPI: Split out custom_method functionality into an own driver With /sys/kernel/debug/acpi/custom_method root can write to arbitrary memory and increase his priveleges, even if these are restricted. -> Make this an own debug .config option and warn about the security issue in the config description. -> Still keep acpi/debugfs.c which now only creates an empty /sys/kernel/debug/acpi directory. There might be other users of it later. Signed-off-by: Thomas Renninger <[email protected]> Acked-by: Rafael J. Wysocki <[email protected]> Acked-by: [email protected] Signed-off-by: Len Brown <[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: void UrlData::MergeFrom(const scoped_refptr<UrlData>& other) { if (ValidateDataOrigin(other->data_origin_)) { DCHECK(thread_checker_.CalledOnValidThread()); valid_until_ = std::max(valid_until_, other->valid_until_); set_length(other->length_); cacheable_ |= other->cacheable_; range_supported_ |= other->range_supported_; if (last_modified_.is_null()) { last_modified_ = other->last_modified_; } bytes_read_from_cache_ += other->bytes_read_from_cache_; set_has_opaque_data(other->has_opaque_data_); multibuffer()->MergeFrom(other->multibuffer()); } } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Target: 1 Example 2: Code: cf2_hintmap_insertHint( CF2_HintMap hintmap, CF2_Hint bottomHintEdge, CF2_Hint topHintEdge ) { CF2_UInt indexInsert; /* set default values, then check for edge hints */ FT_Bool isPair = TRUE; CF2_Hint firstHintEdge = bottomHintEdge; CF2_Hint secondHintEdge = topHintEdge; /* one or none of the input params may be invalid when dealing with */ /* edge hints; at least one edge must be valid */ FT_ASSERT( cf2_hint_isValid( bottomHintEdge ) || cf2_hint_isValid( topHintEdge ) ); /* determine how many and which edges to insert */ if ( !cf2_hint_isValid( bottomHintEdge ) ) { /* insert only the top edge */ firstHintEdge = topHintEdge; isPair = FALSE; } else if ( !cf2_hint_isValid( topHintEdge ) ) { /* insert only the bottom edge */ isPair = FALSE; } /* paired edges must be in proper order */ FT_ASSERT( !isPair || topHintEdge->csCoord >= bottomHintEdge->csCoord ); /* linear search to find index value of insertion point */ indexInsert = 0; for ( ; indexInsert < hintmap->count; indexInsert++ ) { if ( hintmap->edge[indexInsert].csCoord >= firstHintEdge->csCoord ) break; } /* * Discard any hints that overlap in character space. Most often, this * is while building the initial map, where captured hints from all * zones are combined. Define overlap to include hints that `touch' * (overlap zero). Hiragino Sans/Gothic fonts have numerous hints that * touch. Some fonts have non-ideographic glyphs that overlap our * synthetic hints. * * Overlap also occurs when darkening stem hints that are close. * */ if ( indexInsert < hintmap->count ) { /* we are inserting before an existing edge: */ /* verify that an existing edge is not the same */ if ( hintmap->edge[indexInsert].csCoord == firstHintEdge->csCoord ) return; /* ignore overlapping stem hint */ /* verify that a new pair does not straddle the next edge */ if ( isPair && hintmap->edge[indexInsert].csCoord <= secondHintEdge->csCoord ) return; /* ignore overlapping stem hint */ /* verify that we are not inserting between paired edges */ if ( cf2_hint_isPairTop( &hintmap->edge[indexInsert] ) ) return; /* ignore overlapping stem hint */ } /* recompute device space locations using initial hint map */ if ( cf2_hintmap_isValid( hintmap->initialHintMap ) && !cf2_hint_isLocked( firstHintEdge ) ) { if ( isPair ) { /* Use hint map to position the center of stem, and nominal scale */ /* to position the two edges. This preserves the stem width. */ CF2_Fixed midpoint = cf2_hintmap_map( hintmap->initialHintMap, ( secondHintEdge->csCoord + firstHintEdge->csCoord ) / 2 ); CF2_Fixed halfWidth = FT_MulFix( ( secondHintEdge->csCoord - firstHintEdge->csCoord ) / 2, hintmap->scale ); firstHintEdge->dsCoord = midpoint - halfWidth; secondHintEdge->dsCoord = midpoint + halfWidth; } else firstHintEdge->dsCoord = cf2_hintmap_map( hintmap->initialHintMap, firstHintEdge->csCoord ); } /* * Discard any hints that overlap in device space; this can occur * because locked hints have been moved to align with blue zones. * * TODO: Although we might correct this later during adjustment, we * don't currently have a way to delete a conflicting hint once it has * been inserted. See v2.030 MinionPro-Regular, 12 ppem darkened, * initial hint map for second path, glyph 945 (the perispomeni (tilde) * in U+1F6E, Greek omega with psili and perispomeni). Darkening is * 25. Pair 667,747 initially conflicts in design space with top edge * 660. This is because 667 maps to 7.87, and the top edge was * captured by a zone at 8.0. The pair is later successfully inserted * in a zone without the top edge. In this zone it is adjusted to 8.0, * and no longer conflicts with the top edge in design space. This * means it can be included in yet a later zone which does have the top * edge hint. This produces a small mismatch between the first and * last points of this path, even though the hint masks are the same. * The density map difference is tiny (1/256). * */ if ( indexInsert > 0 ) { /* we are inserting after an existing edge */ if ( firstHintEdge->dsCoord < hintmap->edge[indexInsert - 1].dsCoord ) return; } if ( indexInsert < hintmap->count ) { /* we are inserting before an existing edge */ if ( isPair ) { if ( secondHintEdge->dsCoord > hintmap->edge[indexInsert].dsCoord ) return; } else { if ( firstHintEdge->dsCoord > hintmap->edge[indexInsert].dsCoord ) return; } } /* make room to insert */ { CF2_Int iSrc = hintmap->count - 1; CF2_Int iDst = isPair ? hintmap->count + 1 : hintmap->count; CF2_Int count = hintmap->count - indexInsert; if ( iDst >= CF2_MAX_HINT_EDGES ) { FT_TRACE4(( "cf2_hintmap_insertHint: too many hintmaps\n" )); return; } while ( count-- ) hintmap->edge[iDst--] = hintmap->edge[iSrc--]; /* insert first edge */ hintmap->edge[indexInsert] = *firstHintEdge; /* copy struct */ hintmap->count += 1; if ( isPair ) { /* insert second edge */ hintmap->edge[indexInsert + 1] = *secondHintEdge; /* copy struct */ hintmap->count += 1; } } return; } 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: ExtensionOptionsGuest::~ExtensionOptionsGuest() { } Commit Message: Make extensions use a correct same-origin check. GURL::GetOrigin does not do the right thing for all types of URLs. BUG=573317 Review URL: https://codereview.chromium.org/1658913002 Cr-Commit-Position: refs/heads/master@{#373381} 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: BufferMeta(size_t size) : mSize(size), mIsBackup(false) { } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119 Target: 1 Example 2: Code: static void trace_consume(struct trace_iterator *iter) { ring_buffer_consume(iter->trace_buffer->buffer, iter->cpu, &iter->ts, &iter->lost_events); } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787 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: kvp_respond_to_host(char *key, char *value, int error) { struct hv_kvp_msg *kvp_msg; struct hv_kvp_msg_enumerate *kvp_data; char *key_name; struct icmsg_hdr *icmsghdrp; int keylen, valuelen; u32 buf_len; struct vmbus_channel *channel; u64 req_id; /* * If a transaction is not active; log and return. */ if (!kvp_transaction.active) { /* * This is a spurious call! */ pr_warn("KVP: Transaction not active\n"); return; } /* * Copy the global state for completing the transaction. Note that * only one transaction can be active at a time. */ buf_len = kvp_transaction.recv_len; channel = kvp_transaction.recv_channel; req_id = kvp_transaction.recv_req_id; kvp_transaction.active = false; if (channel->onchannel_callback == NULL) /* * We have raced with util driver being unloaded; * silently return. */ return; icmsghdrp = (struct icmsg_hdr *) &recv_buffer[sizeof(struct vmbuspipe_hdr)]; kvp_msg = (struct hv_kvp_msg *) &recv_buffer[sizeof(struct vmbuspipe_hdr) + sizeof(struct icmsg_hdr)]; kvp_data = &kvp_msg->kvp_data; key_name = key; /* * If the error parameter is set, terminate the host's enumeration. */ if (error) { /* * We don't support this index or the we have timedout; * terminate the host-side iteration by returning an error. */ icmsghdrp->status = HV_E_FAIL; goto response_done; } /* * The windows host expects the key/value pair to be encoded * in utf16. */ keylen = utf8s_to_utf16s(key_name, strlen(key_name), (wchar_t *)kvp_data->data.key); kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */ valuelen = utf8s_to_utf16s(value, strlen(value), (wchar_t *)kvp_data->data.value); kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */ kvp_data->data.value_type = REG_SZ; /* all our values are strings */ icmsghdrp->status = HV_S_OK; response_done: icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE; vmbus_sendpacket(channel, recv_buffer, buf_len, req_id, VM_PKT_DATA_INBAND, 0); } Commit Message: NLS: improve UTF8 -> UTF16 string conversion routine The utf8s_to_utf16s conversion routine needs to be improved. Unlike its utf16s_to_utf8s sibling, it doesn't accept arguments specifying the maximum length of the output buffer or the endianness of its 16-bit output. This patch (as1501) adds the two missing arguments, and adjusts the only two places in the kernel where the function is called. A follow-on patch will add a third caller that does utilize the new capabilities. The two conversion routines are still annoyingly inconsistent in the way they handle invalid byte combinations. But that's a subject for a different patch. Signed-off-by: Alan Stern <[email protected]> CC: Clemens Ladisch <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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 fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; const struct bpf_map_ops *ops; struct bpf_insn_aux_data *aux; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || insn->code == (BPF_ALU | BPF_MOD | BPF_X) || insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; struct bpf_insn mask_and_div[] = { BPF_MOV32_REG(insn->src_reg, insn->src_reg), /* Rx div 0 -> 0 */ BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2), BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), BPF_JMP_IMM(BPF_JA, 0, 0, 1), *insn, }; struct bpf_insn mask_and_mod[] = { BPF_MOV32_REG(insn->src_reg, insn->src_reg), /* Rx mod 0 -> Rx */ BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1), *insn, }; struct bpf_insn *patchlet; if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { patchlet = mask_and_div + (is64 ? 1 : 0); cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0); } else { patchlet = mask_and_mod + (is64 ? 1 : 0); cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0); } new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (BPF_CLASS(insn->code) == BPF_LD && (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND)) { cnt = env->ops->gen_ld_abs(insn, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->src_reg == BPF_PSEUDO_CALL) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_override_return) prog->kprobe_override = 1; if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; env->prog->aux->max_pkt_offset = MAX_PACKET_OFF; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; aux = &env->insn_aux_data[i + delta]; if (!bpf_map_ptr_unpriv(aux)) continue; /* instead of changing every JIT dealing with tail_call * emit two extra insns: * if (index >= max_entries) goto out; * index &= array->index_mask; * to avoid out-of-bounds cpu speculation */ if (bpf_map_ptr_poisoned(aux)) { verbose(env, "tail_call abusing map_ptr\n"); return -EINVAL; } map_ptr = BPF_MAP_PTR(aux->map_state); insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, map_ptr->max_entries, 2); insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, container_of(map_ptr, struct bpf_array, map)->index_mask); insn_buf[2] = *insn; cnt = 3; new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * and other inlining handlers are currently limited to 64 bit * only. */ if (prog->jit_requested && BITS_PER_LONG == 64 && (insn->imm == BPF_FUNC_map_lookup_elem || insn->imm == BPF_FUNC_map_update_elem || insn->imm == BPF_FUNC_map_delete_elem || insn->imm == BPF_FUNC_map_push_elem || insn->imm == BPF_FUNC_map_pop_elem || insn->imm == BPF_FUNC_map_peek_elem)) { aux = &env->insn_aux_data[i + delta]; if (bpf_map_ptr_poisoned(aux)) goto patch_call_imm; map_ptr = BPF_MAP_PTR(aux->map_state); ops = map_ptr->ops; if (insn->imm == BPF_FUNC_map_lookup_elem && ops->map_gen_lookup) { cnt = ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, (void *(*)(struct bpf_map *map, void *key))NULL)); BUILD_BUG_ON(!__same_type(ops->map_delete_elem, (int (*)(struct bpf_map *map, void *key))NULL)); BUILD_BUG_ON(!__same_type(ops->map_update_elem, (int (*)(struct bpf_map *map, void *key, void *value, u64 flags))NULL)); BUILD_BUG_ON(!__same_type(ops->map_push_elem, (int (*)(struct bpf_map *map, void *value, u64 flags))NULL)); BUILD_BUG_ON(!__same_type(ops->map_pop_elem, (int (*)(struct bpf_map *map, void *value))NULL)); BUILD_BUG_ON(!__same_type(ops->map_peek_elem, (int (*)(struct bpf_map *map, void *value))NULL)); switch (insn->imm) { case BPF_FUNC_map_lookup_elem: insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - __bpf_call_base; continue; case BPF_FUNC_map_update_elem: insn->imm = BPF_CAST_CALL(ops->map_update_elem) - __bpf_call_base; continue; case BPF_FUNC_map_delete_elem: insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - __bpf_call_base; continue; case BPF_FUNC_map_push_elem: insn->imm = BPF_CAST_CALL(ops->map_push_elem) - __bpf_call_base; continue; case BPF_FUNC_map_pop_elem: insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - __bpf_call_base; continue; case BPF_FUNC_map_peek_elem: insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - __bpf_call_base; continue; } goto patch_call_imm; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm, env->prog); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } Commit Message: bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: static bool emulator_get_cached_descriptor(struct desc_struct *desc, int seg, struct kvm_vcpu *vcpu) { struct kvm_segment var; kvm_get_segment(vcpu, &var, seg); if (var.unusable) return false; if (var.g) var.limit >>= 12; set_desc_limit(desc, var.limit); set_desc_base(desc, (unsigned long)var.base); desc->type = var.type; desc->s = var.s; desc->dpl = var.dpl; desc->p = var.present; desc->avl = var.avl; desc->l = var.l; desc->d = var.db; desc->g = var.g; return true; } Commit Message: KVM: X86: Don't report L2 emulation failures to user-space This patch prevents that emulation failures which result from emulating an instruction for an L2-Guest results in being reported to userspace. Without this patch a malicious L2-Guest would be able to kill the L1 by triggering a race-condition between an vmexit and the instruction emulator. With this patch the L2 will most likely only kill itself in this situation. Signed-off-by: Joerg Roedel <[email protected]> Signed-off-by: Marcelo Tosatti <[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: AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required) : field_types_(field_types), upload_required_(upload_required) { DCHECK(upload_required_); } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 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 crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "blkcipher"); snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s", alg->cra_blkcipher.geniv ?: "<default>"); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_blkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_blkcipher.max_keysize; rblkcipher.ivsize = alg->cra_blkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) 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: virtual void SetUp() { dir_maker_.SetUp(); mock_server_.reset(new MockConnectionManager(directory())); EnableDatatype(syncable::BOOKMARKS); EnableDatatype(syncable::NIGORI); EnableDatatype(syncable::PREFERENCES); EnableDatatype(syncable::NIGORI); worker_ = new FakeModelWorker(GROUP_PASSIVE); std::vector<SyncEngineEventListener*> listeners; listeners.push_back(this); context_.reset( new SyncSessionContext( mock_server_.get(), directory(), this, &extensions_activity_monitor_, listeners, NULL, &traffic_recorder_)); ASSERT_FALSE(context_->resolver()); syncer_ = new Syncer(); session_.reset(MakeSession()); ReadTransaction trans(FROM_HERE, directory()); syncable::Directory::ChildHandles children; directory()->GetChildHandlesById(&trans, trans.root_id(), &children); ASSERT_EQ(0u, children.size()); saw_syncer_event_ = false; root_id_ = TestIdFactory::root(); parent_id_ = ids_.MakeServer("parent id"); child_id_ = ids_.MakeServer("child id"); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 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 EditorClientBlackBerry::canPaste(Frame*, bool defaultValue) const { return defaultValue; } Commit Message: [BlackBerry] Prevent text selection inside Colour and Date/Time input fields https://bugs.webkit.org/show_bug.cgi?id=111733 Reviewed by Rob Buis. PR 305194. Prevent selection for popup input fields as they are buttons. Informally Reviewed Gen Mak. * WebCoreSupport/EditorClientBlackBerry.cpp: (WebCore::EditorClientBlackBerry::shouldChangeSelectedRange): git-svn-id: svn://svn.chromium.org/blink/trunk@145121 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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 gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { gdImagePtr pim = 0, tim = im; int interlace, BitsPerPixel; interlace = im->interlace; if (im->trueColor) { /* Expensive, but the only way that produces an acceptable result: mix down to a palette based temporary image. */ pim = gdImageCreatePaletteFromTrueColor(im, 1, 256); if (!pim) { return; } tim = pim; } BitsPerPixel = colorstobpp(tim->colorsTotal); /* All set, let's do it. */ GIFEncode( out, tim->sx, tim->sy, tim->interlace, 0, tim->transparent, BitsPerPixel, tim->red, tim->green, tim->blue, tim); if (pim) { /* Destroy palette based temporary image. */ gdImageDestroy( pim); } } Commit Message: Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here. CWE ID: CWE-415 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoCullFace(GLenum mode) { api()->glCullFaceFn(mode); 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 DesktopSessionWin::OnChannelConnected() { DCHECK(main_task_runner_->BelongsToCurrentThread()); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 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 SocketStream::Connect() { DCHECK(base::MessageLoop::current()) << "The current base::MessageLoop must exist"; DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type()) << "The current base::MessageLoop must be TYPE_IO"; if (context_.get()) { context_->ssl_config_service()->GetSSLConfig(&server_ssl_config_); proxy_ssl_config_ = server_ssl_config_; } CheckPrivacyMode(); DCHECK_EQ(next_state_, STATE_NONE); AddRef(); // Released in Finish() next_state_ = STATE_BEFORE_CONNECT; net_log_.BeginEvent( NetLog::TYPE_SOCKET_STREAM_CONNECT, NetLog::StringCallback("url", &url_.possibly_invalid_spec())); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&SocketStream::DoLoop, this, OK)); } 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 Target: 1 Example 2: Code: static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){ u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ u8 *pEnd; /* End mark for a varint */ #ifdef SQLITE_DEBUG /* The value returned by this function should always be the same as ** the (CellInfo.nSize) value found by doing a full parse of the ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of ** this function verifies that this invariant is not violated. */ CellInfo debuginfo; pPage->xParseCell(pPage, pCell, &debuginfo); #else UNUSED_PARAMETER(pPage); #endif assert( pPage->childPtrSize==4 ); pEnd = pIter + 9; while( (*pIter++)&0x80 && pIter<pEnd ); assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB ); return (u16)(pIter - pCell); } Commit Message: sqlite: safely move pointer values through SQL. This lands https://www.sqlite.org/src/timeline?c=d6a44b35 in third_party/sqlite/src/ and third_party/sqlite/patches/0013-Add-new-interfaces-sqlite3_bind_pointer-sqlite3_resu.patch and re-generates third_party/sqlite/amalgamation/* using the script at third_party/sqlite/google_generate_amalgamation.sh. The CL also adds a layout test that verifies the patch works as intended. BUG=742407 Change-Id: I2e1a457459cd2e975e6241b630e7b79c82545981 Reviewed-on: https://chromium-review.googlesource.com/572976 Reviewed-by: Chris Mumford <[email protected]> Commit-Queue: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#487275} 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: WarmupURLFetcher::WarmupURLFetcher( CreateCustomProxyConfigCallback create_custom_proxy_config_callback, WarmupURLFetcherCallback callback, GetHttpRttCallback get_http_rtt_callback, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, const std::string& user_agent) : is_fetch_in_flight_(false), previous_attempt_counts_(0), create_custom_proxy_config_callback_(create_custom_proxy_config_callback), callback_(callback), get_http_rtt_callback_(get_http_rtt_callback), user_agent_(user_agent), ui_task_runner_(ui_task_runner) { DCHECK(create_custom_proxy_config_callback); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416 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 futex_wait_requeue_pi(u32 __user *uaddr, int fshared, u32 val, ktime_t *abs_time, u32 bitset, int clockrt, u32 __user *uaddr2) { struct hrtimer_sleeper timeout, *to = NULL; struct rt_mutex_waiter rt_waiter; struct rt_mutex *pi_mutex = NULL; struct futex_hash_bucket *hb; union futex_key key2; struct futex_q q; int res, ret; if (!bitset) return -EINVAL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } /* * The waiter is allocated on our stack, manipulated by the requeue * code while we sleep on uaddr. */ debug_rt_mutex_init_waiter(&rt_waiter); rt_waiter.task = NULL; key2 = FUTEX_KEY_INIT; ret = get_futex_key(uaddr2, fshared, &key2); if (unlikely(ret != 0)) goto out; q.pi_state = NULL; q.bitset = bitset; q.rt_waiter = &rt_waiter; q.requeue_pi_key = &key2; /* Prepare to wait on uaddr. */ ret = futex_wait_setup(uaddr, val, fshared, &q, &hb); if (ret) goto out_key2; /* Queue the futex_q, drop the hb lock, wait for wakeup. */ futex_wait_queue_me(hb, &q, to); spin_lock(&hb->lock); ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to); spin_unlock(&hb->lock); if (ret) goto out_put_keys; /* * In order for us to be here, we know our q.key == key2, and since * we took the hb->lock above, we also know that futex_requeue() has * completed and we no longer have to concern ourselves with a wakeup * race with the atomic proxy lock acquition by the requeue code. */ /* Check if the requeue code acquired the second futex for us. */ if (!q.rt_waiter) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case. */ if (q.pi_state && (q.pi_state->owner != current)) { spin_lock(q.lock_ptr); ret = fixup_pi_state_owner(uaddr2, &q, current, fshared); spin_unlock(q.lock_ptr); } } else { /* * We have been woken up by futex_unlock_pi(), a timeout, or a * signal. futex_unlock_pi() will not destroy the lock_ptr nor * the pi_state. */ WARN_ON(!&q.pi_state); pi_mutex = &q.pi_state->pi_mutex; ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1); debug_rt_mutex_free_waiter(&rt_waiter); spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr2, fshared, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it * acquired the lock, clear -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* Unqueue and drop the lock. */ unqueue_me_pi(&q); } /* * If fixup_pi_state_owner() faulted and was unable to handle the * fault, unlock the rt_mutex and return the fault to userspace. */ if (ret == -EFAULT) { if (rt_mutex_owner(pi_mutex) == current) rt_mutex_unlock(pi_mutex); } else if (ret == -EINTR) { /* * We've already been requeued, but cannot restart by calling * futex_lock_pi() directly. We could restart this syscall, but * it would detect that the user space "val" changed and return * -EWOULDBLOCK. Save the overhead of the restart and return * -EWOULDBLOCK directly. */ ret = -EWOULDBLOCK; } out_put_keys: put_futex_key(fshared, &q.key); out_key2: put_futex_key(fshared, &key2); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; } Commit Message: futex: Fix errors in nested key ref-counting futex_wait() is leaking key references due to futex_wait_setup() acquiring an additional reference via the queue_lock() routine. The nested key ref-counting has been masking bugs and complicating code analysis. queue_lock() is only called with a previously ref-counted key, so remove the additional ref-counting from the queue_(un)lock() functions. Also futex_wait_requeue_pi() drops one key reference too many in unqueue_me_pi(). Remove the key reference handling from unqueue_me_pi(). This was paired with a queue_lock() in futex_lock_pi(), so the count remains unchanged. Document remaining nested key ref-counting sites. Signed-off-by: Darren Hart <[email protected]> Reported-and-tested-by: Matthieu Fertré<[email protected]> Reported-by: Louis Rilling<[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Eric Dumazet <[email protected]> Cc: John Kacur <[email protected]> Cc: Rusty Russell <[email protected]> LKML-Reference: <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Cc: [email protected] CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int may_follow_link(struct nameidata *nd) { const struct inode *inode; const struct inode *parent; if (!sysctl_protected_symlinks) return 0; /* Allowed if owner and follower match. */ inode = nd->link_inode; if (uid_eq(current_cred()->fsuid, inode->i_uid)) return 0; /* Allowed if parent directory not sticky and world-writable. */ parent = nd->inode; if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH)) return 0; /* Allowed if parent directory and link owner match. */ if (uid_eq(parent->i_uid, inode->i_uid)) return 0; if (nd->flags & LOOKUP_RCU) return -ECHILD; audit_log_link_denied("follow_link", &nd->stack[0].link); return -EACCES; } Commit Message: vfs: rename: check backing inode being equal If a file is renamed to a hardlink of itself POSIX specifies that rename(2) should do nothing and return success. This condition is checked in vfs_rename(). However it won't detect hard links on overlayfs where these are given separate inodes on the overlayfs layer. Overlayfs itself detects this condition and returns success without doing anything, but then vfs_rename() will proceed as if this was a successful rename (detach_mounts(), d_move()). The correct thing to do is to detect this condition before even calling into overlayfs. This patch does this by calling vfs_select_inode() to get the underlying inodes. Signed-off-by: Miklos Szeredi <[email protected]> Cc: <[email protected]> # v4.2+ 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: static struct mnt_namespace *create_mnt_ns(struct vfsmount *m) { struct mnt_namespace *new_ns = alloc_mnt_ns(&init_user_ns); if (!IS_ERR(new_ns)) { struct mount *mnt = real_mount(m); mnt->mnt_ns = new_ns; new_ns->root = mnt; list_add(&mnt->mnt_list, &new_ns->list); } else { mntput(m); } return new_ns; } Commit Message: mnt: Add a per mount namespace limit on the number of mounts CAI Qian <[email protected]> pointed out that the semantics of shared subtrees make it possible to create an exponentially increasing number of mounts in a mount namespace. mkdir /tmp/1 /tmp/2 mount --make-rshared / for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done Will create create 2^20 or 1048576 mounts, which is a practical problem as some people have managed to hit this by accident. As such CVE-2016-6213 was assigned. Ian Kent <[email protected]> described the situation for autofs users as follows: > The number of mounts for direct mount maps is usually not very large because of > the way they are implemented, large direct mount maps can have performance > problems. There can be anywhere from a few (likely case a few hundred) to less > than 10000, plus mounts that have been triggered and not yet expired. > > Indirect mounts have one autofs mount at the root plus the number of mounts that > have been triggered and not yet expired. > > The number of autofs indirect map entries can range from a few to the common > case of several thousand and in rare cases up to between 30000 and 50000. I've > not heard of people with maps larger than 50000 entries. > > The larger the number of map entries the greater the possibility for a large > number of active mounts so it's not hard to expect cases of a 1000 or somewhat > more active mounts. So I am setting the default number of mounts allowed per mount namespace at 100,000. This is more than enough for any use case I know of, but small enough to quickly stop an exponential increase in mounts. Which should be perfect to catch misconfigurations and malfunctioning programs. For anyone who needs a higher limit this can be changed by writing to the new /proc/sys/fs/mount-max sysctl. Tested-by: CAI Qian <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-400 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 PepperRendererConnection::OnMsgDidCreateInProcessInstance( PP_Instance instance, const PepperRendererInstanceData& instance_data) { PepperRendererInstanceData data = instance_data; data.render_process_id = render_process_id_; in_process_host_->AddInstance(instance, data); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20 Target: 1 Example 2: Code: static void sighand_ctor(void *data) { struct sighand_struct *sighand = data; spin_lock_init(&sighand->siglock); init_waitqueue_head(&sighand->signalfd_wqh); } Commit Message: Move "exit_robust_list" into mm_release() We don't want to get rid of the futexes just at exit() time, we want to drop them when doing an execve() too, since that gets rid of the previous VM image too. Doing it at mm_release() time means that we automatically always do it when we disassociate a VM map from the task. Reported-by: [email protected] Cc: Andrew Morton <[email protected]> Cc: Nick Piggin <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Brad Spengler <[email protected]> Cc: Alex Efros <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Oleg Nesterov <[email protected]> Signed-off-by: Linus Torvalds <[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 ExtensionTtsPlatformImplChromeOs::IsSpeaking() { if (chromeos::CrosLibrary::Get()->EnsureLoaded()) { return chromeos::CrosLibrary::Get()->GetSpeechSynthesisLibrary()-> IsSpeaking(); } set_error(kCrosLibraryNotLoadedError); return false; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 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: CursorImpl::IDBThreadHelper::~IDBThreadHelper() { cursor_->RemoveCursorFromTransaction(); } Commit Message: [IndexedDB] Fix Cursor UAF If the connection is closed before we return a cursor, it dies in IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on the correct thread, but we also need to makes sure to remove it from its transaction. To make things simpler, we have the cursor remove itself from its transaction on destruction. R: [email protected] Bug: 728887 Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2 Reviewed-on: https://chromium-review.googlesource.com/526284 Commit-Queue: Daniel Murphy <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#477504} CWE ID: CWE-416 Target: 1 Example 2: Code: static int resolve_symlink(char *d, apr_finfo_t *lfi, int opts, apr_pool_t *p) { apr_finfo_t fi; const char *savename; if (!(opts & (OPT_SYM_OWNER | OPT_SYM_LINKS))) { return HTTP_FORBIDDEN; } /* Save the name from the valid bits. */ savename = (lfi->valid & APR_FINFO_NAME) ? lfi->name : NULL; /* if OPT_SYM_OWNER is unset, we only need to check target accessible */ if (!(opts & OPT_SYM_OWNER)) { if (apr_stat(&fi, d, lfi->valid & ~(APR_FINFO_NAME | APR_FINFO_LINK), p) != APR_SUCCESS) { return HTTP_FORBIDDEN; } /* Give back the target */ memcpy(lfi, &fi, sizeof(fi)); if (savename) { lfi->name = savename; lfi->valid |= APR_FINFO_NAME; } return OK; } /* OPT_SYM_OWNER only works if we can get the owner of * both the file and symlink. First fill in a missing * owner of the symlink, then get the info of the target. */ if (!(lfi->valid & APR_FINFO_OWNER)) { if (apr_stat(lfi, d, lfi->valid | APR_FINFO_LINK | APR_FINFO_OWNER, p) != APR_SUCCESS) { return HTTP_FORBIDDEN; } } if (apr_stat(&fi, d, lfi->valid & ~(APR_FINFO_NAME), p) != APR_SUCCESS) { return HTTP_FORBIDDEN; } if (apr_uid_compare(fi.user, lfi->user) != APR_SUCCESS) { return HTTP_FORBIDDEN; } /* Give back the target */ memcpy(lfi, &fi, sizeof(fi)); if (savename) { lfi->name = savename; lfi->valid |= APR_FINFO_NAME; } return OK; } Commit Message: SECURITY: CVE-2015-3183 (cve.mitre.org) Replacement of ap_some_auth_required (unusable in Apache httpd 2.4) with new ap_some_authn_required and ap_force_authn hook. Submitted by: breser git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684524 13f79535-47bb-0310-9956-ffa450edef68 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: DataReductionProxyIOData::DataReductionProxyIOData( Client client, PrefService* prefs, network::NetworkConnectionTracker* network_connection_tracker, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, bool enabled, const std::string& user_agent, const std::string& channel) : client_(client), network_connection_tracker_(network_connection_tracker), io_task_runner_(io_task_runner), ui_task_runner_(ui_task_runner), enabled_(enabled), channel_(channel), effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { DCHECK(io_task_runner_); DCHECK(ui_task_runner_); configurator_.reset(new DataReductionProxyConfigurator()); configurator_->SetConfigUpdatedCallback(base::BindRepeating( &DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this))); DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr; std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config = std::make_unique<DataReductionProxyMutableConfigValues>(); raw_mutable_config = mutable_config.get(); config_.reset(new DataReductionProxyConfig( io_task_runner, ui_task_runner, network_connection_tracker_, std::move(mutable_config), configurator_.get())); request_options_.reset( new DataReductionProxyRequestOptions(client_, config_.get())); request_options_->Init(); request_options_->SetUpdateHeaderCallback(base::BindRepeating( &DataReductionProxyIOData::UpdateProxyRequestHeaders, base::Unretained(this))); config_client_.reset(new DataReductionProxyConfigServiceClient( GetBackoffPolicy(), request_options_.get(), raw_mutable_config, config_.get(), this, network_connection_tracker_, base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig, base::Unretained(this)))); network_properties_manager_.reset(new NetworkPropertiesManager( base::DefaultClock::GetInstance(), prefs, ui_task_runner_)); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416 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 ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov, loff_t offset, unsigned long nr_segs) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; ssize_t ret; size_t count = iov_length(iov, nr_segs); loff_t final_size = offset + count; if (rw == WRITE && final_size <= inode->i_size) { /* * We could direct write to holes and fallocate. * * Allocated blocks to fill the hole are marked as uninitialized * to prevent paralel buffered read to expose the stale data * before DIO complete the data IO. * * As to previously fallocated extents, ext4 get_block * will just simply mark the buffer mapped but still * keep the extents uninitialized. * * for non AIO case, we will convert those unwritten extents * to written after return back from blockdev_direct_IO. * * for async DIO, the conversion needs to be defered when * the IO is completed. The ext4 end_io callback function * will be called to take care of the conversion work. * Here for async case, we allocate an io_end structure to * hook to the iocb. */ iocb->private = NULL; EXT4_I(inode)->cur_aio_dio = NULL; if (!is_sync_kiocb(iocb)) { iocb->private = ext4_init_io_end(inode); if (!iocb->private) return -ENOMEM; /* * we save the io structure for current async * direct IO, so that later ext4_get_blocks() * could flag the io structure whether there * is a unwritten extents needs to be converted * when IO is completed. */ EXT4_I(inode)->cur_aio_dio = iocb->private; } ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov, offset, nr_segs, ext4_get_block_write, ext4_end_io_dio); if (iocb->private) EXT4_I(inode)->cur_aio_dio = NULL; /* * The io_end structure takes a reference to the inode, * that structure needs to be destroyed and the * reference to the inode need to be dropped, when IO is * complete, even with 0 byte write, or failed. * * In the successful AIO DIO case, the io_end structure will be * desctroyed and the reference to the inode will be dropped * after the end_io call back function is called. * * In the case there is 0 byte write, or error case, since * VFS direct IO won't invoke the end_io call back function, * we need to free the end_io structure here. */ if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) { ext4_free_io_end(iocb->private); iocb->private = NULL; } else if (ret > 0 && ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN)) { int err; /* * for non AIO case, since the IO is already * completed, we could do the convertion right here */ err = ext4_convert_unwritten_extents(inode, offset, ret); if (err < 0) ret = err; ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); } return ret; } /* for write the the end of file case, we fall back to old way */ return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Target: 1 Example 2: Code: ACTION_P(QuitMessageLoop, loop_or_proxy) { loop_or_proxy->PostTask(FROM_HERE, MessageLoop::QuitClosure()); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 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: INST_HANDLER (sts) { // STS k, Rr int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; } Commit Message: Fix #10091 - crash in AVR analysis 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: char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: static int pppoe_connect(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len, int flags) { struct sock *sk = sock->sk; struct sockaddr_pppox *sp = (struct sockaddr_pppox *)uservaddr; struct pppox_sock *po = pppox_sk(sk); struct net_device *dev = NULL; struct pppoe_net *pn; struct net *net = NULL; int error; lock_sock(sk); error = -EINVAL; if (sp->sa_protocol != PX_PROTO_OE) goto end; /* Check for already bound sockets */ error = -EBUSY; if ((sk->sk_state & PPPOX_CONNECTED) && stage_session(sp->sa_addr.pppoe.sid)) goto end; /* Check for already disconnected sockets, on attempts to disconnect */ error = -EALREADY; if ((sk->sk_state & PPPOX_DEAD) && !stage_session(sp->sa_addr.pppoe.sid)) goto end; error = 0; /* Delete the old binding */ if (stage_session(po->pppoe_pa.sid)) { pppox_unbind_sock(sk); pn = pppoe_pernet(sock_net(sk)); delete_item(pn, po->pppoe_pa.sid, po->pppoe_pa.remote, po->pppoe_ifindex); if (po->pppoe_dev) { dev_put(po->pppoe_dev); po->pppoe_dev = NULL; } memset(sk_pppox(po) + 1, 0, sizeof(struct pppox_sock) - sizeof(struct sock)); sk->sk_state = PPPOX_NONE; } /* Re-bind in session stage only */ if (stage_session(sp->sa_addr.pppoe.sid)) { error = -ENODEV; net = sock_net(sk); dev = dev_get_by_name(net, sp->sa_addr.pppoe.dev); if (!dev) goto err_put; po->pppoe_dev = dev; po->pppoe_ifindex = dev->ifindex; pn = pppoe_pernet(net); if (!(dev->flags & IFF_UP)) { goto err_put; } memcpy(&po->pppoe_pa, &sp->sa_addr.pppoe, sizeof(struct pppoe_addr)); write_lock_bh(&pn->hash_lock); error = __set_item(pn, po); write_unlock_bh(&pn->hash_lock); if (error < 0) goto err_put; po->chan.hdrlen = (sizeof(struct pppoe_hdr) + dev->hard_header_len); po->chan.mtu = dev->mtu - sizeof(struct pppoe_hdr); po->chan.private = sk; po->chan.ops = &pppoe_chan_ops; error = ppp_register_net_channel(dev_net(dev), &po->chan); if (error) { delete_item(pn, po->pppoe_pa.sid, po->pppoe_pa.remote, po->pppoe_ifindex); goto err_put; } sk->sk_state = PPPOX_CONNECTED; } po->num = sp->sa_addr.pppoe.sid; end: release_sock(sk); return error; err_put: if (po->pppoe_dev) { dev_put(po->pppoe_dev); po->pppoe_dev = NULL; } goto end; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 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: MagickExport MagickBooleanType AnnotateImage(Image *image, const DrawInfo *draw_info,ExceptionInfo *exception) { char *p, primitive[MagickPathExtent], *text, **textlist; DrawInfo *annotate, *annotate_info; GeometryInfo geometry_info; MagickBooleanType status; PointInfo offset; RectangleInfo geometry; register ssize_t i; TypeMetric metrics; size_t height, number_lines; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (draw_info->text == (char *) NULL) return(MagickFalse); if (*draw_info->text == '\0') return(MagickTrue); annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info); text=annotate->text; annotate->text=(char *) NULL; annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); number_lines=1; for (p=text; *p != '\0'; p++) if (*p == '\n') number_lines++; textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist)); if (textlist == (char **) NULL) return(MagickFalse); p=text; for (i=0; i < number_lines; i++) { char *q; textlist[i]=p; for (q=p; *q != '\0'; q++) if ((*q == '\r') || (*q == '\n')) break; if (*q == '\r') { *q='\0'; q++; } *q='\0'; p=q+1; } textlist[i]=(char *) NULL; SetGeometry(image,&geometry); SetGeometryInfo(&geometry_info); if (annotate_info->geometry != (char *) NULL) { (void) ParsePageGeometry(image,annotate_info->geometry,&geometry, exception); (void) ParseGeometry(annotate_info->geometry,&geometry_info); } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; (void) memset(&metrics,0,sizeof(metrics)); for (i=0; textlist[i] != (char *) NULL; i++) { if (*textlist[i] == '\0') continue; /* Position text relative to image. */ annotate_info->affine.tx=geometry_info.xi-image->page.x; annotate_info->affine.ty=geometry_info.psi-image->page.y; (void) CloneString(&annotate->text,textlist[i]); if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity)) (void) GetTypeMetrics(image,annotate,&metrics,exception); height=(ssize_t) (metrics.ascent-metrics.descent+ draw_info->interline_spacing+0.5); switch (annotate->gravity) { case UndefinedGravity: default: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; break; } case NorthWestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height+annotate_info->affine.ry* (metrics.ascent+metrics.descent); offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent; break; } case NorthGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* (metrics.ascent+metrics.descent); offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent-annotate_info->affine.rx*metrics.width/2.0; break; } case NorthEastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width+annotate_info->affine.ry* (metrics.ascent+metrics.descent)-1.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent-annotate_info->affine.rx*metrics.width; break; } case WestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height+annotate_info->affine.ry* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height+ annotate_info->affine.sy*(metrics.ascent+metrics.descent- (number_lines-1.0)*height)/2.0; break; } case CenterGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; break; } case EastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width+ annotate_info->affine.ry*(metrics.ascent+metrics.descent- (number_lines-1.0)*height)/2.0-1.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width+ annotate_info->affine.sy*(metrics.ascent+metrics.descent- (number_lines-1.0)*height)/2.0; break; } case SouthWestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height-annotate_info->affine.ry* (number_lines-1.0)*height; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; break; } case SouthGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0- annotate_info->affine.ry*(number_lines-1.0)*height/2.0; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0- annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; break; } case SouthEastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width- annotate_info->affine.ry*(number_lines-1.0)*height-1.0; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width- annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; break; } } switch (annotate->align) { case LeftAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; break; } case CenterAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0; break; } case RightAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width; break; } default: break; } if (draw_info->undercolor.alpha != TransparentAlpha) { DrawInfo *undercolor_info; /* Text box. */ undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL); undercolor_info->fill=draw_info->undercolor; undercolor_info->affine=draw_info->affine; undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent; undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent; (void) FormatLocaleString(primitive,MagickPathExtent, "rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height); (void) CloneString(&undercolor_info->primitive,primitive); (void) DrawImage(image,undercolor_info,exception); (void) DestroyDrawInfo(undercolor_info); } annotate_info->affine.tx=offset.x; annotate_info->affine.ty=offset.y; (void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g " "line 0,0 %g,0",metrics.underline_thickness,metrics.width); if (annotate->decorate == OverlineDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+ metrics.descent-metrics.underline_position)); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info,exception); } else if (annotate->decorate == UnderlineDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy* metrics.underline_position); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info,exception); } /* Annotate image with text. */ status=RenderType(image,annotate,&offset,&metrics,exception); if (status == MagickFalse) break; if (annotate->decorate == LineThroughDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy*(height+ metrics.underline_position+metrics.descent)/2.0); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info,exception); } } /* Relinquish resources. */ annotate_info=DestroyDrawInfo(annotate_info); annotate=DestroyDrawInfo(annotate); textlist=(char **) RelinquishMagickMemory(textlist); return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1589 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 RTCPeerConnectionHandlerDummy::setLocalDescription(PassRefPtr<RTCVoidRequest>, PassRefPtr<RTCSessionDescriptionDescriptor>) { } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: inline RemoteFrame::RemoteFrame(RemoteFrameClient* client, Page& page, FrameOwner* owner) : Frame(client, page, owner, RemoteWindowProxyManager::Create(*this)), security_context_(RemoteSecurityContext::Create()) { dom_window_ = RemoteDOMWindow::Create(*this); UpdateInertIfPossible(); } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} 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: static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 30 && rdesc[29] == 0x05 && rdesc[30] == 0x09) { hid_info(hdev, "fixing up button/consumer in HID report descriptor\n"); rdesc[30] = 0x0c; } 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 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 rds_ib_xmit(struct rds_connection *conn, struct rds_message *rm, unsigned int hdr_off, unsigned int sg, unsigned int off) { struct rds_ib_connection *ic = conn->c_transport_data; struct ib_device *dev = ic->i_cm_id->device; struct rds_ib_send_work *send = NULL; struct rds_ib_send_work *first; struct rds_ib_send_work *prev; struct ib_send_wr *failed_wr; struct scatterlist *scat; u32 pos; u32 i; u32 work_alloc; u32 credit_alloc = 0; u32 posted; u32 adv_credits = 0; int send_flags = 0; int bytes_sent = 0; int ret; int flow_controlled = 0; int nr_sig = 0; BUG_ON(off % RDS_FRAG_SIZE); BUG_ON(hdr_off != 0 && hdr_off != sizeof(struct rds_header)); /* Do not send cong updates to IB loopback */ if (conn->c_loopback && rm->m_inc.i_hdr.h_flags & RDS_FLAG_CONG_BITMAP) { rds_cong_map_updated(conn->c_fcong, ~(u64) 0); return sizeof(struct rds_header) + RDS_CONG_MAP_BYTES; } /* FIXME we may overallocate here */ if (be32_to_cpu(rm->m_inc.i_hdr.h_len) == 0) i = 1; else i = ceil(be32_to_cpu(rm->m_inc.i_hdr.h_len), RDS_FRAG_SIZE); work_alloc = rds_ib_ring_alloc(&ic->i_send_ring, i, &pos); if (work_alloc == 0) { set_bit(RDS_LL_SEND_FULL, &conn->c_flags); rds_ib_stats_inc(s_ib_tx_ring_full); ret = -ENOMEM; goto out; } if (ic->i_flowctl) { credit_alloc = rds_ib_send_grab_credits(ic, work_alloc, &posted, 0, RDS_MAX_ADV_CREDIT); adv_credits += posted; if (credit_alloc < work_alloc) { rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - credit_alloc); work_alloc = credit_alloc; flow_controlled = 1; } if (work_alloc == 0) { set_bit(RDS_LL_SEND_FULL, &conn->c_flags); rds_ib_stats_inc(s_ib_tx_throttle); ret = -ENOMEM; goto out; } } /* map the message the first time we see it */ if (!ic->i_data_op) { if (rm->data.op_nents) { rm->data.op_count = ib_dma_map_sg(dev, rm->data.op_sg, rm->data.op_nents, DMA_TO_DEVICE); rdsdebug("ic %p mapping rm %p: %d\n", ic, rm, rm->data.op_count); if (rm->data.op_count == 0) { rds_ib_stats_inc(s_ib_tx_sg_mapping_failure); rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc); ret = -ENOMEM; /* XXX ? */ goto out; } } else { rm->data.op_count = 0; } rds_message_addref(rm); ic->i_data_op = &rm->data; /* Finalize the header */ if (test_bit(RDS_MSG_ACK_REQUIRED, &rm->m_flags)) rm->m_inc.i_hdr.h_flags |= RDS_FLAG_ACK_REQUIRED; if (test_bit(RDS_MSG_RETRANSMITTED, &rm->m_flags)) rm->m_inc.i_hdr.h_flags |= RDS_FLAG_RETRANSMITTED; /* If it has a RDMA op, tell the peer we did it. This is * used by the peer to release use-once RDMA MRs. */ if (rm->rdma.op_active) { struct rds_ext_header_rdma ext_hdr; ext_hdr.h_rdma_rkey = cpu_to_be32(rm->rdma.op_rkey); rds_message_add_extension(&rm->m_inc.i_hdr, RDS_EXTHDR_RDMA, &ext_hdr, sizeof(ext_hdr)); } if (rm->m_rdma_cookie) { rds_message_add_rdma_dest_extension(&rm->m_inc.i_hdr, rds_rdma_cookie_key(rm->m_rdma_cookie), rds_rdma_cookie_offset(rm->m_rdma_cookie)); } /* Note - rds_ib_piggyb_ack clears the ACK_REQUIRED bit, so * we should not do this unless we have a chance of at least * sticking the header into the send ring. Which is why we * should call rds_ib_ring_alloc first. */ rm->m_inc.i_hdr.h_ack = cpu_to_be64(rds_ib_piggyb_ack(ic)); rds_message_make_checksum(&rm->m_inc.i_hdr); /* * Update adv_credits since we reset the ACK_REQUIRED bit. */ if (ic->i_flowctl) { rds_ib_send_grab_credits(ic, 0, &posted, 1, RDS_MAX_ADV_CREDIT - adv_credits); adv_credits += posted; BUG_ON(adv_credits > 255); } } /* Sometimes you want to put a fence between an RDMA * READ and the following SEND. * We could either do this all the time * or when requested by the user. Right now, we let * the application choose. */ if (rm->rdma.op_active && rm->rdma.op_fence) send_flags = IB_SEND_FENCE; /* Each frag gets a header. Msgs may be 0 bytes */ send = &ic->i_sends[pos]; first = send; prev = NULL; scat = &ic->i_data_op->op_sg[sg]; i = 0; do { unsigned int len = 0; /* Set up the header */ send->s_wr.send_flags = send_flags; send->s_wr.opcode = IB_WR_SEND; send->s_wr.num_sge = 1; send->s_wr.next = NULL; send->s_queued = jiffies; send->s_op = NULL; send->s_sge[0].addr = ic->i_send_hdrs_dma + (pos * sizeof(struct rds_header)); send->s_sge[0].length = sizeof(struct rds_header); memcpy(&ic->i_send_hdrs[pos], &rm->m_inc.i_hdr, sizeof(struct rds_header)); /* Set up the data, if present */ if (i < work_alloc && scat != &rm->data.op_sg[rm->data.op_count]) { len = min(RDS_FRAG_SIZE, ib_sg_dma_len(dev, scat) - off); send->s_wr.num_sge = 2; send->s_sge[1].addr = ib_sg_dma_address(dev, scat) + off; send->s_sge[1].length = len; bytes_sent += len; off += len; if (off == ib_sg_dma_len(dev, scat)) { scat++; off = 0; } } rds_ib_set_wr_signal_state(ic, send, 0); /* * Always signal the last one if we're stopping due to flow control. */ if (ic->i_flowctl && flow_controlled && i == (work_alloc-1)) send->s_wr.send_flags |= IB_SEND_SIGNALED | IB_SEND_SOLICITED; if (send->s_wr.send_flags & IB_SEND_SIGNALED) nr_sig++; rdsdebug("send %p wr %p num_sge %u next %p\n", send, &send->s_wr, send->s_wr.num_sge, send->s_wr.next); if (ic->i_flowctl && adv_credits) { struct rds_header *hdr = &ic->i_send_hdrs[pos]; /* add credit and redo the header checksum */ hdr->h_credit = adv_credits; rds_message_make_checksum(hdr); adv_credits = 0; rds_ib_stats_inc(s_ib_tx_credit_updates); } if (prev) prev->s_wr.next = &send->s_wr; prev = send; pos = (pos + 1) % ic->i_send_ring.w_nr; send = &ic->i_sends[pos]; i++; } while (i < work_alloc && scat != &rm->data.op_sg[rm->data.op_count]); /* Account the RDS header in the number of bytes we sent, but just once. * The caller has no concept of fragmentation. */ if (hdr_off == 0) bytes_sent += sizeof(struct rds_header); /* if we finished the message then send completion owns it */ if (scat == &rm->data.op_sg[rm->data.op_count]) { prev->s_op = ic->i_data_op; prev->s_wr.send_flags |= IB_SEND_SOLICITED; ic->i_data_op = NULL; } /* Put back wrs & credits we didn't use */ if (i < work_alloc) { rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - i); work_alloc = i; } if (ic->i_flowctl && i < credit_alloc) rds_ib_send_add_credits(conn, credit_alloc - i); if (nr_sig) atomic_add(nr_sig, &ic->i_signaled_sends); /* XXX need to worry about failed_wr and partial sends. */ failed_wr = &first->s_wr; ret = ib_post_send(ic->i_cm_id->qp, &first->s_wr, &failed_wr); rdsdebug("ic %p first %p (wr %p) ret %d wr %p\n", ic, first, &first->s_wr, ret, failed_wr); BUG_ON(failed_wr != &first->s_wr); if (ret) { printk(KERN_WARNING "RDS/IB: ib_post_send to %pI4 " "returned %d\n", &conn->c_faddr, ret); rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc); rds_ib_sub_signaled(ic, nr_sig); if (prev->s_op) { ic->i_data_op = prev->s_op; prev->s_op = NULL; } rds_ib_conn_error(ic->conn, "ib_post_send failed\n"); goto out; } ret = bytes_sent; out: BUG_ON(adv_credits); return ret; } Commit Message: rds: prevent BUG_ON triggering on congestion map updates Recently had this bug halt reported to me: kernel BUG at net/rds/send.c:329! Oops: Exception in kernel mode, sig: 5 [#1] SMP NR_CPUS=1024 NUMA pSeries Modules linked in: rds sunrpc ipv6 dm_mirror dm_region_hash dm_log ibmveth sg ext4 jbd2 mbcache sd_mod crc_t10dif ibmvscsic scsi_transport_srp scsi_tgt dm_mod [last unloaded: scsi_wait_scan] NIP: d000000003ca68f4 LR: d000000003ca67fc CTR: d000000003ca8770 REGS: c000000175cab980 TRAP: 0700 Not tainted (2.6.32-118.el6.ppc64) MSR: 8000000000029032 <EE,ME,CE,IR,DR> CR: 44000022 XER: 00000000 TASK = c00000017586ec90[1896] 'krdsd' THREAD: c000000175ca8000 CPU: 0 GPR00: 0000000000000150 c000000175cabc00 d000000003cb7340 0000000000002030 GPR04: ffffffffffffffff 0000000000000030 0000000000000000 0000000000000030 GPR08: 0000000000000001 0000000000000001 c0000001756b1e30 0000000000010000 GPR12: d000000003caac90 c000000000fa2500 c0000001742b2858 c0000001742b2a00 GPR16: c0000001742b2a08 c0000001742b2820 0000000000000001 0000000000000001 GPR20: 0000000000000040 c0000001742b2814 c000000175cabc70 0800000000000000 GPR24: 0000000000000004 0200000000000000 0000000000000000 c0000001742b2860 GPR28: 0000000000000000 c0000001756b1c80 d000000003cb68e8 c0000001742b27b8 NIP [d000000003ca68f4] .rds_send_xmit+0x4c4/0x8a0 [rds] LR [d000000003ca67fc] .rds_send_xmit+0x3cc/0x8a0 [rds] Call Trace: [c000000175cabc00] [d000000003ca67fc] .rds_send_xmit+0x3cc/0x8a0 [rds] (unreliable) [c000000175cabd30] [d000000003ca7e64] .rds_send_worker+0x54/0x100 [rds] [c000000175cabdb0] [c0000000000b475c] .worker_thread+0x1dc/0x3c0 [c000000175cabed0] [c0000000000baa9c] .kthread+0xbc/0xd0 [c000000175cabf90] [c000000000032114] .kernel_thread+0x54/0x70 Instruction dump: 4bfffd50 60000000 60000000 39080001 935f004c f91f0040 41820024 813d017c 7d094a78 7d290074 7929d182 394a0020 <0b090000> 40e2ff68 4bffffa4 39200000 Kernel panic - not syncing: Fatal exception Call Trace: [c000000175cab560] [c000000000012e04] .show_stack+0x74/0x1c0 (unreliable) [c000000175cab610] [c0000000005a365c] .panic+0x80/0x1b4 [c000000175cab6a0] [c00000000002fbcc] .die+0x21c/0x2a0 [c000000175cab750] [c000000000030000] ._exception+0x110/0x220 [c000000175cab910] [c000000000004b9c] program_check_common+0x11c/0x180 Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 1 Example 2: Code: void RenderThreadImpl::Init() { TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, ""); #if defined(OS_MACOSX) || defined(OS_ANDROID) WebKit::WebView::setUseExternalPopupMenus(true); #endif lazy_tls.Pointer()->Set(this); #if defined(OS_WIN) if (RenderProcessImpl::InProcessPlugins()) initialize_com_.reset(new base::win::ScopedCOMInitializer()); #endif ChildProcess::current()->set_main_thread(this); suspend_webkit_shared_timer_ = true; notify_webkit_of_modal_loop_ = true; plugin_refresh_allowed_ = true; widget_count_ = 0; hidden_widget_count_ = 0; idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs; idle_notifications_to_skip_ = 0; compositor_initialized_ = false; appcache_dispatcher_.reset(new AppCacheDispatcher(Get())); main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher()); media_stream_center_ = NULL; db_message_filter_ = new DBMessageFilter(); AddFilter(db_message_filter_.get()); vc_manager_ = new VideoCaptureImplManager(); AddFilter(vc_manager_->video_capture_message_filter()); audio_input_message_filter_ = new AudioInputMessageFilter(); AddFilter(audio_input_message_filter_.get()); audio_message_filter_ = new AudioMessageFilter(); AddFilter(audio_message_filter_.get()); devtools_agent_message_filter_ = new DevToolsAgentFilter(); AddFilter(devtools_agent_message_filter_.get()); AddFilter(new IndexedDBMessageFilter); content::GetContentClient()->renderer()->RenderThreadStarted(); FilePath media_path; PathService::Get(content::DIR_MEDIA_LIBS, &media_path); if (!media_path.empty()) media::InitializeMediaLibrary(media_path); TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, ""); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 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: xsltNumberFormatGetAnyLevel(xsltTransformContextPtr context, xmlNodePtr node, xsltCompMatchPtr countPat, xsltCompMatchPtr fromPat, double *array, xmlDocPtr doc, xmlNodePtr elem) { int amount = 0; int cnt = 0; xmlNodePtr cur; /* select the starting node */ switch (node->type) { case XML_ELEMENT_NODE: cur = node; break; case XML_ATTRIBUTE_NODE: cur = ((xmlAttrPtr) node)->parent; break; case XML_TEXT_NODE: case XML_PI_NODE: case XML_COMMENT_NODE: cur = node->parent; break; default: cur = NULL; break; } while (cur != NULL) { /* process current node */ if (countPat == NULL) { if ((node->type == cur->type) && /* FIXME: must use expanded-name instead of local name */ xmlStrEqual(node->name, cur->name)) { if ((node->ns == cur->ns) || ((node->ns != NULL) && (cur->ns != NULL) && (xmlStrEqual(node->ns->href, cur->ns->href) ))) cnt++; } } else { if (xsltTestCompMatchList(context, cur, countPat)) cnt++; } if ((fromPat != NULL) && xsltTestCompMatchList(context, cur, fromPat)) { break; /* while */ } /* Skip to next preceding or ancestor */ if ((cur->type == XML_DOCUMENT_NODE) || #ifdef LIBXML_DOCB_ENABLED (cur->type == XML_DOCB_DOCUMENT_NODE) || #endif (cur->type == XML_HTML_DOCUMENT_NODE)) break; /* while */ while ((cur->prev != NULL) && ((cur->prev->type == XML_DTD_NODE) || (cur->prev->type == XML_XINCLUDE_START) || (cur->prev->type == XML_XINCLUDE_END))) cur = cur->prev; if (cur->prev != NULL) { for (cur = cur->prev; cur->last != NULL; cur = cur->last); } else { cur = cur->parent; } } array[amount++] = (double) cnt; return(amount); } 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 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 UninstallExtension(ExtensionService* service, const std::string& id) { if (service && service->GetInstalledExtension(id)) { service->UninstallExtension(id, extensions::UNINSTALL_REASON_SYNC, base::Bind(&base::DoNothing), NULL); } } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID: Target: 1 Example 2: Code: static inline struct audit_context *audit_take_context(struct task_struct *tsk, int return_valid, long return_code) { struct audit_context *context = tsk->audit_context; if (!context) return NULL; context->return_valid = return_valid; /* * we need to fix up the return code in the audit logs if the actual * return codes are later going to be fixed up by the arch specific * signal handlers * * This is actually a test for: * (rc == ERESTARTSYS ) || (rc == ERESTARTNOINTR) || * (rc == ERESTARTNOHAND) || (rc == ERESTART_RESTARTBLOCK) * * but is faster than a bunch of || */ if (unlikely(return_code <= -ERESTARTSYS) && (return_code >= -ERESTART_RESTARTBLOCK) && (return_code != -ENOIOCTLCMD)) context->return_code = -EINTR; else context->return_code = return_code; if (context->in_syscall && !context->dummy) { audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_EXIT]); audit_filter_inodes(tsk, context); } tsk->audit_context = NULL; return context; } Commit Message: audit: fix a double fetch in audit_log_single_execve_arg() There is a double fetch problem in audit_log_single_execve_arg() where we first check the execve(2) argumnets for any "bad" characters which would require hex encoding and then re-fetch the arguments for logging in the audit record[1]. Of course this leaves a window of opportunity for an unsavory application to munge with the data. This patch reworks things by only fetching the argument data once[2] into a buffer where it is scanned and logged into the audit records(s). In addition to fixing the double fetch, this patch improves on the original code in a few other ways: better handling of large arguments which require encoding, stricter record length checking, and some performance improvements (completely unverified, but we got rid of some strlen() calls, that's got to be a good thing). As part of the development of this patch, I've also created a basic regression test for the audit-testsuite, the test can be tracked on GitHub at the following link: * https://github.com/linux-audit/audit-testsuite/issues/25 [1] If you pay careful attention, there is actually a triple fetch problem due to a strnlen_user() call at the top of the function. [2] This is a tiny white lie, we do make a call to strnlen_user() prior to fetching the argument data. I don't like it, but due to the way the audit record is structured we really have no choice unless we copy the entire argument at once (which would require a rather wasteful allocation). The good news is that with this patch the kernel no longer relies on this strnlen_user() value for anything beyond recording it in the log, we also update it with a trustworthy value whenever possible. Reported-by: Pengfei Wang <[email protected]> Cc: <[email protected]> Signed-off-by: Paul Moore <[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 int msr_open(struct inode *inode, struct file *file) { unsigned int cpu; struct cpuinfo_x86 *c; cpu = iminor(file->f_path.dentry->d_inode); if (cpu >= nr_cpu_ids || !cpu_online(cpu)) return -ENXIO; /* No such CPU */ c = &cpu_data(cpu); if (!cpu_has(c, X86_FEATURE_MSR)) return -EIO; /* MSR not supported */ return 0; } Commit Message: x86/msr: Add capabilities check At the moment the MSR driver only relies upon file system checks. This means that anything as root with any capability set can write to MSRs. Historically that wasn't very interesting but on modern processors the MSRs are such that writing to them provides several ways to execute arbitary code in kernel space. Sample code and documentation on doing this is circulating and MSR attacks are used on Windows 64bit rootkits already. In the Linux case you still need to be able to open the device file so the impact is fairly limited and reduces the security of some capability and security model based systems down towards that of a generic "root owns the box" setup. Therefore they should require CAP_SYS_RAWIO to prevent an elevation of capabilities. The impact of this is fairly minimal on most setups because they don't have heavy use of capabilities. Those using SELinux, SMACK or AppArmor rules might want to consider if their rulesets on the MSR driver could be tighter. Signed-off-by: Alan Cox <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Horses <[email protected]> Signed-off-by: Ingo Molnar <[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 int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac, struct ceph_authorizer *a, size_t len) { struct ceph_x_authorizer *au = (void *)a; struct ceph_x_ticket_handler *th; int ret = 0; struct ceph_x_authorize_reply reply; void *p = au->reply_buf; void *end = p + sizeof(au->reply_buf); th = get_ticket_handler(ac, au->service); if (IS_ERR(th)) return PTR_ERR(th); ret = ceph_x_decrypt(&th->session_key, &p, end, &reply, sizeof(reply)); if (ret < 0) return ret; if (ret != sizeof(reply)) return -EPERM; if (au->nonce + 1 != le64_to_cpu(reply.nonce_plus_one)) ret = -EPERM; else ret = 0; dout("verify_authorizer_reply nonce %llx got %llx ret %d\n", au->nonce, le64_to_cpu(reply.nonce_plus_one), ret); return ret; } Commit Message: libceph: do not hard code max auth ticket len We hard code cephx auth ticket buffer size to 256 bytes. This isn't enough for any moderate setups and, in case tickets themselves are not encrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but ceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the buffer is allocated dynamically anyway, allocated it a bit later, at the point where we know how much is going to be needed. Fixes: http://tracker.ceph.com/issues/8979 Cc: [email protected] Signed-off-by: Ilya Dryomov <[email protected]> Reviewed-by: Sage Weil <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: RelayCreateTemporary( scoped_refptr<base::MessageLoopProxy> message_loop_proxy, int additional_file_flags, base::FileUtilProxy::CreateTemporaryCallback* callback) : message_loop_proxy_(message_loop_proxy), additional_file_flags_(additional_file_flags), callback_(callback), file_handle_(base::kInvalidPlatformFileValue) { DCHECK(callback); } Commit Message: Fix a small leak in FileUtilProxy BUG=none TEST=green mem bots Review URL: http://codereview.chromium.org/7669046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 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: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); } Commit Message: (for 4.9.3) CVE-2018-14464/LMP: Add a missing bounds check In lmp_print_data_link_subobjs(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 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 sctp_close(struct sock *sk, long timeout) { struct net *net = sock_net(sk); struct sctp_endpoint *ep; struct sctp_association *asoc; struct list_head *pos, *temp; unsigned int data_was_unread; pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout); lock_sock(sk); sk->sk_shutdown = SHUTDOWN_MASK; sk->sk_state = SCTP_SS_CLOSING; ep = sctp_sk(sk)->ep; /* Clean up any skbs sitting on the receive queue. */ data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue); data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby); /* Walk all associations on an endpoint. */ list_for_each_safe(pos, temp, &ep->asocs) { asoc = list_entry(pos, struct sctp_association, asocs); if (sctp_style(sk, TCP)) { /* A closed association can still be in the list if * it belongs to a TCP-style listening socket that is * not yet accepted. If so, free it. If not, send an * ABORT or SHUTDOWN based on the linger options. */ if (sctp_state(asoc, CLOSED)) { sctp_unhash_established(asoc); sctp_association_free(asoc); continue; } } if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) || !skb_queue_empty(&asoc->ulpq.reasm) || (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) { struct sctp_chunk *chunk; chunk = sctp_make_abort_user(asoc, NULL, 0); if (chunk) sctp_primitive_ABORT(net, asoc, chunk); } else sctp_primitive_SHUTDOWN(net, asoc, NULL); } /* On a TCP-style socket, block for at most linger_time if set. */ if (sctp_style(sk, TCP) && timeout) sctp_wait_for_close(sk, timeout); /* This will run the backlog queue. */ release_sock(sk); /* Supposedly, no process has access to the socket, but * the net layers still may. */ local_bh_disable(); bh_lock_sock(sk); /* Hold the sock, since sk_common_release() will put sock_put() * and we have just a little more cleanup. */ sock_hold(sk); sk_common_release(sk); bh_unlock_sock(sk); local_bh_enable(); sock_put(sk); SCTP_DBG_OBJCNT_DEC(sock); } Commit Message: sctp: fix ASCONF list handling ->auto_asconf_splist is per namespace and mangled by functions like sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization. Also, the call to inet_sk_copy_descendant() was backuping ->auto_asconf_list through the copy but was not honoring ->do_auto_asconf, which could lead to list corruption if it was different between both sockets. This commit thus fixes the list handling by using ->addr_wq_lock spinlock to protect the list. A special handling is done upon socket creation and destruction for that. Error handlig on sctp_init_sock() will never return an error after having initialized asconf, so sctp_destroy_sock() can be called without addrq_wq_lock. The lock now will be take on sctp_close_sock(), before locking the socket, so we don't do it in inverse order compared to sctp_addr_wq_timeout_handler(). Instead of taking the lock on sctp_sock_migrate() for copying and restoring the list values, it's preferred to avoid rewritting it by implementing sctp_copy_descendant(). Issue was found with a test application that kept flipping sysctl default_auto_asconf on and off, but one could trigger it by issuing simultaneous setsockopt() calls on multiple sockets or by creating/destroying sockets fast enough. This is only triggerable locally. Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).") Reported-by: Ji Jianwen <[email protected]> Suggested-by: Neil Horman <[email protected]> Suggested-by: Hannes Frederic Sowa <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoClearBufferfv( GLenum buffer, GLint drawbuffers, const volatile GLfloat* value) { api()->glClearBufferfvFn(buffer, drawbuffers, const_cast<const GLfloat*>(value)); 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: static void vapic_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); dc->reset = vapic_reset; dc->vmsd = &vmstate_vapic; dc->realize = vapic_realize; } 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 skcipher_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t ignored, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm( &ctx->req)); struct skcipher_sg_list *sgl; struct scatterlist *sg; unsigned long iovlen; struct iovec *iov; int err = -EAGAIN; int used; long copied = 0; lock_sock(sk); for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0; iovlen--, iov++) { unsigned long seglen = iov->iov_len; char __user *from = iov->iov_base; while (seglen) { sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list, list); sg = sgl->sg; while (!sg->length) sg++; used = ctx->used; if (!used) { err = skcipher_wait_for_data(sk, flags); if (err) goto unlock; } used = min_t(unsigned long, used, seglen); used = af_alg_make_sg(&ctx->rsgl, from, used, 1); err = used; if (err < 0) goto unlock; if (ctx->more || used < ctx->used) used -= used % bs; err = -EINVAL; if (!used) goto free; ablkcipher_request_set_crypt(&ctx->req, sg, ctx->rsgl.sg, used, ctx->iv); err = af_alg_wait_for_completion( ctx->enc ? crypto_ablkcipher_encrypt(&ctx->req) : crypto_ablkcipher_decrypt(&ctx->req), &ctx->completion); free: af_alg_free_sg(&ctx->rsgl); if (err) goto unlock; copied += used; from += used; seglen -= used; skcipher_pull_sgl(sk, used); } } err = 0; unlock: skcipher_wmem_wakeup(sk); release_sock(sk); return copied ?: err; } Commit Message: crypto: algif - suppress sending source address information in recvmsg The current code does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that. Cc: <[email protected]> # 2.6.38 Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: static int entersafe_match_card(sc_card_t *card) { int i; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); i = _sc_match_atr(card, entersafe_atrs, &card->type); if (i < 0) return 0; return 1; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. 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: e1000_autoneg_timer(void *opaque) { E1000State *s = opaque; s->nic->nc.link_down = false; e1000_link_up(s); s->phy_reg[PHY_STATUS] |= MII_SR_AUTONEG_COMPLETE; DBGOUT(PHY, "Auto negotiation is completed\n"); } 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 _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { if (parser->level <= XML_MAXLEVEL) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } efree(tag_name); } } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static MagickBooleanType ProcessMSLScript(const ImageInfo *image_info, Image **image,ExceptionInfo *exception) { char message[MaxTextExtent]; Image *msl_image; int status; ssize_t n; MSLInfo msl_info; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* 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(image != (Image **) NULL); msl_image=AcquireImage(image_info); status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", msl_image->filename); msl_image=DestroyImageList(msl_image); return(MagickFalse); } msl_image->columns=1; msl_image->rows=1; /* Parse MSL file. */ (void) ResetMagickMemory(&msl_info,0,sizeof(msl_info)); msl_info.exception=exception; msl_info.image_info=(ImageInfo **) AcquireMagickMemory( sizeof(*msl_info.image_info)); msl_info.draw_info=(DrawInfo **) AcquireMagickMemory( sizeof(*msl_info.draw_info)); /* top of the stack is the MSL file itself */ msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image)); msl_info.attributes=(Image **) AcquireMagickMemory( sizeof(*msl_info.attributes)); msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory( sizeof(*msl_info.group_info)); if ((msl_info.image_info == (ImageInfo **) NULL) || (msl_info.image == (Image **) NULL) || (msl_info.attributes == (Image **) NULL) || (msl_info.group_info == (MSLGroupInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError, "UnableToInterpretMSLImage"); *msl_info.image_info=CloneImageInfo(image_info); *msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); *msl_info.attributes=AcquireImage(image_info); msl_info.group_info[0].numImages=0; /* the first slot is used to point to the MSL file image */ *msl_info.image=msl_image; if (*image != (Image *) NULL) MSLPushImage(&msl_info,*image); (void) xmlSubstituteEntitiesDefault(1); (void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=MSLInternalSubset; sax_modules.isStandalone=MSLIsStandalone; sax_modules.hasInternalSubset=MSLHasInternalSubset; sax_modules.hasExternalSubset=MSLHasExternalSubset; sax_modules.resolveEntity=MSLResolveEntity; sax_modules.getEntity=MSLGetEntity; sax_modules.entityDecl=MSLEntityDeclaration; sax_modules.notationDecl=MSLNotationDeclaration; sax_modules.attributeDecl=MSLAttributeDeclaration; sax_modules.elementDecl=MSLElementDeclaration; sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration; sax_modules.setDocumentLocator=MSLSetDocumentLocator; sax_modules.startDocument=MSLStartDocument; sax_modules.endDocument=MSLEndDocument; sax_modules.startElement=MSLStartElement; sax_modules.endElement=MSLEndElement; sax_modules.reference=MSLReference; sax_modules.characters=MSLCharacters; sax_modules.ignorableWhitespace=MSLIgnorableWhitespace; sax_modules.processingInstruction=MSLProcessingInstructions; sax_modules.comment=MSLComment; sax_modules.warning=MSLWarning; sax_modules.error=MSLError; sax_modules.fatalError=MSLError; sax_modules.getParameterEntity=MSLGetParameterEntity; sax_modules.cdataBlock=MSLCDataBlock; sax_modules.externalSubset=MSLExternalSubset; sax_handler=(&sax_modules); msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0, msl_image->filename); while (ReadBlobString(msl_image,message) != (char *) NULL) { n=(ssize_t) strlen(message); if (n == 0) continue; status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse); if (status != 0) break; (void) xmlParseChunk(msl_info.parser," ",1,MagickFalse); if (msl_info.exception->severity >= ErrorException) break; } if (msl_info.exception->severity == UndefinedException) (void) xmlParseChunk(msl_info.parser," ",1,MagickTrue); xmlFreeParserCtxt(msl_info.parser); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory( msl_info.group_info); if (*image == (Image *) NULL) *image=(*msl_info.image); if ((*msl_info.image)->exception.severity != UndefinedException) return(MagickFalse); return(MagickTrue); } Commit Message: Prevent fault in MSL interpreter 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 _make_words(char *l,long n,ogg_uint32_t *r,long quantvals, codebook *b, oggpack_buffer *opb,int maptype){ long i,j,count=0; long top=0; ogg_uint32_t marker[MARKER_SIZE]; if (n<1) return 1; if(n<2){ r[0]=0x80000000; }else{ memset(marker,0,sizeof(marker)); for(i=0;i<n;i++){ long length=l[i]; if(length){ if (length < 0 || length >= MARKER_SIZE) { ALOGE("b/23881715"); return 1; } ogg_uint32_t entry=marker[length]; long chase=0; if(count && !entry)return -1; /* overpopulated tree! */ /* chase the tree as far as it's already populated, fill in past */ for(j=0;j<length-1;j++){ int bit=(entry>>(length-j-1))&1; if(chase>=top){ if (chase < 0 || chase >= n) return 1; top++; r[chase*2]=top; r[chase*2+1]=0; }else if (chase < 0 || chase >= n || chase*2+bit > n*2+1) return 1; if(!r[chase*2+bit]) r[chase*2+bit]=top; chase=r[chase*2+bit]; if (chase < 0 || chase >= n) return 1; } { int bit=(entry>>(length-j-1))&1; if(chase>=top){ top++; r[chase*2+1]=0; } r[chase*2+bit]= decpack(i,count++,quantvals,b,opb,maptype) | 0x80000000; } /* Look to see if the next shorter marker points to the node above. if so, update it and repeat. */ for(j=length;j>0;j--){ if(marker[j]&1){ marker[j]=marker[j-1]<<1; break; } marker[j]++; } /* prune the tree; the implicit invariant says all the longer markers were dangling from our just-taken node. Dangle them from our *new* node. */ for(j=length+1;j<MARKER_SIZE;j++) if((marker[j]>>1) == entry){ entry=marker[j]; marker[j]=marker[j-1]<<1; }else break; } } } /* sanity check the huffman tree; an underpopulated tree must be rejected. The only exception is the one-node pseudo-nil tree, which appears to be underpopulated because the tree doesn't really exist; there's only one possible 'codeword' or zero bits, but the above tree-gen code doesn't mark that. */ if(b->used_entries != 1){ for(i=1;i<MARKER_SIZE;i++) if(marker[i] & (0xffffffffUL>>(32-i))){ return 1; } } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200 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 XMLTreeInfo *NewXMLTree(const char *xml,ExceptionInfo *exception) { char **attribute, **attributes, *tag, *utf8; int c, terminal; MagickBooleanType status; register char *p; register ssize_t i; size_t ignore_depth, length; ssize_t j, l; XMLTreeRoot *root; /* Convert xml-string to UTF8. */ if ((xml == (const char *) NULL) || (strlen(xml) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","root tag missing"); return((XMLTreeInfo *) NULL); } root=(XMLTreeRoot *) NewXMLTreeTag((char *) NULL); length=strlen(xml); utf8=ConvertUTF16ToUTF8(xml,&length); if (utf8 == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","UTF16 to UTF8 failed"); return((XMLTreeInfo *) NULL); } terminal=utf8[length-1]; utf8[length-1]='\0'; p=utf8; while ((*p != '\0') && (*p != '<')) p++; if (*p == '\0') { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","root tag missing"); utf8=DestroyString(utf8); return((XMLTreeInfo *) NULL); } attribute=(char **) NULL; l=0; ignore_depth=0; for (p++; ; p++) { attributes=(char **) sentinel; tag=p; c=(*p); if ((isalpha((int) ((unsigned char) *p)) !=0) || (*p == '_') || (*p == ':') || (c < '\0')) { /* Tag. */ if (root->node == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","root tag missing"); utf8=DestroyString(utf8); return(&root->root); } p+=strcspn(p,XMLWhitespace "/>"); while (isspace((int) ((unsigned char) *p)) != 0) *p++='\0'; if (ignore_depth == 0) { if ((*p != '\0') && (*p != '/') && (*p != '>')) { /* Find tag in default attributes list. */ i=0; while ((root->attributes[i] != (char **) NULL) && (strcmp(root->attributes[i][0],tag) != 0)) i++; attribute=root->attributes[i]; } for (l=0; (*p != '\0') && (*p != '/') && (*p != '>'); l+=2) { /* Attribute. */ if (l == 0) attributes=(char **) AcquireQuantumMemory(4, sizeof(*attributes)); else attributes=(char **) ResizeQuantumMemory(attributes, (size_t) (l+4),sizeof(*attributes)); if (attributes == (char **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); utf8=DestroyString(utf8); return(&root->root); } attributes[l+2]=(char *) NULL; attributes[l+1]=(char *) NULL; attributes[l]=p; p+=strcspn(p,XMLWhitespace "=/>"); if ((*p != '=') && (isspace((int) ((unsigned char) *p)) == 0)) attributes[l]=ConstantString(""); else { *p++='\0'; p+=strspn(p,XMLWhitespace "="); c=(*p); if ((c == '"') || (c == '\'')) { /* Attributes value. */ p++; attributes[l+1]=p; while ((*p != '\0') && (*p != c)) p++; if (*p != '\0') *p++='\0'; else { attributes[l]=ConstantString(""); attributes[l+1]=ConstantString(""); (void) DestroyXMLTreeAttributes(attributes); (void) ThrowMagickException(exception, GetMagickModule(),OptionWarning,"ParseError", "missing %c",c); utf8=DestroyString(utf8); return(&root->root); } j=1; while ((attribute != (char **) NULL) && (attribute[j] != (char *) NULL) && (strcmp(attribute[j],attributes[l]) != 0)) j+=3; attributes[l+1]=ParseEntities(attributes[l+1], root->entities,(attribute != (char **) NULL) && (attribute[j] != (char *) NULL) ? *attribute[j+2] : ' '); } attributes[l]=ConstantString(attributes[l]); } while (isspace((int) ((unsigned char) *p)) != 0) p++; } } else { while((*p != '\0') && (*p != '/') && (*p != '>')) p++; } if (*p == '/') { /* Self closing tag. */ *p++='\0'; if (((*p != '\0') && (*p != '>')) || ((*p == '\0') && (terminal != '>'))) { if (l != 0) (void) DestroyXMLTreeAttributes(attributes); (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","missing >"); utf8=DestroyString(utf8); return(&root->root); } if ((ignore_depth == 0) && (IsSkipTag(tag) == MagickFalse)) { ParseOpenTag(root,tag,attributes); (void) ParseCloseTag(root,tag,exception); } } else { c=(*p); if ((*p == '>') || ((*p == '\0') && (terminal == '>'))) { *p='\0'; if ((ignore_depth == 0) && (IsSkipTag(tag) == MagickFalse)) ParseOpenTag(root,tag,attributes); else ignore_depth++; *p=c; } else { if (l != 0) (void) DestroyXMLTreeAttributes(attributes); (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","missing >"); utf8=DestroyString(utf8); return(&root->root); } } } else if (*p == '/') { /* Close tag. */ tag=p+1; p+=strcspn(tag,XMLWhitespace ">")+1; c=(*p); if ((c == '\0') && (terminal != '>')) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","missing >"); utf8=DestroyString(utf8); return(&root->root); } *p='\0'; if (ignore_depth == 0 && ParseCloseTag(root,tag,exception) != (XMLTreeInfo *) NULL) { utf8=DestroyString(utf8); return(&root->root); } if (ignore_depth > 0) ignore_depth--; *p=c; if (isspace((int) ((unsigned char) *p)) != 0) p+=strspn(p,XMLWhitespace); } else if (strncmp(p,"!--",3) == 0) { /* Comment. */ p=strstr(p+3,"--"); if ((p == (char *) NULL) || ((*(p+=2) != '>') && (*p != '\0')) || ((*p == '\0') && (terminal != '>'))) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unclosed <!--"); utf8=DestroyString(utf8); return(&root->root); } } else if (strncmp(p,"![CDATA[",8) == 0) { /* Cdata. */ p=strstr(p,"]]>"); if (p != (char *) NULL) { p+=2; if (ignore_depth == 0) ParseCharacterContent(root,tag+8,(size_t) (p-tag-10),'c'); } else { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unclosed <![CDATA["); utf8=DestroyString(utf8); return(&root->root); } } else if (strncmp(p,"!DOCTYPE",8) == 0) { /* DTD. */ for (l=0; (*p != '\0') && (((l == 0) && (*p != '>')) || ((l != 0) && ((*p != ']') || (*(p+strspn(p+1,XMLWhitespace)+1) != '>')))); l=(ssize_t) ((*p == '[') ? 1 : l)) p+=strcspn(p+1,"[]>")+1; if ((*p == '\0') && (terminal != '>')) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unclosed <!DOCTYPE"); utf8=DestroyString(utf8); return(&root->root); } if (l != 0) tag=strchr(tag,'[')+1; if (l != 0) { status=ParseInternalDoctype(root,tag,(size_t) (p-tag), exception); if (status == MagickFalse) { utf8=DestroyString(utf8); return(&root->root); } p++; } } else if (*p == '?') { /* Processing instructions. */ do { p=strchr(p,'?'); if (p == (char *) NULL) break; p++; } while ((*p != '\0') && (*p != '>')); if ((p == (char *) NULL) || ((*p == '\0') && (terminal != '>'))) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unclosed <?"); utf8=DestroyString(utf8); return(&root->root); } ParseProcessingInstructions(root,tag+1,(size_t) (p-tag-2)); } else { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unexpected <"); utf8=DestroyString(utf8); return(&root->root); } if ((p == (char *) NULL) || (*p == '\0')) break; *p++='\0'; tag=p; if ((*p != '\0') && (*p != '<')) { /* Tag character content. */ while ((*p != '\0') && (*p != '<')) p++; if (*p == '\0') break; if (ignore_depth == 0) ParseCharacterContent(root,tag,(size_t) (p-tag),'&'); } else if (*p == '\0') break; } utf8=DestroyString(utf8); if (root->node == (XMLTreeInfo *) NULL) return(&root->root); if (root->node->tag == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","root tag missing"); return(&root->root); } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","unclosed tag: `%s'",root->node->tag); return(&root->root); } Commit Message: Coder path traversal is not authorized, bug report provided by Masaaki Chida CWE ID: CWE-22 Target: 1 Example 2: Code: GLenum Framebuffer::GetDrawBuffer(GLenum draw_buffer) const { GLsizei index = static_cast<GLsizei>( draw_buffer - GL_DRAW_BUFFER0_ARB); CHECK(index >= 0 && index < static_cast<GLsizei>(manager_->max_draw_buffers_)); return draw_buffers_[index]; } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 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 die_if_kernel(const char *str, struct pt_regs *regs, long err) { if (!user_mode(regs)) die(str, regs, err); } 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 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 WebMediaPlayerMS::HasSingleSecurityOrigin() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } 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: 1 Example 2: Code: xfs_attr_shortform_getvalue(xfs_da_args_t *args) { xfs_attr_shortform_t *sf; xfs_attr_sf_entry_t *sfe; int i; ASSERT(args->dp->i_afp->if_flags == XFS_IFINLINE); sf = (xfs_attr_shortform_t *)args->dp->i_afp->if_u1.if_data; sfe = &sf->list[0]; for (i = 0; i < sf->hdr.count; sfe = XFS_ATTR_SF_NEXTENTRY(sfe), i++) { if (sfe->namelen != args->namelen) continue; if (memcmp(args->name, sfe->nameval, args->namelen) != 0) continue; if (!xfs_attr_namesp_match(args->flags, sfe->flags)) continue; if (args->flags & ATTR_KERNOVAL) { args->valuelen = sfe->valuelen; return -EEXIST; } if (args->valuelen < sfe->valuelen) { args->valuelen = sfe->valuelen; return -ERANGE; } args->valuelen = sfe->valuelen; memcpy(args->value, &sfe->nameval[args->namelen], args->valuelen); return -EEXIST; } return -ENOATTR; } Commit Message: xfs: don't call xfs_da_shrink_inode with NULL bp xfs_attr3_leaf_create may have errored out before instantiating a buffer, for example if the blkno is out of range. In that case there is no work to do to remove it, and in fact xfs_da_shrink_inode will lead to an oops if we try. This also seems to fix a flaw where the original error from xfs_attr3_leaf_create gets overwritten in the cleanup case, and it removes a pointless assignment to bp which isn't used after this. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199969 Reported-by: Xu, Wen <[email protected]> Tested-by: Xu, Wen <[email protected]> Signed-off-by: Eric Sandeen <[email protected]> Reviewed-by: Darrick J. Wong <[email protected]> Signed-off-by: Darrick J. Wong <[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: xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlElementContentPtr *result) { xmlElementContentPtr tree = NULL; int inputid = ctxt->input->id; int res; *result = NULL; if (RAW != '(') { xmlFatalErrMsgStr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, "xmlParseElementContentDecl : %s '(' expected\n", name); return(-1); } NEXT; GROW; SKIP_BLANKS; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { tree = xmlParseElementMixedContentDecl(ctxt, inputid); res = XML_ELEMENT_TYPE_MIXED; } else { tree = xmlParseElementChildrenContentDeclPriv(ctxt, inputid, 1); res = XML_ELEMENT_TYPE_ELEMENT; } SKIP_BLANKS; *result = tree; return(res); } 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 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 WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); image = CloneImage(IMimage,0,0,MagickFalse,exception); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); if (image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->alpha_trait=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (Magick_png_color_equal(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (Magick_png_color_equal(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (Magick_png_color_equal(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha/2 ? TransparentAlpha : OpaqueAlpha); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",IMimage->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates "-define png:compression-strategy", etc. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { /* Add an opaque matte channel */ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { /* Do not write hex-encoded ICC chunk */ name=GetNextImageProfile(image); continue; } } #endif /* WRITE_iCCP */ if (LocaleCompare(name,"exif") == 0) { /* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk */ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXt chunk with uuencoded %s profile", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); /* write exIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; /* otherwise crashes */ } /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/58 CWE ID: CWE-476 Target: 1 Example 2: Code: bool FrameSelection::IsHidden() const { if (SelectionHasFocus()) return false; const Node* start = ComputeVisibleSelectionInDOMTree().Start().ComputeContainerNode(); if (!start) return true; if (!GetSelectionInDOMTree().IsRange()) return true; return EnclosingTextControl(start); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} 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 xcbc_init_tfm(struct crypto_tfm *tfm) { struct crypto_cipher *cipher; struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_spawn *spawn = crypto_instance_ctx(inst); struct xcbc_tfm_ctx *ctx = crypto_tfm_ctx(tfm); cipher = crypto_spawn_cipher(spawn); if (IS_ERR(cipher)) return PTR_ERR(cipher); ctx->child = cipher; return 0; }; Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[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: void PrintPreviewUI::OnReusePreviewData(int preview_request_id) { base::StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("reloadPreviewPages", ui_identifier, ui_preview_request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200 Target: 1 Example 2: Code: ftp_get(ftpbuf_t *ftp, php_stream *outstream, const char *path, ftptype_t type, long resumepos TSRMLS_DC) { databuf_t *data = NULL; int lastch; size_t rcvd; char arg[11]; if (ftp == NULL) { return 0; } if (!ftp_type(ftp, type)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (resumepos > 0) { snprintf(arg, sizeof(arg), "%ld", resumepos); if (!ftp_putcmd(ftp, "REST", arg)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 350)) { goto bail; } } if (!ftp_putcmd(ftp, "RETR", path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125)) { goto bail; } if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } lastch = 0; while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) { if (rcvd == -1) { goto bail; } if (type == FTPTYPE_ASCII) { #ifndef PHP_WIN32 char *s; #endif char *ptr = data->buf; char *e = ptr + rcvd; /* logic depends on the OS EOL * Win32 -> \r\n * Everything Else \n */ #ifdef PHP_WIN32 php_stream_write(outstream, ptr, (e - ptr)); ptr = e; #else while (e > ptr && (s = memchr(ptr, '\r', (e - ptr)))) { php_stream_write(outstream, ptr, (s - ptr)); if (*(s + 1) == '\n') { s++; php_stream_putc(outstream, '\n'); } ptr = s + 1; } #endif if (ptr < e) { php_stream_write(outstream, ptr, (e - ptr)); } } else if (rcvd != php_stream_write(outstream, data->buf, rcvd)) { goto bail; } } ftp->data = data = data_close(ftp, data); if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) { goto bail; } return 1; bail: ftp->data = data_close(ftp, data); 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 kgdb_ll_trap(int cmd, const char *str, struct pt_regs *regs, long err, int trap, int sig) { struct die_args args = { .regs = regs, .str = str, .err = err, .trapnr = trap, .signr = sig, }; if (!kgdb_io_module_registered) return NOTIFY_DONE; return __kgdb_notify(&args, cmd); } 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 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 PlatformSensorProviderBase::CreateSensor( mojom::SensorType type, const CreateSensorCallback& callback) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!CreateSharedBufferIfNeeded()) { callback.Run(nullptr); return; } mojo::ScopedSharedBufferMapping mapping = MapSharedBufferForType(type); if (!mapping) { callback.Run(nullptr); return; } auto it = requests_map_.find(type); if (it != requests_map_.end()) { it->second.push_back(callback); } else { // This is the first CreateSensor call. requests_map_[type] = CallbackQueue({callback}); CreateSensorInternal( type, std::move(mapping), base::Bind(&PlatformSensorProviderBase::NotifySensorCreated, base::Unretained(this), type)); } } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Target: 1 Example 2: Code: int bat_socket_setup(struct bat_priv *bat_priv) { struct dentry *d; if (!bat_priv->debug_dir) goto err; d = debugfs_create_file(ICMP_SOCKET, S_IFREG | S_IWUSR | S_IRUSR, bat_priv->debug_dir, bat_priv, &fops); if (d) goto err; return 0; err: return 1; } Commit Message: batman-adv: Only write requested number of byte to user buffer Don't write more than the requested number of bytes of an batman-adv icmp packet to the userspace buffer. Otherwise unrelated userspace memory might get overridden by the kernel. Signed-off-by: Sven Eckelmann <[email protected]> Signed-off-by: Marek Lindner <[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 int lua_ap_regex(lua_State *L) { request_rec *r; int i, rv, flags; const char *pattern, *source; char *err; ap_regex_t regex; ap_regmatch_t matches[MODLUA_MAX_REG_MATCH+1]; luaL_checktype(L, 1, LUA_TUSERDATA); luaL_checktype(L, 2, LUA_TSTRING); luaL_checktype(L, 3, LUA_TSTRING); r = ap_lua_check_request_rec(L, 1); source = lua_tostring(L, 2); pattern = lua_tostring(L, 3); flags = luaL_optinteger(L, 4, 0); rv = ap_regcomp(&regex, pattern, flags); if (rv) { lua_pushboolean(L, 0); err = apr_palloc(r->pool, 256); ap_regerror(rv, &regex, err, 256); lua_pushstring(L, err); return 2; } if (regex.re_nsub > MODLUA_MAX_REG_MATCH) { lua_pushboolean(L, 0); err = apr_palloc(r->pool, 64); apr_snprintf(err, 64, "regcomp found %d matches; only %d allowed.", regex.re_nsub, MODLUA_MAX_REG_MATCH); lua_pushstring(L, err); return 2; } rv = ap_regexec(&regex, source, MODLUA_MAX_REG_MATCH, matches, 0); if (rv == AP_REG_NOMATCH) { lua_pushboolean(L, 0); return 1; } lua_newtable(L); for (i = 0; i <= regex.re_nsub; i++) { lua_pushinteger(L, i); if (matches[i].rm_so >= 0 && matches[i].rm_eo >= 0) lua_pushstring(L, apr_pstrndup(r->pool, source + matches[i].rm_so, matches[i].rm_eo - matches[i].rm_so)); else lua_pushnil(L); lua_settable(L, -3); } return 1; } Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org) mod_lua: A maliciously crafted websockets PING after a script calls r:wsupgrade() can cause a child process crash. [Edward Lu <Chaosed0 gmail.com>] Discovered by Guido Vranken <guidovranken gmail.com> Submitted by: Edward Lu Committed by: covener git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-20 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 ZeroSuggestProvider::Start(const AutocompleteInput& input, bool minimal_changes) { TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start"); matches_.clear(); if (!input.from_omnibox_focus() || client()->IsOffTheRecord() || input.type() == metrics::OmniboxInputType::INVALID) return; Stop(true, false); set_field_trial_triggered(false); set_field_trial_triggered_in_session(false); results_from_cache_ = false; permanent_text_ = input.text(); current_query_ = input.current_url().spec(); current_title_ = input.current_title(); current_page_classification_ = input.current_page_classification(); current_url_match_ = MatchForCurrentURL(); std::string url_string = GetContextualSuggestionsUrl(); GURL suggest_url(url_string); if (!suggest_url.is_valid()) return; const TemplateURLService* template_url_service = client()->GetTemplateURLService(); const TemplateURL* default_provider = template_url_service->GetDefaultSearchProvider(); const bool can_send_current_url = CanSendURL(input.current_url(), suggest_url, default_provider, current_page_classification_, template_url_service->search_terms_data(), client()); GURL arbitrary_insecure_url(kArbitraryInsecureUrlString); ZeroSuggestEligibility eligibility = ZeroSuggestEligibility::ELIGIBLE; if (!can_send_current_url) { const bool can_send_ordinary_url = CanSendURL(arbitrary_insecure_url, suggest_url, default_provider, current_page_classification_, template_url_service->search_terms_data(), client()); eligibility = can_send_ordinary_url ? ZeroSuggestEligibility::URL_INELIGIBLE : ZeroSuggestEligibility::GENERALLY_INELIGIBLE; } UMA_HISTOGRAM_ENUMERATION( "Omnibox.ZeroSuggest.Eligible.OnFocus", static_cast<int>(eligibility), static_cast<int>(ZeroSuggestEligibility::ELIGIBLE_MAX_VALUE)); if (can_send_current_url && !OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() && !OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) { if (OmniboxFieldTrial::InZeroSuggestRedirectToChromeFieldTrial()) { url_string += "/url=" + net::EscapePath(current_query_) + OmniboxFieldTrial::ZeroSuggestRedirectToChromeAdditionalFields(); suggest_url = GURL(url_string); } else { base::string16 prefix; TemplateURLRef::SearchTermsArgs search_term_args(prefix); search_term_args.current_page_url = current_query_; suggest_url = GURL(default_provider->suggestions_url_ref().ReplaceSearchTerms( search_term_args, template_url_service->search_terms_data())); } } else if (!ShouldShowNonContextualZeroSuggest(input.current_url())) { return; } done_ = false; MaybeUseCachedSuggestions(); Run(suggest_url); } Commit Message: Provide experimental contextual suggestions when current URL comes from a google domain. The counts for the Omnibox.ZeroSuggestRequests historgram are 35% smaller for groups that are running under the ZeroSuggestRedirectToChrome flag. Note that previous to this CL, a request was not made when the user was visiting an HTTPS page and the domain of the current was different from that of the service providing zero suggestions. This CL addresses this restrictions by making sure that requests are sent to the experimental service when Google is the default search engine AND the same request was validated to be sent to Google. BUG=692471 Review-Url: https://codereview.chromium.org/2915163003 Cr-Commit-Position: refs/heads/master@{#476786} CWE ID: Target: 1 Example 2: Code: static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } 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); } } return(MagickTrue); } Commit Message: 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: gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors, int *pexit_code, ref * perror_object) { ref *epref = pref; ref doref; ref *perrordict; ref error_name; int code, ccode; ref saref; i_ctx_t *i_ctx_p = *pi_ctx_p; int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal; *pexit_code = 0; *gc_signal = 0; ialloc_reset_requested(idmemory); again: /* Avoid a dangling error object that might get traced by a future GC. */ make_null(perror_object); o_stack.requested = e_stack.requested = d_stack.requested = 0; while (*gc_signal) { /* Some routine below triggered a GC. */ gs_gc_root_t epref_root; *gc_signal = 0; /* Make sure that doref will get relocated properly if */ /* a garbage collection happens with epref == &doref. */ gs_register_ref_root(imemory_system, &epref_root, (void **)&epref, "gs_call_interp(epref)"); code = interp_reclaim(pi_ctx_p, -1); i_ctx_p = *pi_ctx_p; gs_unregister_root(imemory_system, &epref_root, "gs_call_interp(epref)"); if (code < 0) return code; } code = interp(pi_ctx_p, epref, perror_object); i_ctx_p = *pi_ctx_p; if (!r_has_type(&i_ctx_p->error_object, t__invalid)) { *perror_object = i_ctx_p->error_object; make_t(&i_ctx_p->error_object, t__invalid); } /* Prevent a dangling reference to the GC signal in ticks_left */ /* in the frame of interp, but be prepared to do a GC if */ /* an allocation in this routine asks for it. */ *gc_signal = 0; set_gc_signal(i_ctx_p, 1); if (esp < esbot) /* popped guard entry */ esp = esbot; switch (code) { case gs_error_Fatal: *pexit_code = 255; return code; case gs_error_Quit: *perror_object = osp[-1]; *pexit_code = code = osp->value.intval; osp -= 2; return (code == 0 ? gs_error_Quit : code < 0 && code > -100 ? code : gs_error_Fatal); case gs_error_InterpreterExit: return 0; case gs_error_ExecStackUnderflow: /****** WRONG -- must keep mark blocks intact ******/ ref_stack_pop_block(&e_stack); doref = *perror_object; epref = &doref; goto again; case gs_error_VMreclaim: /* Do the GC and continue. */ /* We ignore the return value here, if it fails here * we'll call it again having jumped to the "again" label. * Where, assuming it fails again, we'll handle the error. */ (void)interp_reclaim(pi_ctx_p, (osp->value.intval == 2 ? avm_global : avm_local)); i_ctx_p = *pi_ctx_p; make_oper(&doref, 0, zpop); epref = &doref; goto again; case gs_error_NeedInput: case gs_error_interrupt: return code; } /* Adjust osp in case of operand stack underflow */ if (osp < osbot - 1) osp = osbot - 1; /* We have to handle stack over/underflow specially, because */ /* we might be able to recover by adding or removing a block. */ switch (code) { case gs_error_dictstackoverflow: /* We don't have to handle this specially: */ /* The only places that could generate it */ /* use check_dstack, which does a ref_stack_extend, */ /* so if` we get this error, it's a real one. */ if (osp >= ostop) { if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) return ccode; } /* Skip system dictionaries for CET 20-02-02 */ ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref); if (ccode < 0) return ccode; ref_stack_pop_to(&d_stack, min_dstack_size); dict_set_top(); *++osp = saref; break; case gs_error_dictstackunderflow: if (ref_stack_pop_block(&d_stack) >= 0) { dict_set_top(); doref = *perror_object; epref = &doref; goto again; } break; case gs_error_execstackoverflow: /* We don't have to handle this specially: */ /* The only places that could generate it */ /* use check_estack, which does a ref_stack_extend, */ /* so if we get this error, it's a real one. */ if (osp >= ostop) { if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) return ccode; } ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref); if (ccode < 0) return ccode; { uint count = ref_stack_count(&e_stack); uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM; if (count > limit) { /* * If there is an e-stack mark within MIN_BLOCK_ESTACK of * the new top, cut the stack back to remove the mark. */ int skip = count - limit; int i; for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) { const ref *ep = ref_stack_index(&e_stack, i); if (r_has_type_attrs(ep, t_null, a_executable)) { skip = i + 1; break; } } pop_estack(i_ctx_p, skip); } } *++osp = saref; break; case gs_error_stackoverflow: if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */ /* it might be a procedure being pushed as a */ /* literal. We check for this case specially. */ doref = *perror_object; if (r_is_proc(&doref)) { *++osp = doref; make_null_proc(&doref); } epref = &doref; goto again; } ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref); if (ccode < 0) return ccode; ref_stack_clear(&o_stack); *++osp = saref; break; case gs_error_stackunderflow: if (ref_stack_pop_block(&o_stack) >= 0) { doref = *perror_object; epref = &doref; goto again; } break; } if (user_errors < 0) return code; if (gs_errorname(i_ctx_p, code, &error_name) < 0) return code; /* out-of-range error code! */ /* We refer to gserrordict first, which is not accessible to Postcript jobs * If we're running with SAFERERRORS all the handlers are copied to gserrordict * so we'll always find the default one. If not SAFERERRORS, only gs specific * errors are in gserrordict. */ if (dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 || (dict_find(perrordict, &error_name, &epref) <= 0 && (dict_find_string(systemdict, "errordict", &perrordict) <= 0 || dict_find(perrordict, &error_name, &epref) <= 0)) ) return code; /* error name not in errordict??? */ doref = *epref; epref = &doref; /* Push the error object on the operand stack if appropriate. */ if (!GS_ERROR_IS_INTERRUPT(code)) { /* Replace the error object if within an oparray or .errorexec. */ osp++; if (osp >= ostop) { } *osp = *perror_object; } *osp = *perror_object; errorexec_find(i_ctx_p, osp); /* If using SAFER, hand a name object to the error handler, rather than the executable * object/operator itself. */ if (i_ctx_p->LockFilePermissions) { code = obj_cvs(imemory, osp, buf + 2, 256, &rlen, (const byte **)&bufptr); if (code < 0) { const char *unknownstr = "--unknown--"; rlen = strlen(unknownstr); memcpy(buf, unknownstr, rlen); } else { buf[0] = buf[1] = buf[rlen + 2] = buf[rlen + 3] = '-'; rlen += 4; } code = name_ref(imemory, buf, rlen, osp, 1); if (code < 0) make_null(osp); } } Commit Message: CWE ID: CWE-209 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 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) { 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); 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); 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: fix race with concurrent install_user_keyrings() This fixes CVE-2013-1792. There is a race in install_user_keyrings() that can cause a NULL pointer dereference when called concurrently for the same user if the uid and uid-session keyrings are not yet created. It might be possible for an unprivileged user to trigger this by calling keyctl() from userspace in parallel immediately after logging in. Assume that we have two threads both executing lookup_user_key(), both looking for KEY_SPEC_USER_SESSION_KEYRING. THREAD A THREAD B =============================== =============================== ==>call install_user_keyrings(); if (!cred->user->session_keyring) ==>call install_user_keyrings() ... user->uid_keyring = uid_keyring; if (user->uid_keyring) return 0; <== key = cred->user->session_keyring [== NULL] user->session_keyring = session_keyring; atomic_inc(&key->usage); [oops] At the point thread A dereferences cred->user->session_keyring, thread B hasn't updated user->session_keyring yet, but thread A assumes it is populated because install_user_keyrings() returned ok. The race window is really small but can be exploited if, for example, thread B is interrupted or preempted after initializing uid_keyring, but before doing setting session_keyring. This couldn't be reproduced on a stock kernel. However, after placing systemtap probe on 'user->session_keyring = session_keyring;' that introduced some delay, the kernel could be crashed reliably. Fix this by checking both pointers before deciding whether to return. Alternatively, the test could be done away with entirely as it is checked inside the mutex - but since the mutex is global, that may not be the best way. Signed-off-by: David Howells <[email protected]> Reported-by: Mateusz Guzik <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: void SpeechRecognitionManagerImpl::SessionStart(const Session& session) { DCHECK_EQ(primary_session_id_, session.id); const MediaStreamDevices& devices = session.context.devices; std::string device_id; if (devices.empty()) { device_id = media::AudioDeviceDescription::kDefaultDeviceId; } else { DCHECK_EQ(1u, devices.size()); DCHECK_EQ(MEDIA_DEVICE_AUDIO_CAPTURE, devices.front().type); device_id = devices.front().id; } session.recognizer->StartRecognition(device_id); } 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 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 BlobURLRequestJob::DidGetFileItemLength(size_t index, int64 result) { if (error_) return; if (result == net::ERR_UPLOAD_FILE_CHANGED) { NotifyFailure(net::ERR_FILE_NOT_FOUND); return; } else if (result < 0) { NotifyFailure(result); return; } DCHECK_LT(index, blob_data_->items().size()); const BlobData::Item& item = blob_data_->items().at(index); DCHECK(IsFileType(item.type())); int64 item_length = static_cast<int64>(item.length()); if (item_length == -1) item_length = result - item.offset(); DCHECK_LT(index, item_length_list_.size()); item_length_list_[index] = item_length; total_size_ += item_length; if (--pending_get_file_info_count_ == 0) DidCountSize(net::OK); } Commit Message: Avoid integer overflows in BlobURLRequestJob. BUG=169685 Review URL: https://chromiumcodereview.appspot.com/12047012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 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 processRequest(struct reqelem * req) { ssize_t n; unsigned int l, m; unsigned char buf[2048]; const unsigned char * p; int type; struct device * d = devlist; unsigned char rbuf[4096]; unsigned char * rp = rbuf+1; unsigned char nrep = 0; time_t t; struct service * newserv = NULL; struct service * serv; n = read(req->socket, buf, sizeof(buf)); if(n<0) { if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) return; /* try again later */ syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket); goto error; } if(n==0) { syslog(LOG_INFO, "(s=%d) request connection closed", req->socket); goto error; } t = time(NULL); type = buf[0]; p = buf + 1; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(p+l > buf+n) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(l == 0 && type != 3) { syslog(LOG_WARNING, "bad request (length=0)"); goto error; } syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'", req->socket, type, l, p); switch(type) { case 1: /* request by type */ case 2: /* request by USN (unique id) */ case 3: /* everything */ while(d && (nrep < 255)) { if(d->t < t) { syslog(LOG_INFO, "outdated device"); } else { /* test if we can put more responses in the buffer */ if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l + d->headers[HEADER_USN].l + 6 + (rp - rbuf) >= (int)sizeof(rbuf)) break; if( (type==1 && 0==memcmp(d->headers[HEADER_NT].p, p, l)) ||(type==2 && 0==memcmp(d->headers[HEADER_USN].p, p, l)) ||(type==3) ) { /* response : * 1 - Location * 2 - NT (device/service type) * 3 - usn */ m = d->headers[HEADER_LOCATION].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l); rp += d->headers[HEADER_LOCATION].l; m = d->headers[HEADER_NT].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l); rp += d->headers[HEADER_NT].l; m = d->headers[HEADER_USN].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l); rp += d->headers[HEADER_USN].l; nrep++; } } d = d->next; } /* Also look in service list */ for(serv = servicelisthead.lh_first; serv && (nrep < 255); serv = serv->entries.le_next) { /* test if we can put more responses in the buffer */ if(strlen(serv->location) + strlen(serv->st) + strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf)) break; if( (type==1 && 0==strncmp(serv->st, (const char *)p, l)) ||(type==2 && 0==strncmp(serv->usn, (const char *)p, l)) ||(type==3) ) { /* response : * 1 - Location * 2 - NT (device/service type) * 3 - usn */ m = strlen(serv->location); CODELENGTH(m, rp); memcpy(rp, serv->location, m); rp += m; m = strlen(serv->st); CODELENGTH(m, rp); memcpy(rp, serv->st, m); rp += m; m = strlen(serv->usn); CODELENGTH(m, rp); memcpy(rp, serv->usn, m); rp += m; nrep++; } } rbuf[0] = nrep; syslog(LOG_DEBUG, "(s=%d) response : %d device%s", req->socket, nrep, (nrep > 1) ? "s" : ""); if(write(req->socket, rbuf, rp - rbuf) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } break; case 4: /* submit service */ newserv = malloc(sizeof(struct service)); if(!newserv) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (st contains forbidden chars)"); goto error; } newserv->st = malloc(l + 1); if(!newserv->st) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->st, p, l); newserv->st[l] = '\0'; p += l; if(p >= buf + n) { syslog(LOG_WARNING, "bad request (missing usn)"); goto error; } DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(p+l > buf+n) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (usn contains forbidden chars)"); goto error; } syslog(LOG_INFO, "usn='%.*s'", l, p); newserv->usn = malloc(l + 1); if(!newserv->usn) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->usn, p, l); newserv->usn[l] = '\0'; p += l; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(p+l > buf+n) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (server contains forbidden chars)"); goto error; } syslog(LOG_INFO, "server='%.*s'", l, p); newserv->server = malloc(l + 1); if(!newserv->server) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->server, p, l); newserv->server[l] = '\0'; p += l; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(p+l > buf+n) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (location contains forbidden chars)"); goto error; } syslog(LOG_INFO, "location='%.*s'", l, p); newserv->location = malloc(l + 1); if(!newserv->location) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->location, p, l); newserv->location[l] = '\0'; /* look in service list for duplicate */ for(serv = servicelisthead.lh_first; serv; serv = serv->entries.le_next) { if(0 == strcmp(newserv->usn, serv->usn) && 0 == strcmp(newserv->st, serv->st)) { syslog(LOG_INFO, "Service allready in the list. Updating..."); free(newserv->st); free(newserv->usn); free(serv->server); serv->server = newserv->server; free(serv->location); serv->location = newserv->location; free(newserv); newserv = NULL; return; } } /* Inserting new service */ LIST_INSERT_HEAD(&servicelisthead, newserv, entries); newserv = NULL; /*rbuf[0] = '\0'; if(write(req->socket, rbuf, 1) < 0) syslog(LOG_ERR, "(s=%d) write: %m", req->socket); */ break; default: syslog(LOG_WARNING, "Unknown request type %d", type); rbuf[0] = '\0'; if(write(req->socket, rbuf, 1) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } } return; error: if(newserv) { free(newserv->st); free(newserv->usn); free(newserv->server); free(newserv->location); free(newserv); newserv = NULL; } close(req->socket); req->socket = -1; return; } Commit Message: minissdpd.c: Initialize pointers to NULL (fix) CWE ID: CWE-388 Target: 1 Example 2: Code: static int tcp_prune_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PRUNECALLED); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) tcp_clamp_window(sk); else if (tcp_under_memory_pressure(sk)) tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss); tcp_collapse_ofo_queue(sk); if (!skb_queue_empty(&sk->sk_receive_queue)) tcp_collapse(sk, &sk->sk_receive_queue, skb_peek(&sk->sk_receive_queue), NULL, tp->copied_seq, tp->rcv_nxt); sk_mem_reclaim(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* Collapsing did not help, destructive actions follow. * This must not ever occur. */ tcp_prune_ofo_queue(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* If we are really being abused, tell the caller to silently * drop receive data on the floor. It will get retransmitted * and hopefully then we'll have sufficient space. */ NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_RCVPRUNED); /* Massive buffer overcommit. */ tp->pred_flags = 0; return -1; } 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: int tls1_setup_key_block(SSL *s) { unsigned char *p; const EVP_CIPHER *c; const EVP_MD *hash; int num; SSL_COMP *comp; int mac_type = NID_undef, mac_secret_size = 0; int ret = 0; if (s->s3->tmp.key_block_length != 0) return (1); if (!ssl_cipher_get_evp (s->session, &c, &hash, &mac_type, &mac_secret_size, &comp, SSL_USE_ETM(s))) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE); return (0); } s->s3->tmp.new_sym_enc = c; s->s3->tmp.new_hash = hash; s->s3->tmp.new_mac_pkey_type = mac_type; s->s3->tmp.new_mac_secret_size = mac_secret_size; num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c); num *= 2; ssl3_cleanup_key_block(s); if ((p = OPENSSL_malloc(num)) == NULL) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE); goto err; } s->s3->tmp.key_block_length = num; s->s3->tmp.key_block = p; #ifdef SSL_DEBUG printf("client random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->client_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("server random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->server_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("master key\n"); { int z; for (z = 0; z < s->session->master_key_length; z++) printf("%02X%c", s->session->master_key[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!tls1_generate_key_block(s, p, num)) goto err; #ifdef SSL_DEBUG printf("\nkey block\n"); { int z; for (z = 0; z < num; z++) printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) && s->method->version <= TLS1_VERSION) { /* * enable vulnerability countermeasure for CBC ciphers with known-IV * problem (http://www.openssl.org/~bodo/tls-cbc.txt) */ s->s3->need_empty_fragments = 1; if (s->session->cipher != NULL) { if (s->session->cipher->algorithm_enc == SSL_eNULL) s->s3->need_empty_fragments = 0; #ifndef OPENSSL_NO_RC4 if (s->session->cipher->algorithm_enc == SSL_RC4) s->s3->need_empty_fragments = 0; #endif } } ret = 1; err: return (ret); } Commit Message: Don't change the state of the ETM flags until CCS processing Changing the ciphersuite during a renegotiation can result in a crash leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS so this is TLS only. The problem is caused by changing the flag indicating whether to use ETM or not immediately on negotiation of ETM, rather than at CCS. Therefore, during a renegotiation, if the ETM state is changing (usually due to a change of ciphersuite), then an error/crash will occur. Due to the fact that there are separate CCS messages for read and write we actually now need two flags to determine whether to use ETM or not. CVE-2017-3733 Reviewed-by: Richard Levitte <[email protected]> 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 inline struct sem_array *sem_obtain_lock(struct ipc_namespace *ns, int id) { struct kern_ipc_perm *ipcp; struct sem_array *sma; rcu_read_lock(); ipcp = ipc_obtain_object(&sem_ids(ns), id); if (IS_ERR(ipcp)) { sma = ERR_CAST(ipcp); goto err; } spin_lock(&ipcp->lock); /* ipc_rmid() may have already freed the ID while sem_lock * was spinning: verify that the structure is still valid */ if (!ipcp->deleted) return container_of(ipcp, struct sem_array, sem_perm); spin_unlock(&ipcp->lock); sma = ERR_PTR(-EINVAL); err: rcu_read_unlock(); return sma; } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: static unsigned long source_load(int cpu, int type) { struct rq *rq = cpu_rq(cpu); unsigned long total = weighted_cpuload(rq); if (type == 0 || !sched_feat(LB_BIAS)) return total; return min(rq->cpu_load[type-1], total); } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <[email protected]> Analyzed-by: Vincent Guittot <[email protected]> Reported-by: Zhipeng Xie <[email protected]> Reported-by: Sargun Dhillon <[email protected]> Reported-by: Xie XiuQi <[email protected]> Tested-by: Zhipeng Xie <[email protected]> Tested-by: Sargun Dhillon <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Acked-by: Vincent Guittot <[email protected]> Cc: <[email protected]> # v4.13+ Cc: Bin Li <[email protected]> Cc: Mike Galbraith <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Tejun Heo <[email protected]> Cc: Thomas Gleixner <[email protected]> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[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: get_html_data (MAPI_Attr *a) { VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1); int j; for (j = 0; j < a->num_values; j++) { body[j] = XMALLOC(VarLenData, 1); body[j]->len = a->values[j].len; body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len); memmove (body[j]->data, a->values[j].data.buf, body[j]->len); } return body; } Commit Message: Check types to avoid invalid reads/writes. 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: long fuse_do_ioctl(struct file *file, unsigned int cmd, unsigned long arg, unsigned int flags) { struct fuse_file *ff = file->private_data; struct fuse_conn *fc = ff->fc; struct fuse_ioctl_in inarg = { .fh = ff->fh, .cmd = cmd, .arg = arg, .flags = flags }; struct fuse_ioctl_out outarg; struct fuse_req *req = NULL; struct page **pages = NULL; struct page *iov_page = NULL; struct iovec *in_iov = NULL, *out_iov = NULL; unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages; size_t in_size, out_size, transferred; int err; /* assume all the iovs returned by client always fits in a page */ BUILD_BUG_ON(sizeof(struct iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE); err = -ENOMEM; pages = kzalloc(sizeof(pages[0]) * FUSE_MAX_PAGES_PER_REQ, GFP_KERNEL); iov_page = alloc_page(GFP_KERNEL); if (!pages || !iov_page) goto out; /* * If restricted, initialize IO parameters as encoded in @cmd. * RETRY from server is not allowed. */ if (!(flags & FUSE_IOCTL_UNRESTRICTED)) { struct iovec *iov = page_address(iov_page); iov->iov_base = (void __user *)arg; iov->iov_len = _IOC_SIZE(cmd); if (_IOC_DIR(cmd) & _IOC_WRITE) { in_iov = iov; in_iovs = 1; } if (_IOC_DIR(cmd) & _IOC_READ) { out_iov = iov; out_iovs = 1; } } retry: inarg.in_size = in_size = iov_length(in_iov, in_iovs); inarg.out_size = out_size = iov_length(out_iov, out_iovs); /* * Out data can be used either for actual out data or iovs, * make sure there always is at least one page. */ out_size = max_t(size_t, out_size, PAGE_SIZE); max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE); /* make sure there are enough buffer pages and init request with them */ err = -ENOMEM; if (max_pages > FUSE_MAX_PAGES_PER_REQ) goto out; while (num_pages < max_pages) { pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM); if (!pages[num_pages]) goto out; num_pages++; } req = fuse_get_req(fc); if (IS_ERR(req)) { err = PTR_ERR(req); req = NULL; goto out; } memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages); req->num_pages = num_pages; /* okay, let's send it to the client */ req->in.h.opcode = FUSE_IOCTL; req->in.h.nodeid = ff->nodeid; req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; if (in_size) { req->in.numargs++; req->in.args[1].size = in_size; req->in.argpages = 1; err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size, false); if (err) goto out; } req->out.numargs = 2; req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; req->out.args[1].size = out_size; req->out.argpages = 1; req->out.argvar = 1; fuse_request_send(fc, req); err = req->out.h.error; transferred = req->out.args[1].size; fuse_put_request(fc, req); req = NULL; if (err) goto out; /* did it ask for retry? */ if (outarg.flags & FUSE_IOCTL_RETRY) { char *vaddr; /* no retry if in restricted mode */ err = -EIO; if (!(flags & FUSE_IOCTL_UNRESTRICTED)) goto out; in_iovs = outarg.in_iovs; out_iovs = outarg.out_iovs; /* * Make sure things are in boundary, separate checks * are to protect against overflow. */ err = -ENOMEM; if (in_iovs > FUSE_IOCTL_MAX_IOV || out_iovs > FUSE_IOCTL_MAX_IOV || in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV) goto out; vaddr = kmap_atomic(pages[0], KM_USER0); err = fuse_copy_ioctl_iovec(page_address(iov_page), vaddr, transferred, in_iovs + out_iovs, (flags & FUSE_IOCTL_COMPAT) != 0); kunmap_atomic(vaddr, KM_USER0); if (err) goto out; in_iov = page_address(iov_page); out_iov = in_iov + in_iovs; goto retry; } err = -EIO; if (transferred > inarg.out_size) goto out; err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true); out: if (req) fuse_put_request(fc, req); if (iov_page) __free_page(iov_page); while (num_pages) __free_page(pages[--num_pages]); kfree(pages); return err ? err : outarg.result; } Commit Message: fuse: verify ioctl retries Verify that the total length of the iovec returned in FUSE_IOCTL_RETRY doesn't overflow iov_length(). Signed-off-by: Miklos Szeredi <[email protected]> CC: Tejun Heo <[email protected]> CC: <[email protected]> [2.6.31+] CWE ID: CWE-119 Target: 1 Example 2: Code: void PlatformSensorProviderWin::SetSensorManagerForTesting( Microsoft::WRL::ComPtr<ISensorManager> sensor_manager) { CreateSensorThread(); sensor_thread_->SetSensorManagerForTesting(sensor_manager); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} 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: void WebGLRenderingContextBase::texImage2D(GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, ImageData* pixels) { TexImageHelperImageData(kTexImage2D, target, level, internalformat, 0, format, type, 1, 0, 0, 0, pixels, GetImageDataSize(pixels), 0); } 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:
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 process_tree(struct rev_info *revs, struct tree *tree, show_object_fn show, struct strbuf *base, const char *name, void *cb_data) { struct object *obj = &tree->object; struct tree_desc desc; struct name_entry entry; enum interesting match = revs->diffopt.pathspec.nr == 0 ? all_entries_interesting: entry_not_interesting; int baselen = base->len; if (!revs->tree_objects) return; if (!obj) die("bad tree object"); if (obj->flags & (UNINTERESTING | SEEN)) return; if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) { if (revs->ignore_missing_links) return; die("bad tree object %s", oid_to_hex(&obj->oid)); } obj->flags |= SEEN; show(obj, base, name, cb_data); strbuf_addstr(base, name); if (base->len) strbuf_addch(base, '/'); init_tree_desc(&desc, tree->buffer, tree->size); while (tree_entry(&desc, &entry)) { if (match != all_entries_interesting) { match = tree_entry_interesting(&entry, base, 0, &revs->diffopt.pathspec); if (match == all_entries_not_interesting) break; if (match == entry_not_interesting) continue; } if (S_ISDIR(entry.mode)) process_tree(revs, lookup_tree(entry.sha1), show, base, entry.path, cb_data); else if (S_ISGITLINK(entry.mode)) process_gitlink(revs, entry.sha1, show, base, entry.path, cb_data); else process_blob(revs, lookup_blob(entry.sha1), show, base, entry.path, cb_data); } strbuf_setlen(base, baselen); free_tree_buffer(tree); } 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: 1 Example 2: Code: void InspectorAccessibilityAgent::populateRelatives( AXObject& axObject, AXObject* inspectedAXObject, AXNode& nodeObject, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { AXObject* parentObject = axObject.parentObject(); if (parentObject && parentObject != inspectedAXObject) { parentObject = axObject.parentObjectUnignored(); } std::unique_ptr<protocol::Array<AXNodeId>> childIds = protocol::Array<AXNodeId>::create(); if (&axObject != inspectedAXObject || (inspectedAXObject && !inspectedAXObject->accessibilityIsIgnored())) { addChildren(axObject, inspectedAXObject, childIds, nodes, cache); } nodeObject.setChildIds(std::move(childIds)); } 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: void V8TestObject::ImplementedAsVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_implementedAsVoidMethod"); test_object_v8_internal::ImplementedAsVoidMethodMethod(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: 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: const char* Chapters::Display::GetString() const { return m_string; } 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 Target: 1 Example 2: Code: void LayerTreeHost::SetBrowserControlsHeight(float height, bool shrink) { if (top_controls_height_ == height && browser_controls_shrink_blink_size_ == shrink) return; top_controls_height_ = height; browser_controls_shrink_blink_size_ = shrink; SetNeedsCommit(); } 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: TabContentsWrapper* DefaultTabHandler::CreateTabContentsForURL( const GURL& url, const GURL& referrer, Profile* profile, PageTransition::Type transition, bool defer_load, SiteInstance* instance) const { return delegate_->AsBrowser()->CreateTabContentsForURL(url, referrer, profile, transition, defer_load, instance); } Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab. BUG=chromium-os:12088 TEST=verify bug per bug report. Review URL: http://codereview.chromium.org/6882058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 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: choose_volume(struct archive_read *a, struct iso9660 *iso9660) { struct file_info *file; int64_t skipsize; struct vd *vd; const void *block; char seenJoliet; vd = &(iso9660->primary); if (!iso9660->opt_support_joliet) iso9660->seenJoliet = 0; if (iso9660->seenJoliet && vd->location > iso9660->joliet.location) /* This condition is unlikely; by way of caution. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * vd->location; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position = skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } /* * While reading Root Directory, flag seenJoliet must be zero to * avoid converting special name 0x00(Current Directory) and * next byte to UCS2. */ seenJoliet = iso9660->seenJoliet;/* Save flag. */ iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; /* * If the iso image has both RockRidge and Joliet, we preferentially * use RockRidge Extensions rather than Joliet ones. */ if (vd == &(iso9660->primary) && iso9660->seenRockridge && iso9660->seenJoliet) iso9660->seenJoliet = 0; if (vd == &(iso9660->primary) && !iso9660->seenRockridge && iso9660->seenJoliet) { /* Switch reading data from primary to joliet. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * vd->location; skipsize -= iso9660->current_position; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position += skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; } /* Store the root directory in the pending list. */ if (add_entry(a, iso9660, file) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->seenRockridge) { a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE; a->archive.archive_format_name = "ISO9660 with Rockridge extensions"; } return (ARCHIVE_OK); } Commit Message: Issue 717: Fix integer overflow when computing location of volume descriptor The multiplication here defaulted to 'int' but calculations of file positions should always use int64_t. A simple cast suffices to fix this since the base location is always 32 bits for ISO, so multiplying by the sector size will never overflow a 64-bit integer. CWE ID: CWE-190 Target: 1 Example 2: Code: static inline int dentry_cmp(const struct dentry *dentry, const unsigned char *ct, unsigned tcount) { /* * Be careful about RCU walk racing with rename: * use 'lockless_dereference' to fetch the name pointer. * * NOTE! Even if a rename will mean that the length * was not loaded atomically, we don't care. The * RCU walk will check the sequence count eventually, * and catch it. And we won't overrun the buffer, * because we're reading the name pointer atomically, * and a dentry name is guaranteed to be properly * terminated with a NUL byte. * * End result: even if 'len' is wrong, we'll exit * early because the data cannot match (there can * be no NUL in the ct/tcount data) */ const unsigned char *cs = lockless_dereference(dentry->d_name.name); return dentry_string_cmp(cs, ct, tcount); } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <[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: sec_parse_crypt_info(STREAM s, uint32 * rc4_key_size, uint8 ** server_random, uint8 * modulus, uint8 * exponent) { uint32 crypt_level, random_len, rsa_info_len; uint32 cacert_len, cert_len, flags; RDSSL_CERT *cacert, *server_cert; RDSSL_RKEY *server_public_key; uint16 tag, length; uint8 *next_tag, *end; logger(Protocol, Debug, "%s()", __func__); in_uint32_le(s, *rc4_key_size); /* 1 = 40-bit, 2 = 128-bit */ in_uint32_le(s, crypt_level); /* 1 = low, 2 = medium, 3 = high */ if (crypt_level == 0) { /* no encryption */ logger(Protocol, Debug, "sec_parse_crypt_info(), got ENCRYPTION_LEVEL_NONE"); return False; } in_uint32_le(s, random_len); in_uint32_le(s, rsa_info_len); if (random_len != SEC_RANDOM_SIZE) { logger(Protocol, Error, "sec_parse_crypt_info(), got random len %d, expected %d", random_len, SEC_RANDOM_SIZE); return False; } in_uint8p(s, *server_random, random_len); /* RSA info */ end = s->p + rsa_info_len; if (end > s->end) { logger(Protocol, Error, "sec_parse_crypt_info(), end > s->end"); return False; } in_uint32_le(s, flags); /* 1 = RDP4-style, 0x80000002 = X.509 */ if (flags & 1) { logger(Protocol, Debug, "sec_parse_crypt_info(), We're going for the RDP4-style encryption"); in_uint8s(s, 8); /* unknown */ while (s->p < end) { in_uint16_le(s, tag); in_uint16_le(s, length); next_tag = s->p + length; switch (tag) { case SEC_TAG_PUBKEY: if (!sec_parse_public_key(s, modulus, exponent)) { logger(Protocol, Error, "sec_parse_crypt_info(), invalid public key"); return False; } logger(Protocol, Debug, "sec_parse_crypt_info(), got public key"); break; case SEC_TAG_KEYSIG: if (!sec_parse_public_sig(s, length, modulus, exponent)) { logger(Protocol, Error, "sec_parse_crypt_info(), invalid public sig"); return False; } break; default: logger(Protocol, Warning, "sec_parse_crypt_info(), unhandled crypt tag 0x%x", tag); } s->p = next_tag; } } else { uint32 certcount; logger(Protocol, Debug, "sec_parse_crypt_info(), We're going for the RDP5-style encryption"); in_uint32_le(s, certcount); /* Number of certificates */ if (certcount < 2) { logger(Protocol, Error, "sec_parse_crypt_info(), server didn't send enough x509 certificates"); return False; } for (; certcount > 2; certcount--) { /* ignore all the certificates between the root and the signing CA */ uint32 ignorelen; RDSSL_CERT *ignorecert; in_uint32_le(s, ignorelen); ignorecert = rdssl_cert_read(s->p, ignorelen); in_uint8s(s, ignorelen); if (ignorecert == NULL) { /* XXX: error out? */ logger(Protocol, Error, "sec_parse_crypt_info(), got a bad cert: this will probably screw up the rest of the communication"); } } /* Do da funky X.509 stuffy "How did I find out about this? I looked up and saw a bright light and when I came to I had a scar on my forehead and knew about X.500" - Peter Gutman in a early version of http://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt */ in_uint32_le(s, cacert_len); logger(Protocol, Debug, "sec_parse_crypt_info(), server CA Certificate length is %d", cacert_len); cacert = rdssl_cert_read(s->p, cacert_len); in_uint8s(s, cacert_len); if (NULL == cacert) { logger(Protocol, Error, "sec_parse_crypt_info(), couldn't load CA Certificate from server"); return False; } in_uint32_le(s, cert_len); logger(Protocol, Debug, "sec_parse_crypt_info(), certificate length is %d", cert_len); server_cert = rdssl_cert_read(s->p, cert_len); in_uint8s(s, cert_len); if (NULL == server_cert) { rdssl_cert_free(cacert); logger(Protocol, Error, "sec_parse_crypt_info(), couldn't load Certificate from server"); return False; } if (!rdssl_certs_ok(server_cert, cacert)) { rdssl_cert_free(server_cert); rdssl_cert_free(cacert); logger(Protocol, Error, "sec_parse_crypt_info(), security error, CA Certificate invalid"); return False; } rdssl_cert_free(cacert); in_uint8s(s, 16); /* Padding */ server_public_key = rdssl_cert_to_rkey(server_cert, &g_server_public_key_len); if (NULL == server_public_key) { logger(Protocol, Debug, "sec_parse_crypt_info(). failed to parse X509 correctly"); rdssl_cert_free(server_cert); return False; } rdssl_cert_free(server_cert); if ((g_server_public_key_len < SEC_MODULUS_SIZE) || (g_server_public_key_len > SEC_MAX_MODULUS_SIZE)) { logger(Protocol, Error, "sec_parse_crypt_info(), bad server public key size (%u bits)", g_server_public_key_len * 8); rdssl_rkey_free(server_public_key); return False; } if (rdssl_rkey_get_exp_mod(server_public_key, exponent, SEC_EXPONENT_SIZE, modulus, SEC_MAX_MODULUS_SIZE) != 0) { logger(Protocol, Error, "sec_parse_crypt_info(), problem extracting RSA exponent, modulus"); rdssl_rkey_free(server_public_key); return False; } rdssl_rkey_free(server_public_key); return True; /* There's some garbage here we don't care about */ } return s_check_end(s); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 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 int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint32 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ Commit Message: * tools/tiffcrop.c: fix readContigStripsIntoBuffer() in -i (ignore) mode so that the output buffer is correctly incremented to avoid write outside bounds. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2620 CWE ID: CWE-119 Target: 1 Example 2: Code: static void check_and_drop(void *_data) { struct detach_data *data = _data; if (!data->mountpoint && list_empty(&data->select.dispose)) __d_drop(data->select.start); } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <[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 inline void inc(be128 *iv) { be64_add_cpu(&iv->b, 1); if (!iv->b) be64_add_cpu(&iv->a, 1); } Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[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: ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode) { EVP_CIPHER_CTX *ctx; unsigned char key[EVP_MAX_KEY_LENGTH], *p_key = NULL; unsigned char iv[EVP_MAX_IV_LENGTH], *p_iv = NULL; VALUE pass, init_v; if(rb_scan_args(argc, argv, "02", &pass, &init_v) > 0){ /* * oops. this code mistakes salt for IV. * We deprecated the arguments for this method, but we decided * keeping this behaviour for backward compatibility. */ VALUE cname = rb_class_path(rb_obj_class(self)); rb_warn("arguments for %"PRIsVALUE"#encrypt and %"PRIsVALUE"#decrypt were deprecated; " "use %"PRIsVALUE"#pkcs5_keyivgen to derive key and IV", cname, cname, cname); StringValue(pass); GetCipher(self, ctx); if (NIL_P(init_v)) memcpy(iv, "OpenSSL for Ruby rulez!", sizeof(iv)); else{ StringValue(init_v); if (EVP_MAX_IV_LENGTH > RSTRING_LEN(init_v)) { memset(iv, 0, EVP_MAX_IV_LENGTH); memcpy(iv, RSTRING_PTR(init_v), RSTRING_LEN(init_v)); } else memcpy(iv, RSTRING_PTR(init_v), sizeof(iv)); } EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), EVP_md5(), iv, (unsigned char *)RSTRING_PTR(pass), RSTRING_LENINT(pass), 1, key, NULL); p_key = key; p_iv = iv; } else { GetCipher(self, ctx); } if (EVP_CipherInit_ex(ctx, NULL, NULL, p_key, p_iv, mode) != 1) { ossl_raise(eCipherError, NULL); } return self; } Commit Message: cipher: don't set dummy encryption key in Cipher#initialize Remove the encryption key initialization from Cipher#initialize. This is effectively a revert of r32723 ("Avoid possible SEGV from AES encryption/decryption", 2011-07-28). r32723, which added the key initialization, was a workaround for Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate() before setting an encryption key caused segfault. It was not a problem until OpenSSL implemented GCM mode - the encryption key could be overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the case for AES-GCM ciphers. Setting a key, an IV, a key, in this order causes the IV to be reset to an all-zero IV. The problem of Bug #2768 persists on the current versions of OpenSSL. So, make Cipher#update raise an exception if a key is not yet set by the user. Since encrypting or decrypting without key does not make any sense, this should not break existing applications. Users can still call Cipher#key= and Cipher#iv= multiple times with their own responsibility. Reference: https://bugs.ruby-lang.org/issues/2768 Reference: https://bugs.ruby-lang.org/issues/8221 Reference: https://github.com/ruby/openssl/issues/49 CWE ID: CWE-310 Target: 1 Example 2: Code: void Browser::BookmarkCurrentPage() { UserMetrics::RecordAction(UserMetricsAction("Star")); BookmarkModel* model = profile()->GetBookmarkModel(); if (!model || !model->IsLoaded()) return; // Ignore requests until bookmarks are loaded. GURL url; string16 title; TabContentsWrapper* tab = GetSelectedTabContentsWrapper(); bookmark_utils::GetURLAndTitleToBookmark(tab->tab_contents(), &url, &title); bool was_bookmarked = model->IsBookmarked(url); if (!was_bookmarked && profile_->IsOffTheRecord()) { tab->favicon_tab_helper()->SaveFavicon(); } bookmark_utils::AddIfNotBookmarked(model, url, title); if (window_->IsActive() && model->IsBookmarked(url)) { window_->ShowBookmarkBubble(url, was_bookmarked); } } 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 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 put_compat_itimerval(struct compat_itimerval __user *o, const struct itimerval *i) { struct compat_itimerval v32; v32.it_interval.tv_sec = i->it_interval.tv_sec; v32.it_interval.tv_usec = i->it_interval.tv_usec; v32.it_value.tv_sec = i->it_value.tv_sec; v32.it_value.tv_usec = i->it_value.tv_usec; return copy_to_user(o, &v32, sizeof(struct compat_itimerval)) ? -EFAULT : 0; } Commit Message: compat: fix 4-byte infoleak via uninitialized struct field Commit 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts") removed the memset() in compat_get_timex(). Since then, the compat adjtimex syscall can invoke do_adjtimex() with an uninitialized ->tai. If do_adjtimex() doesn't write to ->tai (e.g. because the arguments are invalid), compat_put_timex() then copies the uninitialized ->tai field to userspace. Fix it by adding the memset() back. Fixes: 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts") Signed-off-by: Jann Horn <[email protected]> Acked-by: Kees Cook <[email protected]> Acked-by: Al Viro <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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 JSValueRef releaseTouchPointCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { if (argumentCount < 1) return JSValueMakeUndefined(context); int index = static_cast<int>(JSValueToNumber(context, arguments[0], exception)); ASSERT(!exception || !*exception); if (index < 0 || index >= (int)touches.size()) return JSValueMakeUndefined(context); touches[index].m_state = BlackBerry::Platform::TouchPoint::TouchReleased; return JSValueMakeUndefined(context); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: unsigned char *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len) { if (tail != skb) { skb->data_len += len; skb->len += len; } return skb_put(tail, len); } Commit Message: skbuff: skb_segment: orphan frags before copying skb_segment copies frags around, so we need to copy them carefully to avoid accessing user memory after reporting completion to userspace through a callback. skb_segment doesn't normally happen on datapath: TSO needs to be disabled - so disabling zero copy in this case does not look like a big deal. Signed-off-by: Michael S. Tsirkin <[email protected]> Acked-by: Herbert Xu <[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 DeviceTokenFetcher::SetState(FetcherState state) { state_ = state; if (state_ != STATE_TEMPORARY_ERROR) effective_token_fetch_error_delay_ms_ = kTokenFetchErrorDelayMilliseconds; base::Time delayed_work_at; switch (state_) { case STATE_INACTIVE: notifier_->Inform(CloudPolicySubsystem::UNENROLLED, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::TOKEN_FETCHER); break; case STATE_TOKEN_AVAILABLE: notifier_->Inform(CloudPolicySubsystem::SUCCESS, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::TOKEN_FETCHER); break; case STATE_UNMANAGED: delayed_work_at = cache_->last_policy_refresh_time() + base::TimeDelta::FromMilliseconds( kUnmanagedDeviceRefreshRateMilliseconds); notifier_->Inform(CloudPolicySubsystem::UNMANAGED, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::TOKEN_FETCHER); break; case STATE_TEMPORARY_ERROR: delayed_work_at = base::Time::Now() + base::TimeDelta::FromMilliseconds( effective_token_fetch_error_delay_ms_); effective_token_fetch_error_delay_ms_ = std::min(effective_token_fetch_error_delay_ms_ * 2, kTokenFetchErrorMaxDelayMilliseconds); notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::DMTOKEN_NETWORK_ERROR, PolicyNotifier::TOKEN_FETCHER); break; case STATE_ERROR: effective_token_fetch_error_delay_ms_ = kTokenFetchErrorMaxDelayMilliseconds; delayed_work_at = base::Time::Now() + base::TimeDelta::FromMilliseconds( effective_token_fetch_error_delay_ms_); notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::DMTOKEN_NETWORK_ERROR, PolicyNotifier::TOKEN_FETCHER); break; case STATE_BAD_AUTH: notifier_->Inform(CloudPolicySubsystem::BAD_GAIA_TOKEN, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::TOKEN_FETCHER); break; } scheduler_->CancelDelayedWork(); if (!delayed_work_at.is_null()) { base::Time now(base::Time::Now()); int64 delay = std::max<int64>((delayed_work_at - now).InMilliseconds(), 0); scheduler_->PostDelayedWork( base::Bind(&DeviceTokenFetcher::DoWork, base::Unretained(this)), delay); } } 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: std::string SanitizeFrontendQueryParam( const std::string& key, const std::string& value) { if (key == "can_dock" || key == "debugFrontend" || key == "experiments" || key == "isSharedWorker" || key == "v8only" || key == "remoteFrontend") return "true"; if (key == "ws" || key == "service-backend") return SanitizeEndpoint(value); if (key == "dockSide" && value == "undocked") return value; if (key == "panel" && (value == "elements" || value == "console")) return value; if (key == "remoteBase") return SanitizeRemoteBase(value); if (key == "remoteFrontendUrl") return SanitizeRemoteFrontendURL(value); return std::string(); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200 Target: 1 Example 2: Code: void WebContentsImpl::Paste() { RenderFrameHost* focused_frame = GetFocusedFrame(); if (!focused_frame) return; focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID())); RecordAction(base::UserMetricsAction("Paste")); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} 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: Init_ossl_cipher(void) { #if 0 mOSSL = rb_define_module("OpenSSL"); eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError); #endif /* Document-class: OpenSSL::Cipher * * Provides symmetric algorithms for encryption and decryption. The * algorithms that are available depend on the particular version * of OpenSSL that is installed. * * === Listing all supported algorithms * * A list of supported algorithms can be obtained by * * puts OpenSSL::Cipher.ciphers * * === Instantiating a Cipher * * There are several ways to create a Cipher instance. Generally, a * Cipher algorithm is categorized by its name, the key length in bits * and the cipher mode to be used. The most generic way to create a * Cipher is the following * * cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>') * * That is, a string consisting of the hyphenated concatenation of the * individual components name, key length and mode. Either all uppercase * or all lowercase strings may be used, for example: * * cipher = OpenSSL::Cipher.new('AES-128-CBC') * * For each algorithm supported, there is a class defined under the * Cipher class that goes by the name of the cipher, e.g. to obtain an * instance of AES, you could also use * * # these are equivalent * cipher = OpenSSL::Cipher::AES.new(128, :CBC) * cipher = OpenSSL::Cipher::AES.new(128, 'CBC') * cipher = OpenSSL::Cipher::AES.new('128-CBC') * * Finally, due to its wide-spread use, there are also extra classes * defined for the different key sizes of AES * * cipher = OpenSSL::Cipher::AES128.new(:CBC) * cipher = OpenSSL::Cipher::AES192.new(:CBC) * cipher = OpenSSL::Cipher::AES256.new(:CBC) * * === Choosing either encryption or decryption mode * * Encryption and decryption are often very similar operations for * symmetric algorithms, this is reflected by not having to choose * different classes for either operation, both can be done using the * same class. Still, after obtaining a Cipher instance, we need to * tell the instance what it is that we intend to do with it, so we * need to call either * * cipher.encrypt * * or * * cipher.decrypt * * on the Cipher instance. This should be the first call after creating * the instance, otherwise configuration that has already been set could * get lost in the process. * * === Choosing a key * * Symmetric encryption requires a key that is the same for the encrypting * and for the decrypting party and after initial key establishment should * be kept as private information. There are a lot of ways to create * insecure keys, the most notable is to simply take a password as the key * without processing the password further. A simple and secure way to * create a key for a particular Cipher is * * cipher = OpenSSL::AES256.new(:CFB) * cipher.encrypt * key = cipher.random_key # also sets the generated key on the Cipher * * If you absolutely need to use passwords as encryption keys, you * should use Password-Based Key Derivation Function 2 (PBKDF2) by * generating the key with the help of the functionality provided by * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac. * * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and * it should only be used in legacy applications because it does not use * the newer PKCS#5 v2 algorithms. * * === Choosing an IV * * The cipher modes CBC, CFB, OFB and CTR all need an "initialization * vector", or short, IV. ECB mode is the only mode that does not require * an IV, but there is almost no legitimate use case for this mode * because of the fact that it does not sufficiently hide plaintext * patterns. Therefore * * <b>You should never use ECB mode unless you are absolutely sure that * you absolutely need it</b> * * Because of this, you will end up with a mode that explicitly requires * an IV in any case. Note that for backwards compatibility reasons, * setting an IV is not explicitly mandated by the Cipher API. If not * set, OpenSSL itself defaults to an all-zeroes IV ("\\0", not the * character). Although the IV can be seen as public information, i.e. * it may be transmitted in public once generated, it should still stay * unpredictable to prevent certain kinds of attacks. Therefore, ideally * * <b>Always create a secure random IV for every encryption of your * Cipher</b> * * A new, random IV should be created for every encryption of data. Think * of the IV as a nonce (number used once) - it's public but random and * unpredictable. A secure random IV can be created as follows * * cipher = ... * cipher.encrypt * key = cipher.random_key * iv = cipher.random_iv # also sets the generated IV on the Cipher * * Although the key is generally a random value, too, it is a bad choice * as an IV. There are elaborate ways how an attacker can take advantage * of such an IV. As a general rule of thumb, exposing the key directly * or indirectly should be avoided at all cost and exceptions only be * made with good reason. * * === Calling Cipher#final * * ECB (which should not be used) and CBC are both block-based modes. * This means that unlike for the other streaming-based modes, they * operate on fixed-size blocks of data, and therefore they require a * "finalization" step to produce or correctly decrypt the last block of * data by appropriately handling some form of padding. Therefore it is * essential to add the output of OpenSSL::Cipher#final to your * encryption/decryption buffer or you will end up with decryption errors * or truncated data. * * Although this is not really necessary for streaming-mode ciphers, it is * still recommended to apply the same pattern of adding the output of * Cipher#final there as well - it also enables you to switch between * modes more easily in the future. * * === Encrypting and decrypting some data * * data = "Very, very confidential data" * * cipher = OpenSSL::Cipher::AES.new(128, :CBC) * cipher.encrypt * key = cipher.random_key * iv = cipher.random_iv * * encrypted = cipher.update(data) + cipher.final * ... * decipher = OpenSSL::Cipher::AES.new(128, :CBC) * decipher.decrypt * decipher.key = key * decipher.iv = iv * * plain = decipher.update(encrypted) + decipher.final * * puts data == plain #=> true * * === Authenticated Encryption and Associated Data (AEAD) * * If the OpenSSL version used supports it, an Authenticated Encryption * mode (such as GCM or CCM) should always be preferred over any * unauthenticated mode. Currently, OpenSSL supports AE only in combination * with Associated Data (AEAD) where additional associated data is included * in the encryption process to compute a tag at the end of the encryption. * This tag will also be used in the decryption process and by verifying * its validity, the authenticity of a given ciphertext is established. * * This is superior to unauthenticated modes in that it allows to detect * if somebody effectively changed the ciphertext after it had been * encrypted. This prevents malicious modifications of the ciphertext that * could otherwise be exploited to modify ciphertexts in ways beneficial to * potential attackers. * * An associated data is used where there is additional information, such as * headers or some metadata, that must be also authenticated but not * necessarily need to be encrypted. If no associated data is needed for * encryption and later decryption, the OpenSSL library still requires a * value to be set - "" may be used in case none is available. * * An example using the GCM (Galois/Counter Mode). You have 16 bytes +key+, * 12 bytes (96 bits) +nonce+ and the associated data +auth_data+. Be sure * not to reuse the +key+ and +nonce+ pair. Reusing an nonce ruins the * security gurantees of GCM mode. * * cipher = OpenSSL::Cipher::AES.new(128, :GCM).encrypt * cipher.key = key * cipher.iv = nonce * cipher.auth_data = auth_data * * encrypted = cipher.update(data) + cipher.final * tag = cipher.auth_tag # produces 16 bytes tag by default * * Now you are the receiver. You know the +key+ and have received +nonce+, * +auth_data+, +encrypted+ and +tag+ through an untrusted network. Note * that GCM accepts an arbitrary length tag between 1 and 16 bytes. You may * additionally need to check that the received tag has the correct length, * or you allow attackers to forge a valid single byte tag for the tampered * ciphertext with a probability of 1/256. * * raise "tag is truncated!" unless tag.bytesize == 16 * decipher = OpenSSL::Cipher::AES.new(128, :GCM).decrypt * decipher.key = key * decipher.iv = nonce * decipher.auth_tag = tag * decipher.auth_data = auth_data * * decrypted = decipher.update(encrypted) + decipher.final * * puts data == decrypted #=> true */ cCipher = rb_define_class_under(mOSSL, "Cipher", rb_cObject); eCipherError = rb_define_class_under(cCipher, "CipherError", eOSSLError); rb_define_alloc_func(cCipher, ossl_cipher_alloc); rb_define_copy_func(cCipher, ossl_cipher_copy); rb_define_module_function(cCipher, "ciphers", ossl_s_ciphers, 0); rb_define_method(cCipher, "initialize", ossl_cipher_initialize, 1); rb_define_method(cCipher, "reset", ossl_cipher_reset, 0); rb_define_method(cCipher, "encrypt", ossl_cipher_encrypt, -1); rb_define_method(cCipher, "decrypt", ossl_cipher_decrypt, -1); rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1); rb_define_method(cCipher, "update", ossl_cipher_update, -1); rb_define_method(cCipher, "final", ossl_cipher_final, 0); rb_define_method(cCipher, "name", ossl_cipher_name, 0); rb_define_method(cCipher, "key=", ossl_cipher_set_key, 1); rb_define_method(cCipher, "auth_data=", ossl_cipher_set_auth_data, 1); rb_define_method(cCipher, "auth_tag=", ossl_cipher_set_auth_tag, 1); rb_define_method(cCipher, "auth_tag", ossl_cipher_get_auth_tag, -1); rb_define_method(cCipher, "auth_tag_len=", ossl_cipher_set_auth_tag_len, 1); rb_define_method(cCipher, "authenticated?", ossl_cipher_is_authenticated, 0); rb_define_method(cCipher, "key_len=", ossl_cipher_set_key_length, 1); rb_define_method(cCipher, "key_len", ossl_cipher_key_length, 0); rb_define_method(cCipher, "iv=", ossl_cipher_set_iv, 1); rb_define_method(cCipher, "iv_len=", ossl_cipher_set_iv_length, 1); rb_define_method(cCipher, "iv_len", ossl_cipher_iv_length, 0); rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0); rb_define_method(cCipher, "padding=", ossl_cipher_set_padding, 1); id_auth_tag_len = rb_intern_const("auth_tag_len"); } Commit Message: cipher: don't set dummy encryption key in Cipher#initialize Remove the encryption key initialization from Cipher#initialize. This is effectively a revert of r32723 ("Avoid possible SEGV from AES encryption/decryption", 2011-07-28). r32723, which added the key initialization, was a workaround for Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate() before setting an encryption key caused segfault. It was not a problem until OpenSSL implemented GCM mode - the encryption key could be overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the case for AES-GCM ciphers. Setting a key, an IV, a key, in this order causes the IV to be reset to an all-zero IV. The problem of Bug #2768 persists on the current versions of OpenSSL. So, make Cipher#update raise an exception if a key is not yet set by the user. Since encrypting or decrypting without key does not make any sense, this should not break existing applications. Users can still call Cipher#key= and Cipher#iv= multiple times with their own responsibility. Reference: https://bugs.ruby-lang.org/issues/2768 Reference: https://bugs.ruby-lang.org/issues/8221 Reference: https://github.com/ruby/openssl/issues/49 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: static pfunc check_literal(struct jv_parser* p) { if (p->tokenpos == 0) return 0; const char* pattern = 0; int plen; jv v; switch (p->tokenbuf[0]) { case 't': pattern = "true"; plen = 4; v = jv_true(); break; case 'f': pattern = "false"; plen = 5; v = jv_false(); break; case 'n': pattern = "null"; plen = 4; v = jv_null(); break; } if (pattern) { if (p->tokenpos != plen) return "Invalid literal"; for (int i=0; i<plen; i++) if (p->tokenbuf[i] != pattern[i]) return "Invalid literal"; TRY(value(p, v)); } else { p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid char* end = 0; double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end); if (end == 0 || *end != 0) return "Invalid numeric literal"; TRY(value(p, jv_number(d))); } p->tokenpos = 0; return 0; } Commit Message: Heap buffer overflow in tokenadd() (fix #105) This was an off-by one: the NUL terminator byte was not allocated on resize. This was triggered by JSON-encoded numbers longer than 256 bytes. CWE ID: CWE-119 Target: 1 Example 2: Code: void OnSetIsInertOnUI(bool is_inert) { is_inert_ = is_inert; if (!msg_received_) { msg_received_ = true; message_loop_runner_->Quit(); } } Commit Message: Avoid sharing process for blob URLs with null origin. Previously, when a frame with a unique origin, such as from a data URL, created a blob URL, the blob URL looked like blob:null/guid and resulted in a site URL of "blob:" when navigated to. This incorrectly allowed all such blob URLs to share a process, even if they were created by different sites. This CL changes the site URL assigned in such cases to be the full blob URL, which includes the GUID. This avoids process sharing for all blob URLs with unique origins. This fix is conservative in the sense that it would also isolate different blob URLs created by the same unique origin from each other. This case isn't expected to be common, so it's unlikely to affect process count. There's ongoing work to maintain a GUID for unique origins, so longer-term, we could try using that to track down the creator and potentially use that GUID in the site URL instead of the blob URL's GUID, to avoid unnecessary process isolation in scenarios like this. Note that as part of this, we discovered a bug where data URLs aren't able to script blob URLs that they create: https://crbug.com/865254. This scripting bug should be fixed independently of this CL, and as far as we can tell, this CL doesn't regress scripting cases like this further. Bug: 863623 Change-Id: Ib50407adbba3d5ee0cf6d72d3df7f8d8f24684ee Reviewed-on: https://chromium-review.googlesource.com/1142389 Commit-Queue: Alex Moshchuk <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#576318} 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: void esp_request_cancelled(SCSIRequest *req) { ESPState *s = req->hba_private; if (req == s->current_req) { scsi_req_unref(s->current_req); s->current_req = NULL; s->current_dev = NULL; } } Commit Message: 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: void ping_unhash(struct sock *sk) { struct inet_sock *isk = inet_sk(sk); pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num); if (sk_hashed(sk)) { write_lock_bh(&ping_table.lock); hlist_nulls_del(&sk->sk_nulls_node); sock_put(sk); isk->inet_num = 0; isk->inet_sport = 0; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); write_unlock_bh(&ping_table.lock); } } Commit Message: ipv4: Missing sk_nulls_node_init() in ping_unhash(). If we don't do that, then the poison value is left in the ->pprev backlink. This can cause crashes if we do a disconnect, followed by a connect(). Tested-by: Linus Torvalds <[email protected]> Reported-by: Wen Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 1 Example 2: Code: bool WebGraphicsContext3DCommandBufferImpl::ShouldUseSwapClient() { GpuChannelHostFactory* factory = GpuChannelHostFactory::instance(); return factory && factory->IsMainThread() && swap_client_.get(); } Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip. BUG=116637 TEST=manual test from bug report with ASAN Review URL: https://chromiumcodereview.appspot.com/9617038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 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: InProcessBrowserTest::~InProcessBrowserTest() { } Commit Message: chromeos: Move audio, power, and UI files into subdirs. This moves more files from chrome/browser/chromeos/ into subdirectories. BUG=chromium-os:22896 TEST=did chrome os builds both with and without aura TBR=sky Review URL: http://codereview.chromium.org/9125006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116746 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: parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr, const wbxml_decoding *map) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; guint8 attr_save_known = 0; /* Will contain peek & 0x3F (attr identity) */ const char *attr_save_literal = NULL; /* Will contain the LITERAL attr identity */ DebugLog(("parse_wbxml_attr_defined (level = %u, offset = %u)\n", level, offset)); /* Parse attributes */ while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("ATTR: (top of while) level = %3u, peek = 0x%02X, " "off = %u, tvb_len = %u\n", level, peek, off, tvb_len)); if ((peek & 0x3F) < 5) switch (peek) { /* Global tokens in state = ATTR */ case 0x00: /* SWITCH_PAGE */ *codepage_attr = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Attr | A -->%3d " "| SWITCH_PAGE (Attr code page) |", *codepage_attr); off += 2; break; case 0x01: /* END */ /* BEWARE * The Attribute END token means either ">" or "/>" * and as a consequence both must be treated separately. * This is done in the TAG state parser. */ off++; DebugLog(("ATTR: level = %u, Return: len = %u\n", level, off - offset)); return (off - offset); case 0x02: /* ENTITY */ ent = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| ENTITY " "| %s'&#%u;'", level, *codepage_attr, Indent (level), ent); off += 1+len; break; case 0x03: /* STR_I */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| STR_I (Inline string) " "| %s\'%s\'", level, *codepage_attr, Indent (level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x04: /* LITERAL */ /* ALWAYS means the start of a new attribute, * and may only contain the NAME of the attribute. */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); attr_save_known = 0; attr_save_literal = tvb_format_text (tvb, str_tbl+idx, str_len-1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| LITERAL (Literal Attribute) " "| %s<%s />", level, *codepage_attr, Indent (level), attr_save_literal); off += 1+len; break; case 0x40: /* EXT_I_0 */ case 0x41: /* EXT_I_1 */ case 0x42: /* EXT_I_2 */ /* Extension tokens */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| EXT_I_%1x (Extension Token) " "| %s(%s: \'%s\')", level, *codepage_attr, peek & 0x0f, Indent (level), map_token (map->global, 0, peek), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; /* 0x43 impossible in ATTR state */ /* 0x44 impossible in ATTR state */ case 0x80: /* EXT_T_0 */ case 0x81: /* EXT_T_1 */ case 0x82: /* EXT_T_2 */ /* Extension tokens */ idx = tvb_get_guintvar (tvb, off+1, &len); { char *s; if (map->ext_t[peek & 0x03]) s = (map->ext_t[peek & 0x03])(tvb, idx, str_tbl); else s = wmem_strdup_printf(wmem_packet_scope(), "EXT_T_%1x (%s)", peek & 0x03, map_token (map->global, 0, peek)); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_T_%1x (Extension Token) " "| %s%s)", level, *codepage_attr, peek & 0x0f, Indent (level), s); } off += 1+len; break; case 0x83: /* STR_T */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| STR_T (Tableref string) " "| %s\'%s\'", level, *codepage_attr, Indent (level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; /* 0x84 impossible in ATTR state */ case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| EXT_%1x (Extension Token) " "| %s(%s)", level, *codepage_attr, peek & 0x0f, Indent (level), map_token (map->global, 0, peek)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ char *str; if (attr_save_known) { /* Knwon attribute */ if (map->opaque_binary_attr) { str = map->opaque_binary_attr(tvb, off + 1, attr_save_known, *codepage_attr, &len); } else { str = default_opaque_binary_attr(tvb, off + 1, attr_save_known, *codepage_attr, &len); } } else { /* lITERAL attribute */ if (map->opaque_literal_tag) { str = map->opaque_literal_attr(tvb, off + 1, attr_save_literal, *codepage_attr, &len); } else { str = default_opaque_literal_attr(tvb, off + 1, attr_save_literal, *codepage_attr, &len); } } proto_tree_add_text (tree, tvb, off, 1 + len, " %3d | Attr | A %3d " "| OPAQUE (Opaque data) " "| %s%s", level, *codepage_attr, Indent (level), str); off += 1 + len; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", level, *codepage_attr); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("ATTR: level = %u, Return: len = %u\n", level, off - offset)); return (off - offset); } break; /* 0xC4 impossible in ATTR state */ default: proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| %-10s (Invalid Token!) " "| WBXML parsing stops here.", level, *codepage_attr, val_to_str_ext (peek, &vals_wbxml1x_global_tokens_ext, "(unknown 0x%x)")); /* Move to end of buffer */ off = tvb_len; break; } else { /* Known atribute token */ if (peek & 0x80) { /* attrValue */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| Known attrValue 0x%02X " "| %s%s", level, *codepage_attr, peek & 0x7f, Indent (level), map_token (map->attrValue, *codepage_attr, peek)); off++; } else { /* attrStart */ attr_save_known = peek & 0x7f; proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| Known attrStart 0x%02X " "| %s%s", level, *codepage_attr, attr_save_known, Indent (level), map_token (map->attrStart, *codepage_attr, peek)); off++; } } } /* End WHILE */ DebugLog(("ATTR: level = %u, Return: len = %u (end of function body)\n", level, off - offset)); return (off - offset); } Commit Message: WBXML: add a basic sanity check for offset overflow This is a naive approach allowing to detact that something went wrong, without the need to replace all proto_tree_add_text() calls as what was done in master-2.0 branch. Bug: 12408 Change-Id: Ia14905005e17ae322c2fc639ad5e491fa08b0108 Reviewed-on: https://code.wireshark.org/review/15310 Reviewed-by: Michael Mann <[email protected]> Reviewed-by: Pascal Quantin <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM( uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) { GLuint count = c.count; uint32 pnames_size; if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) { return error::kOutOfBounds; } const GLenum* pnames = GetSharedMemoryAs<const GLenum*>( c.pnames_shm_id, c.pnames_shm_offset, pnames_size); if (pnames == NULL) { return error::kOutOfBounds; } scoped_array<GLenum> enums(new GLenum[count]); memcpy(enums.get(), pnames, pnames_size); uint32 num_results = 0; for (GLuint ii = 0; ii < count; ++ii) { uint32 num = util_.GLGetNumValuesReturned(enums[ii]); if (num == 0) { SetGLError(GL_INVALID_ENUM, "glGetMulitpleCHROMIUM: pname GL_INVALID_ENUM"); return error::kNoError; } DCHECK_LE(num, 4u); if (!SafeAdd(num_results, num, &num_results)) { return error::kOutOfBounds; } } uint32 result_size = 0; if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) { return error::kOutOfBounds; } if (result_size != static_cast<uint32>(c.size)) { SetGLError(GL_INVALID_VALUE, "glGetMulitpleCHROMIUM: bad size GL_INVALID_VALUE"); return error::kNoError; } GLint* results = GetSharedMemoryAs<GLint*>( c.results_shm_id, c.results_shm_offset, result_size); if (results == NULL) { return error::kOutOfBounds; } for (uint32 ii = 0; ii < num_results; ++ii) { if (results[ii]) { return error::kInvalidArguments; } } GLint* start = results; for (GLuint ii = 0; ii < count; ++ii) { GLsizei num_written = 0; if (!GetHelper(enums[ii], results, &num_written)) { glGetIntegerv(enums[ii], results); } results += num_written; } if (static_cast<uint32>(results - start) != num_results) { return error::kOutOfBounds; } 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 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 lrw_serpent_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct serpent_lrw_ctx *ctx = crypto_tfm_ctx(tfm); int err; err = __serpent_setkey(&ctx->serpent_ctx, key, keylen - SERPENT_BLOCK_SIZE); if (err) return err; return lrw_init_table(&ctx->lrw_table, key + keylen - SERPENT_BLOCK_SIZE); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[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: int res_inverse(vorbis_dsp_state *vd,vorbis_info_residue *info, ogg_int32_t **in,int *nonzero,int ch){ int i,j,k,s,used=0; codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup; codebook *phrasebook=ci->book_param+info->groupbook; int samples_per_partition=info->grouping; int partitions_per_word=phrasebook->dim; int pcmend=ci->blocksizes[vd->W]; if(info->type<2){ int max=pcmend>>1; int end=(info->end<max?info->end:max); int n=end-info->begin; if(n>0){ int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; for(i=0;i<ch;i++) if(nonzero[i]) in[used++]=in[i]; ch=used; if(used){ char **partword=(char **)alloca(ch*sizeof(*partword)); for(j=0;j<ch;j++) partword[j]=(char *)alloca(partwords*partitions_per_word* sizeof(*partword[j])); for(s=0;s<info->stages;s++){ for(i=0;i<partvals;){ if(s==0){ /* fetch the partition word for each channel */ partword[0][i+partitions_per_word-1]=1; for(k=partitions_per_word-2;k>=0;k--) partword[0][i+k]=partword[0][i+k+1]*info->partitions; for(j=1;j<ch;j++) for(k=partitions_per_word-1;k>=0;k--) partword[j][i+k]=partword[j-1][i+k]; for(j=0;j<ch;j++){ int temp=vorbis_book_decode(phrasebook,&vd->opb); if(temp==-1)goto eopbreak; /* this can be done quickly in assembly due to the quotient always being at most six bits */ for(k=0;k<partitions_per_word;k++){ ogg_uint32_t div=partword[j][i+k]; partword[j][i+k]=temp/div; temp-=partword[j][i+k]*div; } } } /* now we decode residual values for the partitions */ for(k=0;k<partitions_per_word && i<partvals;k++,i++) for(j=0;j<ch;j++){ long offset=info->begin+i*samples_per_partition; if(info->stagemasks[(int)partword[j][i]]&(1<<s)){ codebook *stagebook=ci->book_param+ info->stagebooks[(partword[j][i]<<3)+s]; if(info->type){ if(vorbis_book_decodev_add(stagebook,in[j]+offset,&vd->opb, samples_per_partition,-8)==-1) goto eopbreak; }else{ if(vorbis_book_decodevs_add(stagebook,in[j]+offset,&vd->opb, samples_per_partition,-8)==-1) goto eopbreak; } } } } } } } }else{ int max=(pcmend*ch)>>1; int end=(info->end<max?info->end:max); int n=end-info->begin; if(n>0){ int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; char *partword= (char *)alloca(partwords*partitions_per_word*sizeof(*partword)); int beginoff=info->begin/ch; for(i=0;i<ch;i++)if(nonzero[i])break; if(i==ch)return(0); /* no nonzero vectors */ samples_per_partition/=ch; for(s=0;s<info->stages;s++){ for(i=0;i<partvals;){ if(s==0){ int temp; partword[i+partitions_per_word-1]=1; for(k=partitions_per_word-2;k>=0;k--) partword[i+k]=partword[i+k+1]*info->partitions; /* fetch the partition word */ temp=vorbis_book_decode(phrasebook,&vd->opb); if(temp==-1)goto eopbreak; /* this can be done quickly in assembly due to the quotient always being at most six bits */ for(k=0;k<partitions_per_word;k++){ ogg_uint32_t div=partword[i+k]; partword[i+k]=temp/div; temp-=partword[i+k]*div; } } /* now we decode residual values for the partitions */ for(k=0;k<partitions_per_word && i<partvals;k++,i++) if(info->stagemasks[(int)partword[i]]&(1<<s)){ codebook *stagebook=ci->book_param+ info->stagebooks[(partword[i]<<3)+s]; if(vorbis_book_decodevv_add(stagebook,in, i*samples_per_partition+beginoff,ch, &vd->opb, samples_per_partition,-8)==-1) goto eopbreak; } } } } } eopbreak: return 0; } Commit Message: Check partword is in range for # of partitions and reformat tabs->spaces for readability. Bug: 28556125 Change-Id: Id02819a6a5bcc24ba4f8a502081e5cb45272681c CWE ID: CWE-20 Target: 1 Example 2: Code: const AtomicString& TextTrack::ShowingKeyword() { DEFINE_STATIC_LOCAL(const AtomicString, showing, ("showing")); return showing; } Commit Message: Support negative timestamps of TextTrackCue Ensure proper behaviour for negative timestamps of TextTrackCue. 1. Cues with negative startTime should become active from 0s. 2. Cues with negative startTime and endTime should never be active. Bug: 314032 Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d Reviewed-on: https://chromium-review.googlesource.com/863270 Commit-Queue: srirama chandra sekhar <[email protected]> Reviewed-by: Fredrik Söderquist <[email protected]> Cr-Commit-Position: refs/heads/master@{#529012} 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 void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (arg_zsh) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.zshrc", &s) == 0) { if (is_link("/etc/skel/.zshrc")) { fprintf(stderr, "Error: invalid /etc/skel/.zshrc file\n"); exit(1); } if (copy_file("/etc/skel/.zshrc", fname) == 0) { if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.zshrc"); } } else { // FILE *fp = fopen(fname, "w"); if (fp) { fprintf(fp, "\n"); fclose(fp); if (chown(fname, u, g) == -1) errExit("chown"); if (chmod(fname, S_IRUSR | S_IWUSR) < 0) errExit("chown"); fs_logger2("touch", fname); } } free(fname); } else if (arg_csh) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.cshrc", &s) == 0) { if (is_link("/etc/skel/.cshrc")) { fprintf(stderr, "Error: invalid /etc/skel/.cshrc file\n"); exit(1); } if (copy_file("/etc/skel/.cshrc", fname) == 0) { if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.cshrc"); } } else { // /* coverity[toctou] */ FILE *fp = fopen(fname, "w"); if (fp) { fprintf(fp, "\n"); fclose(fp); if (chown(fname, u, g) == -1) errExit("chown"); if (chmod(fname, S_IRUSR | S_IWUSR) < 0) errExit("chown"); fs_logger2("touch", fname); } } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.bashrc", &s) == 0) { if (is_link("/etc/skel/.bashrc")) { fprintf(stderr, "Error: invalid /etc/skel/.bashrc file\n"); exit(1); } if (copy_file("/etc/skel/.bashrc", fname) == 0) { /* coverity[toctou] */ if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.bashrc"); } } free(fname); } } Commit Message: security fix CWE ID: CWE-269 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 xt_compat_check_entry_offsets(const void *base, unsigned int target_offset, unsigned int next_offset) { const struct compat_xt_entry_target *t; const char *e = base; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct compat_xt_standard_target) != next_offset) return -EINVAL; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: unsigned LocalFrameClientImpl::BackForwardLength() { WebViewImpl* webview = web_frame_->ViewImpl(); if (!webview || !webview->Client()) return 0; return webview->Client()->HistoryBackListCount() + 1 + webview->Client()->HistoryForwardListCount(); } 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: MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info, const DrawInfo *draw_info) { DrawInfo *clone_info; ExceptionInfo *exception; clone_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*clone_info)); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); exception=AcquireExceptionInfo(); if (draw_info->primitive != (char *) NULL) (void) CloneString(&clone_info->primitive,draw_info->primitive); if (draw_info->geometry != (char *) NULL) (void) CloneString(&clone_info->geometry,draw_info->geometry); clone_info->compliance=draw_info->compliance; clone_info->viewbox=draw_info->viewbox; clone_info->affine=draw_info->affine; clone_info->gravity=draw_info->gravity; clone_info->fill=draw_info->fill; clone_info->stroke=draw_info->stroke; clone_info->stroke_width=draw_info->stroke_width; if (draw_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue, exception); if (draw_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke_antialias=draw_info->stroke_antialias; clone_info->text_antialias=draw_info->text_antialias; clone_info->fill_rule=draw_info->fill_rule; clone_info->linecap=draw_info->linecap; clone_info->linejoin=draw_info->linejoin; clone_info->miterlimit=draw_info->miterlimit; clone_info->dash_offset=draw_info->dash_offset; clone_info->decorate=draw_info->decorate; clone_info->compose=draw_info->compose; if (draw_info->text != (char *) NULL) (void) CloneString(&clone_info->text,draw_info->text); if (draw_info->font != (char *) NULL) (void) CloneString(&clone_info->font,draw_info->font); if (draw_info->metrics != (char *) NULL) (void) CloneString(&clone_info->metrics,draw_info->metrics); if (draw_info->family != (char *) NULL) (void) CloneString(&clone_info->family,draw_info->family); clone_info->style=draw_info->style; clone_info->stretch=draw_info->stretch; clone_info->weight=draw_info->weight; if (draw_info->encoding != (char *) NULL) (void) CloneString(&clone_info->encoding,draw_info->encoding); clone_info->pointsize=draw_info->pointsize; clone_info->kerning=draw_info->kerning; clone_info->interline_spacing=draw_info->interline_spacing; clone_info->interword_spacing=draw_info->interword_spacing; clone_info->direction=draw_info->direction; if (draw_info->density != (char *) NULL) (void) CloneString(&clone_info->density,draw_info->density); clone_info->align=draw_info->align; clone_info->undercolor=draw_info->undercolor; clone_info->border_color=draw_info->border_color; if (draw_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) { register ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= MagickEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memset(clone_info->dash_pattern,0,(size_t) (2*x+2)* sizeof(*clone_info->dash_pattern)); (void) memcpy(clone_info->dash_pattern,draw_info->dash_pattern,(size_t) (x+1)*sizeof(*clone_info->dash_pattern)); } clone_info->gradient=draw_info->gradient; if (draw_info->gradient.stops != (StopInfo *) NULL) { size_t number_stops; number_stops=clone_info->gradient.number_stops; clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t) number_stops,sizeof(*clone_info->gradient.stops)); if (clone_info->gradient.stops == (StopInfo *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memcpy(clone_info->gradient.stops,draw_info->gradient.stops, (size_t) number_stops*sizeof(*clone_info->gradient.stops)); } clone_info->bounds=draw_info->bounds; clone_info->fill_alpha=draw_info->fill_alpha; clone_info->stroke_alpha=draw_info->stroke_alpha; clone_info->element_reference=draw_info->element_reference; clone_info->clip_path=draw_info->clip_path; clone_info->clip_units=draw_info->clip_units; if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) clone_info->clipping_mask=CloneImage(draw_info->clipping_mask,0,0, MagickTrue,exception); if (draw_info->composite_mask != (Image *) NULL) clone_info->composite_mask=CloneImage(draw_info->composite_mask,0,0, MagickTrue,exception); clone_info->render=draw_info->render; clone_info->debug=IsEventLogging(); exception=DestroyExceptionInfo(exception); return(clone_info); } Commit Message: ... 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 int php_stream_temp_seek(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (!ts->innerstream) { *newoffs = -1; return -1; } ret = php_stream_seek(ts->innerstream, offset, whence); *newoffs = php_stream_tell(ts->innerstream); stream->eof = ts->innerstream->eof; return ret; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static void put_int32(QEMUFile *f, void *pv, size_t size) { int32_t *v = pv; qemu_put_sbe32s(f, v); } 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: static v8::Handle<v8::Value> convert5Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert5"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(e*, , V8e::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8e::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert5(); 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: 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 BrowserContextDestroyer::RenderProcessHostDestroyed( content::RenderProcessHost* host) { DCHECK_GT(pending_hosts_, 0U); if (--pending_hosts_ != 0) { return; } //// static if (content::RenderProcessHost::run_renderer_in_process()) { FinishDestroyContext(); } else { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&BrowserContextDestroyer::FinishDestroyContext, base::Unretained(this))); } } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: void V8TestObject::SaveSameObjectAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_saveSameObjectAttribute_Getter"); test_object_v8_internal::SaveSameObjectAttributeAttributeGetter(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: bool TestDataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const { return add_default_proxy_bypass_rules_; } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} 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: decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (0 == plen) { snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; plen-=32; /* adjust prefix length */ if (64 < plen) return -1; memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[1], (plen + 7) / 8); memcpy(&route_target, &pptr[1], (plen + 7) / 8); if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)), bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } Commit Message: CVE-2017-13053/BGP: fix VPN route target bounds checks decode_rt_routing_info() didn't check bounds before fetching 4 octets of the origin AS field and could over-read the input buffer, put it right. It also fetched the varying number of octets of the route target field from 4 octets lower than the correct offset, put it right. It also used the same temporary buffer explicitly through as_printf() and implicitly through bgp_vpn_rd_print() so the end result of snprintf() was not what was originally intended. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: static int vr_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { int ret; flush_altivec_to_thread(target); BUILD_BUG_ON(offsetof(struct thread_vr_state, vscr) != offsetof(struct thread_vr_state, vr[32])); ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &target->thread.vr_state, 0, 33 * sizeof(vector128)); if (!ret && count > 0) { /* * We use only the first word of vrsave. */ union { elf_vrreg_t reg; u32 word; } vrsave; memset(&vrsave, 0, sizeof(vrsave)); vrsave.word = target->thread.vrsave; ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &vrsave, 33 * sizeof(vector128), -1); if (!ret) target->thread.vrsave = vrsave.word; } return ret; } Commit Message: powerpc/tm: Flush TM only if CPU has TM feature Commit cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump") added code to access TM SPRs in flush_tmregs_to_thread(). However flush_tmregs_to_thread() does not check if TM feature is available on CPU before trying to access TM SPRs in order to copy live state to thread structures. flush_tmregs_to_thread() is indeed guarded by CONFIG_PPC_TRANSACTIONAL_MEM but it might be the case that kernel was compiled with CONFIG_PPC_TRANSACTIONAL_MEM enabled and ran on a CPU without TM feature available, thus rendering the execution of TM instructions that are treated by the CPU as illegal instructions. The fix is just to add proper checking in flush_tmregs_to_thread() if CPU has the TM feature before accessing any TM-specific resource, returning immediately if TM is no available on the CPU. Adding that checking in flush_tmregs_to_thread() instead of in places where it is called, like in vsr_get() and vsr_set(), is better because avoids the same problem cropping up elsewhere. Cc: [email protected] # v4.13+ Fixes: cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump") Signed-off-by: Gustavo Romero <[email protected]> Reviewed-by: Cyril Bur <[email protected]> Signed-off-by: Michael Ellerman <[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: generate_fips (RSA_secret_key *sk, unsigned int nbits, unsigned long use_e, gcry_sexp_t testparms, int transient_key) { gcry_mpi_t p, q; /* the two primes */ gcry_mpi_t d; /* the private key */ gcry_mpi_t u; gcry_mpi_t p1, q1; gcry_mpi_t n; /* the public key */ gcry_mpi_t e; /* the exponent */ gcry_mpi_t g; gcry_mpi_t minp; gcry_mpi_t diff, mindiff; gcry_random_level_t random_level; unsigned int pbits = nbits/2; unsigned int i; int pqswitch; gpg_err_code_t ec = GPG_ERR_NO_PRIME; if (nbits < 1024 || (nbits & 0x1FF)) return GPG_ERR_INV_VALUE; if (_gcry_enforced_fips_mode() && nbits != 2048 && nbits != 3072) return GPG_ERR_INV_VALUE; /* The random quality depends on the transient_key flag. */ random_level = transient_key ? GCRY_STRONG_RANDOM : GCRY_VERY_STRONG_RANDOM; if (testparms) { /* Parameters to derive the key are given. */ /* Note that we explicitly need to setup the values of tbl because some compilers (e.g. OpenWatcom, IRIX) don't allow to initialize a structure with automatic variables. */ struct { const char *name; gcry_mpi_t *value; } tbl[] = { { "e" }, { "p" }, { "q" }, { NULL } }; int idx; gcry_sexp_t oneparm; tbl[0].value = &e; tbl[1].value = &p; tbl[2].value = &q; for (idx=0; tbl[idx].name; idx++) { oneparm = sexp_find_token (testparms, tbl[idx].name, 0); if (oneparm) { *tbl[idx].value = sexp_nth_mpi (oneparm, 1, GCRYMPI_FMT_USG); sexp_release (oneparm); } } for (idx=0; tbl[idx].name; idx++) if (!*tbl[idx].value) break; if (tbl[idx].name) { /* At least one parameter is missing. */ for (idx=0; tbl[idx].name; idx++) _gcry_mpi_release (*tbl[idx].value); return GPG_ERR_MISSING_VALUE; } } else { if (use_e < 65537) use_e = 65537; /* This is the smallest value allowed by FIPS */ e = mpi_alloc ((32+BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB); use_e |= 1; /* make sure this is odd */ mpi_set_ui (e, use_e); p = mpi_snew (pbits); q = mpi_snew (pbits); } n = mpi_new (nbits); d = mpi_snew (nbits); u = mpi_snew (nbits); /* prepare approximate minimum p and q */ minp = mpi_new (pbits); mpi_set_ui (minp, 0xB504F334); mpi_lshift (minp, minp, pbits - 32); /* prepare minimum p and q difference */ diff = mpi_new (pbits); mindiff = mpi_new (pbits - 99); mpi_set_ui (mindiff, 1); mpi_lshift (mindiff, mindiff, pbits - 100); p1 = mpi_snew (pbits); q1 = mpi_snew (pbits); g = mpi_snew (pbits); retry: /* generate p and q */ for (i = 0; i < 5 * pbits; i++) { ploop: if (!testparms) { _gcry_mpi_randomize (p, pbits, random_level); } if (mpi_cmp (p, minp) < 0) { if (testparms) goto err; goto ploop; } mpi_sub_ui (p1, p, 1); if (mpi_gcd (g, p1, e)) { if (_gcry_fips186_4_prime_check (p, pbits) != GPG_ERR_NO_ERROR) { /* not a prime */ if (testparms) goto err; } else break; } else if (testparms) goto err; } if (i >= 5 * pbits) goto err; for (i = 0; i < 5 * pbits; i++) { qloop: if (!testparms) { _gcry_mpi_randomize (q, pbits, random_level); } if (mpi_cmp (q, minp) < 0) { if (testparms) goto err; goto qloop; } if (mpi_cmp (p, q) > 0) { pqswitch = 1; mpi_sub (diff, p, q); } else { pqswitch = 0; mpi_sub (diff, q, p); } if (mpi_cmp (diff, mindiff) < 0) { if (testparms) goto err; goto qloop; } mpi_sub_ui (q1, q, 1); if (mpi_gcd (g, q1, e)) { if (_gcry_fips186_4_prime_check (q, pbits) != GPG_ERR_NO_ERROR) { /* not a prime */ if (testparms) goto err; } else break; } else if (testparms) goto err; } if (i >= 5 * pbits) goto err; if (testparms) { mpi_clear (p); mpi_clear (q); } else { gcry_mpi_t f; if (pqswitch) { gcry_mpi_t tmp; tmp = p; p = q; q = tmp; } f = mpi_snew (nbits); /* calculate the modulus */ mpi_mul (n, p, q); /* calculate the secret key d = e^1 mod phi */ mpi_gcd (g, p1, q1); mpi_fdiv_q (f, p1, g); mpi_mul (f, f, q1); mpi_invm (d, e, f); _gcry_mpi_release (f); if (mpi_get_nbits (d) < pbits) goto retry; /* calculate the inverse of p and q (used for chinese remainder theorem)*/ mpi_invm (u, p, q ); } ec = 0; if (DBG_CIPHER) { log_mpidump(" p= ", p ); log_mpidump(" q= ", q ); log_mpidump(" n= ", n ); log_mpidump(" e= ", e ); log_mpidump(" d= ", d ); log_mpidump(" u= ", u ); } err: _gcry_mpi_release (p1); _gcry_mpi_release (q1); _gcry_mpi_release (g); _gcry_mpi_release (minp); _gcry_mpi_release (mindiff); _gcry_mpi_release (diff); sk->n = n; sk->e = e; sk->p = p; sk->q = q; sk->d = d; sk->u = u; /* Now we can test our keys. */ if (ec || (!testparms && test_keys (sk, nbits - 64))) { _gcry_mpi_release (sk->n); sk->n = NULL; _gcry_mpi_release (sk->e); sk->e = NULL; _gcry_mpi_release (sk->p); sk->p = NULL; _gcry_mpi_release (sk->q); sk->q = NULL; _gcry_mpi_release (sk->d); sk->d = NULL; _gcry_mpi_release (sk->u); sk->u = NULL; if (!ec) { fips_signal_error ("self-test after key generation failed"); return GPG_ERR_SELFTEST_FAILED; } } return ec; } Commit Message: 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: ~InputMethodStatusConnection() { } bool IBusConnectionsAreAlive() { return ibus_ && ibus_bus_is_connected(ibus_) && ibus_config_; } void MaybeRestoreConnections() { if (IBusConnectionsAreAlive()) { return; } MaybeCreateIBus(); MaybeRestoreIBusConfig(); if (IBusConnectionsAreAlive()) { ConnectPanelServiceSignals(); if (connection_change_handler_) { LOG(INFO) << "Notifying Chrome that IBus is ready."; connection_change_handler_(language_library_, true); } } } void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { LOG(INFO) << "IBus connection is ready."; } } 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."; } } void MaybeDestroyIBusConfig() { if (!ibus_) { LOG(ERROR) << "MaybeDestroyIBusConfig: ibus_ is NULL"; return; } if (ibus_config_ && !ibus_bus_is_connected(ibus_)) { g_object_unref(ibus_config_); ibus_config_ = NULL; } } void FocusIn(const char* input_context_path) { if (!input_context_path) { LOG(ERROR) << "NULL context passed"; } else { DLOG(INFO) << "FocusIn: " << input_context_path; } input_context_path_ = Or(input_context_path, ""); } void RegisterProperties(IBusPropList* ibus_prop_list) { DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)"); ImePropertyList prop_list; // our representation. if (ibus_prop_list) { if (!FlattenPropertyList(ibus_prop_list, &prop_list)) { RegisterProperties(NULL); return; } } register_ime_properties_(language_library_, prop_list); } void UpdateProperty(IBusProperty* ibus_prop) { DLOG(INFO) << "UpdateProperty"; DCHECK(ibus_prop); ImePropertyList prop_list; // our representation. if (!FlattenProperty(ibus_prop, &prop_list)) { LOG(ERROR) << "Malformed properties are detected"; return; } if (!prop_list.empty()) { update_ime_property_(language_library_, prop_list); } } void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const IBusEngineInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kIBusEngines); ++i) { if (kIBusEngines[i].name == std::string(current_global_engine_id)) { engine_info = &kIBusEngines[i]; break; } } if (!engine_info) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } InputMethodDescriptor current_input_method = CreateInputMethodDescriptor(engine_info->name, engine_info->longname, engine_info->layout, engine_info->language); DLOG(INFO) << "Updating the UI. ID:" << current_input_method.id << ", keyboard_layout:" << current_input_method.keyboard_layout; current_input_method_changed_(language_library_, current_input_method); } void ConnectIBusSignals() { if (!ibus_) { return; } g_signal_connect_after(ibus_, "connected", G_CALLBACK(IBusBusConnectedCallback), this); g_signal_connect(ibus_, "disconnected", G_CALLBACK(IBusBusDisconnectedCallback), this); g_signal_connect(ibus_, "global-engine-changed", G_CALLBACK(IBusBusGlobalEngineChangedCallback), this); g_signal_connect(ibus_, "name-owner-changed", G_CALLBACK(IBusBusNameOwnerChangedCallback), this); } void ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInCallback), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesCallback), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyCallback), this); } static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is recovered."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } static void IBusBusDisconnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is terminated."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeDestroyIBusConfig(); if (self->connection_change_handler_) { LOG(INFO) << "Notifying Chrome that IBus is terminated."; self->connection_change_handler_(self->language_library_, false); } } static void IBusBusGlobalEngineChangedCallback( IBusBus* bus, const gchar* engine_name, gpointer user_data) { DCHECK(engine_name); DLOG(INFO) << "Global engine is changed to " << engine_name; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateUI(engine_name); } static void IBusBusNameOwnerChangedCallback( IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name, gpointer user_data) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); DLOG(INFO) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; return; } LOG(INFO) << "IBus config daemon is started. Recovering ibus_config_"; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } static void FocusInCallback(IBusPanelService* panel, const gchar* path, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->FocusIn(path); } static void RegisterPropertiesCallback(IBusPanelService* panel, IBusPropList* prop_list, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->RegisterProperties(prop_list); } static void UpdatePropertyCallback(IBusPanelService* panel, IBusProperty* ibus_prop, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateProperty(ibus_prop); } static void SetImeConfigCallback(GObject* source_object, GAsyncResult* res, gpointer user_data) { IBusConfig* config = IBUS_CONFIG(user_data); g_return_if_fail(config); GError* error = NULL; const gboolean result = ibus_config_set_value_async_finish(config, res, &error); if (!result) { std::string message = "(unknown error)"; if (error && error->message) { message = error->message; } LOG(ERROR) << "ibus_config_set_value_async failed: " << message; } if (error) { g_error_free(error); } g_object_unref(config); } LanguageCurrentInputMethodMonitorFunction current_input_method_changed_; LanguageRegisterImePropertiesFunction register_ime_properties_; LanguageUpdateImePropertyFunction update_ime_property_; LanguageConnectionChangeMonitorFunction connection_change_handler_; void* language_library_; IBusBus* ibus_; IBusConfig* ibus_config_; std::string input_context_path_; }; 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: 1 Example 2: Code: void FrameFetchContext::AddAdditionalRequestHeaders(ResourceRequest& request, FetchResourceType type) { BaseFetchContext::AddAdditionalRequestHeaders(request, type); if (!request.Url().IsEmpty() && !request.Url().ProtocolIsInHTTPFamily()) return; if (IsDetached()) return; if (IsReloadLoadType(MasterDocumentLoader()->LoadType())) request.ClearHTTPHeaderField(HTTPNames::Save_Data); if (GetSettings() && GetSettings()->GetDataSaverEnabled()) request.SetHTTPHeaderField(HTTPNames::Save_Data, "on"); if (GetLocalFrameClient()->IsClientLoFiActiveForFrame()) { request.AddHTTPHeaderField( "Intervention", "<https://www.chromestatus.com/features/6072546726248448>; " "level=\"warning\""); } } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} 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 predictor_decode_mono_3930(APEContext *ctx, int count) { APEPredictor *p = &ctx->predictor; int32_t *decoded0 = ctx->decoded[0]; ape_apply_filters(ctx, ctx->decoded[0], NULL, count); while (count--) { *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA); decoded0++; p->buf++; /* Have we filled the history buffer? */ if (p->buf == p->historybuffer + HISTORY_SIZE) { memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; } } } 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:
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: RenderFrameHostManager::DetermineSiteInstanceForURL( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* current_instance, SiteInstance* dest_instance, ui::PageTransition transition, bool dest_is_restore, bool dest_is_view_source_mode, bool force_browsing_instance_swap, bool was_server_redirect) { SiteInstanceImpl* current_instance_impl = static_cast<SiteInstanceImpl*>(current_instance); NavigationControllerImpl& controller = delegate_->GetControllerForRenderManager(); BrowserContext* browser_context = controller.GetBrowserContext(); if (dest_instance) { if (force_browsing_instance_swap) { CHECK(!dest_instance->IsRelatedSiteInstance( render_frame_host_->GetSiteInstance())); } return SiteInstanceDescriptor(dest_instance); } if (force_browsing_instance_swap) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kProcessPerSite) && ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) { return SiteInstanceDescriptor(current_instance_impl); } if (SiteIsolationPolicy::AreCrossProcessFramesPossible() && !frame_tree_node_->IsMainFrame()) { SiteInstance* parent_site_instance = frame_tree_node_->parent()->current_frame_host()->GetSiteInstance(); if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) && dest_url.SchemeIs(kChromeUIScheme)) { return SiteInstanceDescriptor(parent_site_instance); } } if (!current_instance_impl->HasSite()) { bool use_process_per_site = RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) && RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url); if (current_instance_impl->HasRelatedSiteInstance(dest_url) || use_process_per_site) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } if (current_instance_impl->HasWrongProcessForURL(dest_url)) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); if (dest_is_view_source_mode) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } if (dest_is_restore && GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) { current_instance_impl->SetSite(dest_url); } return SiteInstanceDescriptor(current_instance_impl); } NavigationEntry* current_entry = controller.GetLastCommittedEntry(); if (interstitial_page_) { current_entry = controller.GetEntryAtOffset(-1); } if (current_entry && current_entry->IsViewSourceMode() != dest_is_view_source_mode && !IsRendererDebugURL(dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } GURL about_blank(url::kAboutBlankURL); GURL about_srcdoc(content::kAboutSrcDocURL); bool dest_is_data_or_about = dest_url == about_srcdoc || dest_url == about_blank || dest_url.scheme() == url::kDataScheme; if (source_instance && dest_is_data_or_about && !was_server_redirect) return SiteInstanceDescriptor(source_instance); if (IsCurrentlySameSite(render_frame_host_.get(), dest_url)) return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) { if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* main_frame = frame_tree_node_->frame_tree()->root()->current_frame_host(); if (IsCurrentlySameSite(main_frame, dest_url)) return SiteInstanceDescriptor(main_frame->GetSiteInstance()); } if (frame_tree_node_->opener()) { RenderFrameHostImpl* opener_frame = frame_tree_node_->opener()->current_frame_host(); if (IsCurrentlySameSite(opener_frame, dest_url)) return SiteInstanceDescriptor(opener_frame->GetSiteInstance()); } } if (!frame_tree_node_->IsMainFrame() && SiteIsolationPolicy::IsTopDocumentIsolationEnabled() && !SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url)) { if (GetContentClient() ->browser() ->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation( dest_url, current_instance)) { return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); } return SiteInstanceDescriptor( browser_context, dest_url, SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME); } if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* parent = frame_tree_node_->parent()->current_frame_host(); bool dest_url_requires_dedicated_process = SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url); if (!parent->GetSiteInstance()->RequiresDedicatedProcess() && !dest_url_requires_dedicated_process) { return SiteInstanceDescriptor(parent->GetSiteInstance()); } } return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20 Target: 1 Example 2: Code: PHP_FUNCTION(pg_lo_export) { zval *pgsql_link = NULL; char *file_out, *oid_string, *end_ptr; int oid_strlen; int id = -1, name_len; long oid_long; Oid oid; PGconn *pgsql; int argc = ZEND_NUM_ARGS(); /* allow string to handle large OID value correctly */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rlp", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "lp", &oid_long, &file_out, &name_len) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "sp", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "spr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "lpr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used"); if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 2 or 3 arguments"); RETURN_FALSE; } if (php_check_open_basedir(file_out TSRMLS_CC)) { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (lo_export(pgsql, oid, file_out) == -1) { RETURN_FALSE; } RETURN_TRUE; } 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: v8::Handle<v8::Value> V8TestInterface::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestInterface.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); ExceptionCode ec = 0; STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); ScriptExecutionContext* context = getScriptExecutionContext(); if (!context) return V8Proxy::throwError(V8Proxy::ReferenceError, "TestInterface constructor's associated context is not available", args.GetIsolate()); RefPtr<TestInterface> impl = TestInterface::create(context, str1, str2, ec); v8::Handle<v8::Object> wrapper = args.Holder(); if (ec) goto fail; V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get()); V8DOMWrapper::setJSWrapperForActiveDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate()); return args.Holder(); fail: return throwError(ec, 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: 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: ieee802_15_4_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; int hdrlen; uint16_t fc; uint8_t seq; if (caplen < 3) { ND_PRINT((ndo, "[|802.15.4] %x", caplen)); return caplen; } fc = EXTRACT_LE_16BITS(p); hdrlen = extract_header_length(fc); seq = EXTRACT_LE_8BITS(p + 2); p += 3; caplen -= 3; ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[fc & 0x7])); if (ndo->ndo_vflag) ND_PRINT((ndo,"seq %02x ", seq)); if (hdrlen == -1) { ND_PRINT((ndo,"invalid! ")); return caplen; } if (!ndo->ndo_vflag) { p+= hdrlen; caplen -= hdrlen; } else { uint16_t panid = 0; switch ((fc >> 10) & 0x3) { case 0x00: ND_PRINT((ndo,"none ")); break; case 0x01: ND_PRINT((ndo,"reserved destination addressing mode")); return 0; case 0x02: panid = EXTRACT_LE_16BITS(p); p += 2; ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; break; case 0x03: panid = EXTRACT_LE_16BITS(p); p += 2; ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; break; } ND_PRINT((ndo,"< ")); switch ((fc >> 14) & 0x3) { case 0x00: ND_PRINT((ndo,"none ")); break; case 0x01: ND_PRINT((ndo,"reserved source addressing mode")); return 0; case 0x02: if (!(fc & (1 << 6))) { panid = EXTRACT_LE_16BITS(p); p += 2; } ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; break; case 0x03: if (!(fc & (1 << 6))) { panid = EXTRACT_LE_16BITS(p); p += 2; } ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; break; } caplen -= hdrlen; } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); return 0; } Commit Message: CVE-2017-13000/IEEE 802.15.4: Add more bounds checks. While we're at it, add a bunch of macros for the frame control field's subfields, have the reserved frame types show the frame type value, use the same code path for processing source and destination addresses regardless of whether -v was specified (just leave out the addresses in non-verbose mode), and return the header length in all cases. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: static inline void register_rt_sched_group(struct task_group *tg, int cpu) { } 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: 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 main(int argc, char **argv) { char *filein, *str, *tempfile, *prestring, *outprotos, *protostr; const char *spacestr = " "; char buf[L_BUF_SIZE]; l_uint8 *allheaders; l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret; size_t nbytes; L_BYTEA *ba, *ba2; SARRAY *sa, *safirst; static char mainName[] = "xtractprotos"; if (argc == 1) { fprintf(stderr, "xtractprotos [-prestring=<string>] [-protos=<where>] " "[list of C files]\n" "where the prestring is prepended to each prototype, and \n" "protos can be either 'inline' or the name of an output " "prototype file\n"); return 1; } /* ---------------------------------------------------------------- */ /* Parse input flags and find prestring and outprotos, if requested */ /* ---------------------------------------------------------------- */ prestring = outprotos = NULL; in_line = FALSE; nflags = 0; maxindex = L_MIN(3, argc); for (i = 1; i < maxindex; i++) { if (argv[i][0] == '-') { if (!strncmp(argv[i], "-prestring", 10)) { nflags++; ret = sscanf(argv[i] + 1, "prestring=%s", buf); if (ret != 1) { fprintf(stderr, "parse failure for prestring\n"); return 1; } if ((len = strlen(buf)) > L_BUF_SIZE - 3) { L_WARNING("prestring too large; omitting!\n", mainName); } else { buf[len] = ' '; buf[len + 1] = '\0'; prestring = stringNew(buf); } } else if (!strncmp(argv[i], "-protos", 7)) { nflags++; ret = sscanf(argv[i] + 1, "protos=%s", buf); if (ret != 1) { fprintf(stderr, "parse failure for protos\n"); return 1; } outprotos = stringNew(buf); if (!strncmp(outprotos, "inline", 7)) in_line = TRUE; } } } if (argc - nflags < 2) { fprintf(stderr, "no files specified!\n"); return 1; } /* ---------------------------------------------------------------- */ /* Generate the prototype string */ /* ---------------------------------------------------------------- */ ba = l_byteaCreate(500); /* First the extern C head */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)"/*", L_COPY); snprintf(buf, L_BUF_SIZE, " * These prototypes were autogen'd by xtractprotos, v. %s", version); sarrayAddString(sa, buf, L_COPY); sarrayAddString(sa, (char *)" */", L_COPY); sarrayAddString(sa, (char *)"#ifdef __cplusplus", L_COPY); sarrayAddString(sa, (char *)"extern \"C\" {", L_COPY); sarrayAddString(sa, (char *)"#endif /* __cplusplus */\n", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); /* Then the prototypes */ firstfile = 1 + nflags; protos_added = FALSE; if ((tempfile = l_makeTempFilename()) == NULL) { fprintf(stderr, "failure to make a writeable temp file\n"); return 1; } for (i = firstfile; i < argc; i++) { filein = argv[i]; len = strlen(filein); if (filein[len - 1] == 'h') /* skip .h files */ continue; snprintf(buf, L_BUF_SIZE, "cpp -ansi -DNO_PROTOS %s %s", filein, tempfile); ret = system(buf); /* cpp */ if (ret) { fprintf(stderr, "cpp failure for %s; continuing\n", filein); continue; } if ((str = parseForProtos(tempfile, prestring)) == NULL) { fprintf(stderr, "parse failure for %s; continuing\n", filein); continue; } if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */ l_byteaAppendString(ba, str); protos_added = TRUE; } lept_free(str); } lept_rmfile(tempfile); lept_free(tempfile); /* Lastly the extern C tail */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", L_COPY); sarrayAddString(sa, (char *)"}", L_COPY); sarrayAddString(sa, (char *)"#endif /* __cplusplus */", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); protostr = (char *)l_byteaCopyData(ba, &nbytes); l_byteaDestroy(&ba); /* ---------------------------------------------------------------- */ /* Generate the output */ /* ---------------------------------------------------------------- */ if (!outprotos) { /* just write to stdout */ fprintf(stderr, "%s\n", protostr); lept_free(protostr); return 0; } /* If no protos were found, do nothing further */ if (!protos_added) { fprintf(stderr, "No protos found\n"); lept_free(protostr); return 1; } /* Make the output files */ ba = l_byteaInitFromFile("allheaders_top.txt"); if (!in_line) { snprintf(buf, sizeof(buf), "#include \"%s\"\n", outprotos); l_byteaAppendString(ba, buf); l_binaryWrite(outprotos, "w", protostr, nbytes); } else { l_byteaAppendString(ba, protostr); } ba2 = l_byteaInitFromFile("allheaders_bot.txt"); l_byteaJoin(ba, &ba2); l_byteaWrite("allheaders.h", ba, 0, 0); l_byteaDestroy(&ba); lept_free(protostr); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). 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 ChromeMockRenderThread::OnScriptedPrint( const PrintHostMsg_ScriptedPrint_Params& params, PrintMsg_PrintPages_Params* settings) { if (print_dialog_user_response_ && printer_.get()) { printer_->ScriptedPrint(params.cookie, params.expected_pages_count, params.has_selection, settings); } } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200 Target: 1 Example 2: Code: unsigned char URI_FUNC(HexdigToInt)(URI_CHAR hexdig) { switch (hexdig) { case _UT('0'): case _UT('1'): case _UT('2'): case _UT('3'): case _UT('4'): case _UT('5'): case _UT('6'): case _UT('7'): case _UT('8'): case _UT('9'): return (unsigned char)(9 + hexdig - _UT('9')); case _UT('a'): case _UT('b'): case _UT('c'): case _UT('d'): case _UT('e'): case _UT('f'): return (unsigned char)(15 + hexdig - _UT('f')); case _UT('A'): case _UT('B'): case _UT('C'): case _UT('D'): case _UT('E'): case _UT('F'): return (unsigned char)(15 + hexdig - _UT('F')); default: return 0; } } Commit Message: ResetUri: Protect against NULL 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: void __dev_remove_pack(struct packet_type *pt) { struct list_head *head; struct packet_type *pt1; spin_lock_bh(&ptype_lock); if (pt->type == htons(ETH_P_ALL)) head = &ptype_all; else head = &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK]; list_for_each_entry(pt1, head, list) { if (pt == pt1) { list_del_rcu(&pt->list); goto out; } } printk(KERN_WARNING "dev_remove_pack: %p not found.\n", pt); out: spin_unlock_bh(&ptype_lock); } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const { if (idx < 0) return 0; if (idx >= m_void_element_count) return 0; return m_void_elements + idx; } 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 Target: 1 Example 2: Code: SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata) { struct smb_rqst rqst; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; FILE_SYSTEM_POSIX_INFO *info = NULL; int flags = 0; rc = build_qfs_info_req(&iov, tcon, FS_POSIX_INFORMATION, sizeof(FILE_SYSTEM_POSIX_INFO), persistent_fid, volatile_fid); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = &iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto posix_qfsinf_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; info = (FILE_SYSTEM_POSIX_INFO *)( le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp); rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp_iov, sizeof(FILE_SYSTEM_POSIX_INFO)); if (!rc) copy_posix_fs_info_to_kstatfs(info, fsdata); posix_qfsinf_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } Commit Message: cifs: Fix use-after-free in SMB2_read There is a KASAN use-after-free: BUG: KASAN: use-after-free in SMB2_read+0x1136/0x1190 Read of size 8 at addr ffff8880b4e45e50 by task ln/1009 Should not release the 'req' because it will use in the trace. Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging") Signed-off-by: ZhangXiaoxu <[email protected]> Signed-off-by: Steve French <[email protected]> CC: Stable <[email protected]> 4.18+ Reviewed-by: Pavel Shilovsky <[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 int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base, unsigned int *total, struct ebt_entries_buf_state *state) { unsigned int i, j, startoff, new_offset = 0; /* stores match/watchers/targets & offset of next struct ebt_entry: */ unsigned int offsets[4]; unsigned int *offsets_update = NULL; int ret; char *buf_start; if (*total < sizeof(struct ebt_entries)) return -EINVAL; if (!entry->bitmask) { *total -= sizeof(struct ebt_entries); return ebt_buf_add(state, entry, sizeof(struct ebt_entries)); } if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry)) return -EINVAL; startoff = state->buf_user_offset; /* pull in most part of ebt_entry, it does not need to be changed. */ ret = ebt_buf_add(state, entry, offsetof(struct ebt_entry, watchers_offset)); if (ret < 0) return ret; offsets[0] = sizeof(struct ebt_entry); /* matches come first */ memcpy(&offsets[1], &entry->watchers_offset, sizeof(offsets) - sizeof(offsets[0])); if (state->buf_kern_start) { buf_start = state->buf_kern_start + state->buf_kern_offset; offsets_update = (unsigned int *) buf_start; } ret = ebt_buf_add(state, &offsets[1], sizeof(offsets) - sizeof(offsets[0])); if (ret < 0) return ret; buf_start = (char *) entry; /* 0: matches offset, always follows ebt_entry. * 1: watchers offset, from ebt_entry structure * 2: target offset, from ebt_entry structure * 3: next ebt_entry offset, from ebt_entry structure * * offsets are relative to beginning of struct ebt_entry (i.e., 0). */ for (i = 0, j = 1 ; j < 4 ; j++, i++) { struct compat_ebt_entry_mwt *match32; unsigned int size; char *buf = buf_start + offsets[i]; if (offsets[i] > offsets[j]) return -EINVAL; match32 = (struct compat_ebt_entry_mwt *) buf; size = offsets[j] - offsets[i]; ret = ebt_size_mwt(match32, size, i, state, base); if (ret < 0) return ret; new_offset += ret; if (offsets_update && new_offset) { pr_debug("change offset %d to %d\n", offsets_update[i], offsets[j] + new_offset); offsets_update[i] = offsets[j] + new_offset; } } if (state->buf_kern_start == NULL) { unsigned int offset = buf_start - (char *) base; ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset); if (ret < 0) return ret; } startoff = state->buf_user_offset - startoff; if (WARN_ON(*total < startoff)) return -EINVAL; *total -= startoff; return 0; } Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets We need to make sure the offsets are not out of range of the total size. Also check that they are in ascending order. The WARN_ON triggered by syzkaller (it sets panic_on_warn) is changed to also bail out, no point in continuing parsing. Briefly tested with simple ruleset of -A INPUT --limit 1/s' --log plus jump to custom chains using 32bit ebtables binary. Reported-by: <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> 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 int p4_pmu_handle_irq(struct pt_regs *regs) { struct perf_sample_data data; struct cpu_hw_events *cpuc; struct perf_event *event; struct hw_perf_event *hwc; int idx, handled = 0; u64 val; perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); for (idx = 0; idx < x86_pmu.num_counters; idx++) { int overflow; if (!test_bit(idx, cpuc->active_mask)) { /* catch in-flight IRQs */ if (__test_and_clear_bit(idx, cpuc->running)) handled++; continue; } event = cpuc->events[idx]; hwc = &event->hw; WARN_ON_ONCE(hwc->idx != idx); /* it might be unflagged overflow */ overflow = p4_pmu_clear_cccr_ovf(hwc); val = x86_perf_event_update(event); if (!overflow && (val & (1ULL << (x86_pmu.cntval_bits - 1)))) continue; handled += overflow; /* event overflow for sure */ data.period = event->hw.last_period; if (!x86_perf_event_set_period(event)) continue; if (perf_event_overflow(event, 1, &data, regs)) x86_pmu_stop(event, 0); } if (handled) inc_irq_stat(apic_perf_irqs); /* * When dealing with the unmasking of the LVTPC on P4 perf hw, it has * been observed that the OVF bit flag has to be cleared first _before_ * the LVTPC can be unmasked. * * The reason is the NMI line will continue to be asserted while the OVF * bit is set. This causes a second NMI to generate if the LVTPC is * unmasked before the OVF bit is cleared, leading to unknown NMI * messages. */ apic_write(APIC_LVTPC, APIC_DM_NMI); return handled; } 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 int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu, struct kvm_cpuid2 *cpuid, struct kvm_cpuid_entry2 __user *entries) { int r; r = -E2BIG; if (cpuid->nent < vcpu->arch.cpuid_nent) goto out; r = -EFAULT; if (copy_to_user(entries, &vcpu->arch.cpuid_entries, vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2))) goto out; return 0; out: cpuid->nent = vcpu->arch.cpuid_nent; return r; } Commit Message: KVM: X86: Don't report L2 emulation failures to user-space This patch prevents that emulation failures which result from emulating an instruction for an L2-Guest results in being reported to userspace. Without this patch a malicious L2-Guest would be able to kill the L1 by triggering a race-condition between an vmexit and the instruction emulator. With this patch the L2 will most likely only kill itself in this situation. Signed-off-by: Joerg Roedel <[email protected]> Signed-off-by: Marcelo Tosatti <[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 int generic_print_tuple(struct seq_file *s, const struct nf_conntrack_tuple *tuple) { return 0; } Commit Message: netfilter: conntrack: disable generic tracking for known protocols Given following iptables ruleset: -P FORWARD DROP -A FORWARD -m sctp --dport 9 -j ACCEPT -A FORWARD -p tcp --dport 80 -j ACCEPT -A FORWARD -p tcp -m conntrack -m state ESTABLISHED,RELATED -j ACCEPT One would assume that this allows SCTP on port 9 and TCP on port 80. Unfortunately, if the SCTP conntrack module is not loaded, this allows *all* SCTP communication, to pass though, i.e. -p sctp -j ACCEPT, which we think is a security issue. This is because on the first SCTP packet on port 9, we create a dummy "generic l4" conntrack entry without any port information (since conntrack doesn't know how to extract this information). All subsequent packets that are unknown will then be in established state since they will fallback to proto_generic and will match the 'generic' entry. Our originally proposed version [1] completely disabled generic protocol tracking, but Jozsef suggests to not track protocols for which a more suitable helper is available, hence we now mitigate the issue for in tree known ct protocol helpers only, so that at least NAT and direction information will still be preserved for others. [1] http://www.spinics.net/lists/netfilter-devel/msg33430.html Joint work with Daniel Borkmann. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Jozsef Kadlecsik <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> 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: static int nfs_readlink_reply(unsigned char *pkt, unsigned len) { uint32_t *data; char *path; int rlen; int ret; ret = rpc_check_reply(pkt, 1); if (ret) return ret; data = (uint32_t *)(pkt + sizeof(struct rpc_reply)); data++; rlen = ntohl(net_read_uint32(data)); /* new path length */ data++; path = (char *)data; } else { memcpy(nfs_path, path, rlen); nfs_path[rlen] = 0; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: struct sockaddr_nl *nlmsg_get_dst(struct nl_msg *msg) { return &msg->nm_dst; } Commit Message: 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: static void eat_until_eol( const char **pcur ) { while (**pcur != '\0' && **pcur != '\n') (*pcur)++; } Commit Message: CWE ID: CWE-119 Output:
0