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: int sandbox(void* sandbox_arg) { (void)sandbox_arg; pid_t child_pid = getpid(); if (arg_debug) printf("Initializing child process\n"); close(parent_to_child_fds[1]); close(child_to_parent_fds[0]); wait_for_other(parent_to_child_fds[0]); if (arg_debug && child_pid == 1) printf("PID namespace installed\n"); if (cfg.hostname) { if (sethostname(cfg.hostname, strlen(cfg.hostname)) < 0) errExit("sethostname"); } if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) { chk_chroot(); } preproc_mount_mnt_dir(); if (mount(LIBDIR "/firejail", RUN_FIREJAIL_LIB_DIR, "none", MS_BIND, NULL) < 0) errExit("mounting " RUN_FIREJAIL_LIB_DIR); if (cfg.name) fs_logger2("sandbox name:", cfg.name); fs_logger2int("sandbox pid:", (int) sandbox_pid); if (cfg.chrootdir) fs_logger("sandbox filesystem: chroot"); else if (arg_overlay) fs_logger("sandbox filesystem: overlay"); else fs_logger("sandbox filesystem: local"); fs_logger("install mount namespace"); if (arg_netfilter && any_bridge_configured()) { // assuming by default the client filter netfilter(arg_netfilter_file); } if (arg_netfilter6 && any_bridge_configured()) { // assuming by default the client filter netfilter6(arg_netfilter6_file); } int gw_cfg_failed = 0; // default gw configuration flag if (arg_nonetwork) { net_if_up("lo"); if (arg_debug) printf("Network namespace enabled, only loopback interface available\n"); } else if (arg_netns) { netns(arg_netns); if (arg_debug) printf("Network namespace '%s' activated\n", arg_netns); } else if (any_bridge_configured() || any_interface_configured()) { net_if_up("lo"); if (mac_not_zero(cfg.bridge0.macsandbox)) net_config_mac(cfg.bridge0.devsandbox, cfg.bridge0.macsandbox); sandbox_if_up(&cfg.bridge0); if (mac_not_zero(cfg.bridge1.macsandbox)) net_config_mac(cfg.bridge1.devsandbox, cfg.bridge1.macsandbox); sandbox_if_up(&cfg.bridge1); if (mac_not_zero(cfg.bridge2.macsandbox)) net_config_mac(cfg.bridge2.devsandbox, cfg.bridge2.macsandbox); sandbox_if_up(&cfg.bridge2); if (mac_not_zero(cfg.bridge3.macsandbox)) net_config_mac(cfg.bridge3.devsandbox, cfg.bridge3.macsandbox); sandbox_if_up(&cfg.bridge3); if (cfg.interface0.configured && cfg.interface0.ip) { if (arg_debug) printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface0.ip), cfg.interface0.dev); net_config_interface(cfg.interface0.dev, cfg.interface0.ip, cfg.interface0.mask, cfg.interface0.mtu); } if (cfg.interface1.configured && cfg.interface1.ip) { if (arg_debug) printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface1.ip), cfg.interface1.dev); net_config_interface(cfg.interface1.dev, cfg.interface1.ip, cfg.interface1.mask, cfg.interface1.mtu); } if (cfg.interface2.configured && cfg.interface2.ip) { if (arg_debug) printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface2.ip), cfg.interface2.dev); net_config_interface(cfg.interface2.dev, cfg.interface2.ip, cfg.interface2.mask, cfg.interface2.mtu); } if (cfg.interface3.configured && cfg.interface3.ip) { if (arg_debug) printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface3.ip), cfg.interface3.dev); net_config_interface(cfg.interface3.dev, cfg.interface3.ip, cfg.interface3.mask, cfg.interface3.mtu); } if (cfg.defaultgw) { if (net_add_route(0, 0, cfg.defaultgw)) { fwarning("cannot configure default route\n"); gw_cfg_failed = 1; } } if (arg_debug) printf("Network namespace enabled\n"); } if (!arg_quiet) { if (any_bridge_configured() || any_interface_configured() || cfg.defaultgw || cfg.dns1) { fmessage("\n"); if (any_bridge_configured() || any_interface_configured()) { if (arg_scan) sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 3, PATH_FNET, "printif", "scan"); else sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 2, PATH_FNET, "printif"); } if (cfg.defaultgw != 0) { if (gw_cfg_failed) fmessage("Default gateway configuration failed\n"); else fmessage("Default gateway %d.%d.%d.%d\n", PRINT_IP(cfg.defaultgw)); } if (cfg.dns1 != NULL) fmessage("DNS server %s\n", cfg.dns1); if (cfg.dns2 != NULL) fmessage("DNS server %s\n", cfg.dns2); if (cfg.dns3 != NULL) fmessage("DNS server %s\n", cfg.dns3); if (cfg.dns4 != NULL) fmessage("DNS server %s\n", cfg.dns4); fmessage("\n"); } } if (arg_nonetwork || any_bridge_configured() || any_interface_configured()) { } else { EUID_USER(); env_ibus_load(); EUID_ROOT(); } #ifdef HAVE_SECCOMP if (cfg.protocol) { if (arg_debug) printf("Build protocol filter: %s\n", cfg.protocol); int rv = sbox_run(SBOX_USER | SBOX_CAPS_NONE | SBOX_SECCOMP, 5, PATH_FSECCOMP, "protocol", "build", cfg.protocol, RUN_SECCOMP_PROTOCOL); if (rv) exit(rv); } if (arg_seccomp && (cfg.seccomp_list || cfg.seccomp_list_drop || cfg.seccomp_list_keep)) arg_seccomp_postexec = 1; #endif bool need_preload = arg_trace || arg_tracelog || arg_seccomp_postexec; if (getuid() != 0 && (arg_appimage || cfg.chrootdir || arg_overlay)) { enforce_filters(); need_preload = arg_trace || arg_tracelog; } if (need_preload) fs_trace_preload(); if (cfg.hosts_file) fs_store_hosts_file(); #ifdef HAVE_CHROOT if (cfg.chrootdir) { fs_chroot(cfg.chrootdir); if (need_preload) fs_trace_preload(); } else #endif #ifdef HAVE_OVERLAYFS if (arg_overlay) fs_overlayfs(); else #endif fs_basic_fs(); if (arg_private) { if (cfg.home_private) { // --private= if (cfg.chrootdir) fwarning("private=directory feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private=directory feature is disabled in overlay\n"); else fs_private_homedir(); } else if (cfg.home_private_keep) { // --private-home= if (cfg.chrootdir) fwarning("private-home= feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-home= feature is disabled in overlay\n"); else fs_private_home_list(); } else // --private fs_private(); } if (arg_private_dev) fs_private_dev(); if (arg_private_etc) { if (cfg.chrootdir) fwarning("private-etc feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-etc feature is disabled in overlay\n"); else { fs_private_dir_list("/etc", RUN_ETC_DIR, cfg.etc_private_keep); if (need_preload) fs_trace_preload(); } } if (arg_private_opt) { if (cfg.chrootdir) fwarning("private-opt feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-opt feature is disabled in overlay\n"); else { fs_private_dir_list("/opt", RUN_OPT_DIR, cfg.opt_private_keep); } } if (arg_private_srv) { if (cfg.chrootdir) fwarning("private-srv feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-srv feature is disabled in overlay\n"); else { fs_private_dir_list("/srv", RUN_SRV_DIR, cfg.srv_private_keep); } } if (arg_private_bin && !arg_appimage) { if (cfg.chrootdir) fwarning("private-bin feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-bin feature is disabled in overlay\n"); else { if (arg_x11_xorg) { EUID_USER(); char *tmp; if (asprintf(&tmp, "%s,xauth", cfg.bin_private_keep) == -1) errExit("asprintf"); cfg.bin_private_keep = tmp; EUID_ROOT(); } fs_private_bin_list(); } } if (arg_private_lib && !arg_appimage) { if (cfg.chrootdir) fwarning("private-lib feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-lib feature is disabled in overlay\n"); else { fs_private_lib(); } } if (arg_private_cache) { if (cfg.chrootdir) fwarning("private-cache feature is disabled in chroot\n"); else if (arg_overlay) fwarning("private-cache feature is disabled in overlay\n"); else fs_private_cache(); } if (arg_private_tmp) { EUID_USER(); fs_private_tmp(); EUID_ROOT(); } if (arg_nodbus) dbus_session_disable(); if (cfg.hostname) fs_hostname(cfg.hostname); if (cfg.hosts_file) fs_mount_hosts_file(); if (arg_netns) netns_mounts(arg_netns); fs_proc_sys_dev_boot(); if (checkcfg(CFG_DISABLE_MNT)) fs_mnt(1); else if (arg_disable_mnt) fs_mnt(0); fs_whitelist(); fs_blacklist(); // mkdir and mkfile are processed all over again if (arg_nosound) { pulseaudio_disable(); fs_dev_disable_sound(); } else if (!arg_noautopulse) pulseaudio_init(); if (arg_no3d) fs_dev_disable_3d(); if (arg_notv) fs_dev_disable_tv(); if (arg_nodvd) fs_dev_disable_dvd(); if (arg_nou2f) fs_dev_disable_u2f(); if (arg_novideo) fs_dev_disable_video(); if (need_preload) fs_trace(); fs_resolvconf(); fs_logger_print(); fs_logger_change_owner(); EUID_USER(); int cwd = 0; if (cfg.cwd) { if (chdir(cfg.cwd) == 0) cwd = 1; } if (!cwd) { if (chdir("/") < 0) errExit("chdir"); if (cfg.homedir) { struct stat s; if (stat(cfg.homedir, &s) == 0) { /* coverity[toctou] */ if (chdir(cfg.homedir) < 0) errExit("chdir"); } } } if (arg_debug) { char *cpath = get_current_dir_name(); if (cpath) { printf("Current directory: %s\n", cpath); free(cpath); } } EUID_ROOT(); fs_x11(); if (arg_x11_xorg) x11_xorg(); save_umask(); save_nonewprivs(); set_caps(); save_cpu(); save_cgroup(); #ifdef HAVE_SECCOMP #ifdef SYS_socket if (cfg.protocol) { if (arg_debug) printf("Install protocol filter: %s\n", cfg.protocol); seccomp_load(RUN_SECCOMP_PROTOCOL); // install filter protocol_filter_save(); // save filter in RUN_PROTOCOL_CFG } else { int rv = unlink(RUN_SECCOMP_PROTOCOL); (void) rv; } #endif if (arg_seccomp == 1) { if (cfg.seccomp_list_keep) seccomp_filter_keep(); else seccomp_filter_drop(); } else { // clean seccomp files under /run/firejail/mnt int rv = unlink(RUN_SECCOMP_CFG); rv |= unlink(RUN_SECCOMP_32); (void) rv; } if (arg_memory_deny_write_execute) { if (arg_debug) printf("Install memory write&execute filter\n"); seccomp_load(RUN_SECCOMP_MDWX); // install filter } else { int rv = unlink(RUN_SECCOMP_MDWX); (void) rv; } #endif FILE *rj = create_ready_for_join_file(); save_nogroups(); if (arg_noroot) { int rv = unshare(CLONE_NEWUSER); if (rv == -1) { fwarning("cannot create a new user namespace, going forward without it...\n"); arg_noroot = 0; } } notify_other(child_to_parent_fds[1]); close(child_to_parent_fds[1]); wait_for_other(parent_to_child_fds[0]); close(parent_to_child_fds[0]); if (arg_noroot) { if (arg_debug) printf("noroot user namespace installed\n"); set_caps(); } if (arg_nonewprivs) { prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) != 1) { fwarning("cannot set NO_NEW_PRIVS, it requires a Linux kernel version 3.5 or newer.\n"); if (force_nonewprivs) { fprintf(stderr, "Error: NO_NEW_PRIVS required for this sandbox, exiting ...\n"); exit(1); } } else if (arg_debug) printf("NO_NEW_PRIVS set\n"); } drop_privs(arg_nogroups); prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); if (cfg.cpus) set_cpu_affinity(); pid_t app_pid = fork(); if (app_pid == -1) errExit("fork"); if (app_pid == 0) { #ifdef HAVE_APPARMOR if (checkcfg(CFG_APPARMOR) && arg_apparmor) { errno = 0; if (aa_change_onexec("firejail-default")) { fwarning("Cannot confine the application using AppArmor.\n" "Maybe firejail-default AppArmor profile is not loaded into the kernel.\n" "As root, run \"aa-enforce firejail-default\" to load it.\n"); } else if (arg_debug) printf("AppArmor enabled\n"); } #endif if (arg_nice) set_nice(cfg.nice); set_rlimits(); start_application(0, rj); } fclose(rj); int status = monitor_application(app_pid); // monitor application flush_stdin(); if (WIFEXITED(status)) { return WEXITSTATUS(status); } else { return -1; } } Commit Message: mount runtime seccomp files read-only (#2602) avoid creating locations in the file system that are both writable and executable (in this case for processes with euid of the user). for the same reason also remove user owned libfiles when it is not needed any more CWE ID: CWE-284 Target: 1 Example 2: Code: ProcPseudoramiXGetScreenCount(ClientPtr client) { REQUEST(xPanoramiXGetScreenCountReq); WindowPtr pWin; xPanoramiXGetScreenCountReply rep; register int rc; TRACE; REQUEST_SIZE_MATCH(xPanoramiXGetScreenCountReq); rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); if (rc != Success) return rc; rep.type = X_Reply; rep.length = 0; rep.sequenceNumber = client->sequence; rep.ScreenCount = pseudoramiXNumScreens; rep.window = stuff->window; if (client->swapped) { swaps(&rep.sequenceNumber); swapl(&rep.length); swapl(&rep.window); } WriteToClient(client, sizeof(xPanoramiXGetScreenCountReply),&rep); return Success; } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: const BlockEntry* Cues::GetBlock(const CuePoint* pCP, const CuePoint::TrackPosition* pTP) const { if (pCP == NULL) return NULL; if (pTP == NULL) return NULL; return m_pSegment->GetBlock(*pCP, *pTP); } 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 void dtls1_clear_queues(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; dtls1_hm_fragment_free(frag); pitem_free(item); } while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; pqueue_free(s->d1->buffered_messages); } } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: void PresentationConnection::bindProxy( std::unique_ptr<WebPresentationConnectionProxy> proxy) { DCHECK(proxy); m_proxy = std::move(proxy); } Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures Add layout test. 1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead. BUG=697719 Review-Url: https://codereview.chromium.org/2730123003 Cr-Commit-Position: refs/heads/master@{#455225} 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: HashSet<SVGElement*>* SVGDocumentExtensions::setOfElementsReferencingTarget(SVGElement* referencedElement) const { ASSERT(referencedElement); const HashMap<SVGElement*, OwnPtr<HashSet<SVGElement*> > >::const_iterator it = m_elementDependencies.find(referencedElement); if (it == m_elementDependencies.end()) return 0; return it->value.get(); } Commit Message: SVG: Moving animating <svg> to other iframe should not crash. Moving SVGSVGElement with its SMILTimeContainer already started caused crash before this patch. |SVGDocumentExtentions::startAnimations()| calls begin() against all SMILTimeContainers in the document, but the SMILTimeContainer for <svg> moved from other document may be already started. BUG=369860 Review URL: https://codereview.chromium.org/290353002 git-svn-id: svn://svn.chromium.org/blink/trunk@174338 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: static int http_open(URLContext *h, const char *uri, int flags, AVDictionary **options) { HTTPContext *s = h->priv_data; int ret; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; s->filesize = -1; s->location = av_strdup(uri); if (!s->location) return AVERROR(ENOMEM); if (options) av_dict_copy(&s->chained_options, *options, 0); if (s->headers) { int len = strlen(s->headers); if (len < 2 || strcmp("\r\n", s->headers + len - 2)) { av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n"); ret = av_reallocp(&s->headers, len + 3); if (ret < 0) return ret; s->headers[len] = '\r'; s->headers[len + 1] = '\n'; s->headers[len + 2] = '\0'; } } if (s->listen) { return http_listen(h, uri, flags, options); } ret = http_open_cnx(h, options); if (ret < 0) av_dict_free(&s->chained_options); return ret; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119 Target: 1 Example 2: Code: static void gcm_encrypt_done(struct crypto_async_request *areq, int err) { struct aead_request *req = areq->data; struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req); if (!err) { err = gcm_hash(req, pctx); if (err == -EINPROGRESS || err == -EBUSY) return; else if (!err) { crypto_xor(pctx->auth_tag, pctx->iauth_tag, 16); gcm_enc_copy_hash(req, pctx); } } aead_request_complete(req, err); } 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 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 *uverbs_devnode(struct device *dev, umode_t *mode) { if (mode) *mode = 0666; return kasprintf(GFP_KERNEL, "infiniband/%s", dev_name(dev)); } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-264 Output:
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: modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_MODIFY; log_unauth("kadm5_modify_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_modify_principal((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119 Target: 1 Example 2: Code: ModuleExport void UnregisterDJVUImage(void) { (void) UnregisterMagickInfo("DJVU"); } 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 int __init vhost_scsi_init(void) { int ret = -ENOMEM; /* * Use our own dedicated workqueue for submitting I/O into * target core to avoid contention within system_wq. */ vhost_scsi_workqueue = alloc_workqueue("vhost_scsi", 0, 0); if (!vhost_scsi_workqueue) goto out; ret = vhost_scsi_register(); if (ret < 0) goto out_destroy_workqueue; ret = vhost_scsi_register_configfs(); if (ret < 0) goto out_vhost_scsi_deregister; return 0; out_vhost_scsi_deregister: vhost_scsi_deregister(); out_destroy_workqueue: destroy_workqueue(vhost_scsi_workqueue); out: return ret; }; Commit Message: vhost/scsi: potential memory corruption This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt" to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16. I looked at the context and it turns out that in vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so anything higher than 255 then it is invalid. I have made that the limit now. In vhost_scsi_send_evt() we mask away values higher than 255, but now that the limit has changed, we don't need the mask. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Nicholas Bellinger <[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: void RecordResourceCompletionUMA(bool image_complete, bool css_complete, bool xhr_complete) { base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Image", image_complete); base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Css", css_complete); base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Xhr", xhr_complete); } Commit Message: Remove unused histograms from the background loader offliner. Bug: 975512 Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361 Reviewed-by: Cathy Li <[email protected]> Reviewed-by: Steven Holte <[email protected]> Commit-Queue: Peter Williamson <[email protected]> Cr-Commit-Position: refs/heads/master@{#675332} CWE ID: CWE-119 Target: 1 Example 2: Code: R_API RFlag *r_flag_free(RFlag *f) { int i; for (i = 0; i < R_FLAG_SPACES_MAX; i++) { free (f->spaces[i]); } r_skiplist_free (f->by_off); ht_free (f->ht_name); r_list_free (f->flags); r_list_free (f->spacestack); r_num_free (f->num); free (f); return NULL; } Commit Message: Fix crash in wasm disassembler CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int nfs4_do_setattr(struct inode *inode, struct rpc_cred *cred, struct nfs_fattr *fattr, struct iattr *sattr, struct nfs4_state *state) { struct nfs_server *server = NFS_SERVER(inode); struct nfs4_exception exception = { .state = state, .inode = inode, }; int err; do { err = _nfs4_do_setattr(inode, cred, fattr, sattr, state); switch (err) { case -NFS4ERR_OPENMODE: if (state && !(state->state & FMODE_WRITE)) { err = -EBADF; if (sattr->ia_valid & ATTR_OPEN) err = -EACCES; goto out; } } err = nfs4_handle_exception(server, err, &exception); } while (exception.retry); out: return err; } Commit Message: NFSv4: Check for buffer length in __nfs4_get_acl_uncached Commit 1f1ea6c "NFSv4: Fix buffer overflow checking in __nfs4_get_acl_uncached" accidently dropped the checking for too small result buffer length. If someone uses getxattr on "system.nfs4_acl" on an NFSv4 mount supporting ACLs, the ACL has not been cached and the buffer suplied is too short, we still copy the complete ACL, resulting in kernel and user space memory corruption. Signed-off-by: Sven Wegener <[email protected]> Cc: [email protected] Signed-off-by: Trond Myklebust <[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: predicate_parse(const char *str, int nr_parens, int nr_preds, parse_pred_fn parse_pred, void *data, struct filter_parse_error *pe) { struct prog_entry *prog_stack; struct prog_entry *prog; const char *ptr = str; char *inverts = NULL; int *op_stack; int *top; int invert = 0; int ret = -ENOMEM; int len; int N = 0; int i; nr_preds += 2; /* For TRUE and FALSE */ op_stack = kmalloc_array(nr_parens, sizeof(*op_stack), GFP_KERNEL); if (!op_stack) return ERR_PTR(-ENOMEM); prog_stack = kmalloc_array(nr_preds, sizeof(*prog_stack), GFP_KERNEL); if (!prog_stack) { parse_error(pe, -ENOMEM, 0); goto out_free; } inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL); if (!inverts) { parse_error(pe, -ENOMEM, 0); goto out_free; } top = op_stack; prog = prog_stack; *top = 0; /* First pass */ while (*ptr) { /* #1 */ const char *next = ptr++; if (isspace(*next)) continue; switch (*next) { case '(': /* #2 */ if (top - op_stack > nr_parens) return ERR_PTR(-EINVAL); *(++top) = invert; continue; case '!': /* #3 */ if (!is_not(next)) break; invert = !invert; continue; } if (N >= nr_preds) { parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str); goto out_free; } inverts[N] = invert; /* #4 */ prog[N].target = N-1; len = parse_pred(next, data, ptr - str, pe, &prog[N].pred); if (len < 0) { ret = len; goto out_free; } ptr = next + len; N++; ret = -1; while (1) { /* #5 */ next = ptr++; if (isspace(*next)) continue; switch (*next) { case ')': case '\0': break; case '&': case '|': if (next[1] == next[0]) { ptr++; break; } default: parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str); goto out_free; } invert = *top & INVERT; if (*top & PROCESS_AND) { /* #7 */ update_preds(prog, N - 1, invert); *top &= ~PROCESS_AND; } if (*next == '&') { /* #8 */ *top |= PROCESS_AND; break; } if (*top & PROCESS_OR) { /* #9 */ update_preds(prog, N - 1, !invert); *top &= ~PROCESS_OR; } if (*next == '|') { /* #10 */ *top |= PROCESS_OR; break; } if (!*next) /* #11 */ goto out; if (top == op_stack) { ret = -1; /* Too few '(' */ parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, ptr - str); goto out_free; } top--; /* #12 */ } } out: if (top != op_stack) { /* Too many '(' */ parse_error(pe, FILT_ERR_TOO_MANY_OPEN, ptr - str); goto out_free; } prog[N].pred = NULL; /* #13 */ prog[N].target = 1; /* TRUE */ prog[N+1].pred = NULL; prog[N+1].target = 0; /* FALSE */ prog[N-1].target = N; prog[N-1].when_to_branch = false; /* Second Pass */ for (i = N-1 ; i--; ) { int target = prog[i].target; if (prog[i].when_to_branch == prog[target].when_to_branch) prog[i].target = prog[target].target; } /* Third Pass */ for (i = 0; i < N; i++) { invert = inverts[i] ^ prog[i].when_to_branch; prog[i].when_to_branch = invert; /* Make sure the program always moves forward */ if (WARN_ON(prog[i].target <= i)) { ret = -EINVAL; goto out_free; } } return prog; out_free: kfree(op_stack); kfree(prog_stack); kfree(inverts); return ERR_PTR(ret); } 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: 1 Example 2: Code: const MockAutoFillMetrics* metric_logger() const { return static_cast<const MockAutoFillMetrics*>( AutoFillManager::metric_logger()); } 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 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 InputType::Height() const { return 0; } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: 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 Reset() { error_nframes_ = 0; droppable_nframes_ = 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static void atusb_tx_done(struct atusb *atusb, uint8_t seq) { struct usb_device *usb_dev = atusb->usb_dev; uint8_t expect = atusb->tx_ack_seq; dev_dbg(&usb_dev->dev, "atusb_tx_done (0x%02x/0x%02x)\n", seq, expect); if (seq == expect) { /* TODO check for ifs handling in firmware */ ieee802154_xmit_complete(atusb->hw, atusb->tx_skb, false); } else { /* TODO I experience this case when atusb has a tx complete * irq before probing, we should fix the firmware it's an * unlikely case now that seq == expect is then true, but can * happen and fail with a tx_skb = NULL; */ ieee802154_wake_queue(atusb->hw); if (atusb->tx_skb) dev_kfree_skb_irq(atusb->tx_skb); } } Commit Message: ieee802154: atusb: do not use the stack for buffers to make them DMA able From 4.9 we should really avoid using the stack here as this will not be DMA able on various platforms. This changes the buffers already being present in time of 4.9 being released. This should go into stable as well. Reported-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Stefan Schmidt <[email protected]> Signed-off-by: Marcel Holtmann <[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: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram( Reference ref) { PersistentHistogramData* data = memory_allocator_->GetAsObject<PersistentHistogramData>(ref); const size_t length = memory_allocator_->GetAllocSize(ref); if (!data || data->name[0] == '\0' || reinterpret_cast<char*>(data)[length - 1] != '\0' || data->samples_metadata.id == 0 || data->logged_metadata.id == 0 || (data->logged_metadata.id != data->samples_metadata.id && data->logged_metadata.id != data->samples_metadata.id + 1) || HashMetricName(data->name) != data->samples_metadata.id) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA); NOTREACHED(); return nullptr; } return CreateHistogram(data); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ParamTraits<FilePath>::Read(const Message* m, PickleIterator* iter, param_type* r) { FilePath::StringType value; if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value)) return false; *r = FilePath(value); return true; } Commit Message: Validate that paths don't contain embedded NULLs at deserialization. BUG=166867 Review URL: https://chromiumcodereview.appspot.com/11743009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174935 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: PermissionsData::PageAccess PermissionsData::GetContentScriptAccess( const GURL& document_url, int tab_id, std::string* error) const { base::AutoLock auto_lock(runtime_lock_); const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id); return CanRunOnPage( document_url, tab_id, active_permissions_unsafe_->scriptable_hosts(), withheld_permissions_unsafe_->scriptable_hosts(), tab_permissions ? &tab_permissions->scriptable_hosts() : nullptr, error); } Commit Message: Call CanCaptureVisiblePage in page capture API. Currently the pageCapture permission allows access to arbitrary local files and chrome:// pages which can be a security concern. In order to address this, the page capture API needs to be changed similar to the captureVisibleTab API. The API will now only allow extensions to capture otherwise-restricted URLs if the user has granted activeTab. In addition, file:// URLs are only capturable with the "Allow on file URLs" option enabled. Bug: 893087 Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624 Reviewed-on: https://chromium-review.googlesource.com/c/1330689 Commit-Queue: Bettina Dea <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Varun Khaneja <[email protected]> Cr-Commit-Position: refs/heads/master@{#615248} 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 void AddImpl(Handle<JSObject> object, uint32_t index, Handle<Object> value, PropertyAttributes attributes, uint32_t new_capacity) { PropertyDetails details(kData, attributes, 0, PropertyCellType::kNoCell); Handle<SeededNumberDictionary> dictionary = object->HasFastElements() || object->HasFastStringWrapperElements() ? JSObject::NormalizeElements(object) : handle(SeededNumberDictionary::cast(object->elements())); Handle<SeededNumberDictionary> new_dictionary = SeededNumberDictionary::AddNumberEntry(dictionary, index, value, details, object); if (attributes != NONE) object->RequireSlowElements(*new_dictionary); if (dictionary.is_identical_to(new_dictionary)) return; object->set_elements(*new_dictionary); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704 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 AudioTrack::Parse( Segment* pSegment, const Info& info, long long element_start, long long element_size, AudioTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kAudio) return -1; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; double rate = 8000.0; // MKV default long long channels = 1; long long bit_depth = 0; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x35) //Sample Rate { status = UnserializeFloat(pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x1F) //Channel Count { channels = UnserializeUInt(pReader, pos, size); if (channels <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x2264) //Bit Depth { bit_depth = UnserializeUInt(pReader, pos, size); if (bit_depth <= 0) return E_FILE_FORMAT_INVALID; } pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); AudioTrack* const pTrack = new (std::nothrow) AudioTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; //generic error const int status = info.Copy(pTrack->m_info); if (status) { delete pTrack; return status; } pTrack->m_rate = rate; pTrack->m_channels = channels; pTrack->m_bitDepth = bit_depth; 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 void btif_hl_proc_abort_ind(tBTA_HL_MCL_HANDLE mcl_handle){ BTIF_TRACE_DEBUG("%s", __FUNCTION__ ); btif_hl_app_cb_t *p_acb; UINT8 i,j; for (i=0; i<BTA_HL_NUM_APPS; i++) { p_acb =BTIF_HL_GET_APP_CB_PTR(i); for (j=0; j < BTA_HL_NUM_MCLS ; j++) { if (p_acb->mcb[j].in_use) BTIF_TRACE_DEBUG("btif_hl_find_mcl_idx_using_handle: app_idx=%d,mcl_idx =%d mcl_handle=%d",i,j,p_acb->mcb[j].mcl_handle); if (p_acb->mcb[j].in_use && (p_acb->mcb[j].mcl_handle == mcl_handle)) { btif_hl_stop_cch_timer(i, j); btif_hl_send_setup_disconnected_cb(i, j); btif_hl_clean_mcl_cb(i, j); } } } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int perf_event_task_disable(void) { struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) perf_event_for_each_child(event, perf_event_disable); mutex_unlock(&current->perf_event_mutex); return 0; } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264 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: MockAudioRendererHost(base::RunLoop* auth_run_loop, int render_process_id, media::AudioManager* audio_manager, AudioMirroringManager* mirroring_manager, MediaStreamManager* media_stream_manager, const std::string& salt) : AudioRendererHost(render_process_id, audio_manager, mirroring_manager, media_stream_manager, salt), shared_memory_length_(0), auth_run_loop_(auth_run_loop) { set_render_frame_id_validate_function_for_testing(&ValidateRenderFrameId); } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID: Target: 1 Example 2: Code: bool Element::hasActiveAnimations() const { return hasRareData() && elementRareData()->activeAnimations() && elementRareData()->activeAnimations()->size(); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 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: ExtensionFunction::ResponseAction TabsCaptureVisibleTabFunction::Run() { using api::extension_types::ImageDetails; EXTENSION_FUNCTION_VALIDATE(args_); int context_id = extension_misc::kCurrentWindowId; args_->GetInteger(0, &context_id); std::unique_ptr<ImageDetails> image_details; if (args_->GetSize() > 1) { base::Value* spec = NULL; EXTENSION_FUNCTION_VALIDATE(args_->Get(1, &spec) && spec); image_details = ImageDetails::FromValue(*spec); } std::string error; WebContents* contents = GetWebContentsForID(context_id, &error); const CaptureResult capture_result = CaptureAsync( contents, image_details.get(), base::BindOnce(&TabsCaptureVisibleTabFunction::CopyFromSurfaceComplete, this)); if (capture_result == OK) { return did_respond() ? AlreadyResponded() : RespondLater(); } return RespondNow(Error(CaptureResultToErrorMessage(capture_result))); } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#548891} 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: int exfat_mount(struct exfat* ef, const char* spec, const char* options) { int rc; enum exfat_mode mode; exfat_tzset(); memset(ef, 0, sizeof(struct exfat)); parse_options(ef, options); if (match_option(options, "ro")) mode = EXFAT_MODE_RO; else if (match_option(options, "ro_fallback")) mode = EXFAT_MODE_ANY; else mode = EXFAT_MODE_RW; ef->dev = exfat_open(spec, mode); if (ef->dev == NULL) return -EIO; if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO) { if (mode == EXFAT_MODE_ANY) ef->ro = -1; else ef->ro = 1; } ef->sb = malloc(sizeof(struct exfat_super_block)); if (ef->sb == NULL) { exfat_close(ef->dev); exfat_error("failed to allocate memory for the super block"); return -ENOMEM; } memset(ef->sb, 0, sizeof(struct exfat_super_block)); if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to read boot sector"); return -EIO; } if (memcmp(ef->sb->oem_name, "EXFAT ", 8) != 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("exFAT file system is not found"); return -EIO; } ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb)); if (ef->zero_cluster == NULL) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate zero sector"); return -ENOMEM; } /* use zero_cluster as a temporary buffer for VBR checksum verification */ if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb))) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb)); if (ef->sb->version.major != 1 || ef->sb->version.minor != 0) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported exFAT version: %hhu.%hhu", ef->sb->version.major, ef->sb->version.minor); free(ef->sb); return -EIO; } if (ef->sb->fat_count != 1) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported FAT count: %hhu", ef->sb->fat_count); free(ef->sb); return -EIO; } /* officially exFAT supports cluster size up to 32 MB */ if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("too big cluster size: 2^%d", (int) ef->sb->sector_bits + (int) ef->sb->spc_bits); free(ef->sb); return -EIO; } if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) > exfat_get_size(ef->dev)) { /* this can cause I/O errors later but we don't fail mounting to let user rescue data */ exfat_warn("file system is larger than underlying device: " "%"PRIu64" > %"PRIu64, le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb), exfat_get_size(ef->dev)); } ef->root = malloc(sizeof(struct exfat_node)); if (ef->root == NULL) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate root node"); return -ENOMEM; } memset(ef->root, 0, sizeof(struct exfat_node)); ef->root->flags = EXFAT_ATTRIB_DIR; ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster); ef->root->fptr_cluster = ef->root->start_cluster; ef->root->name[0] = cpu_to_le16('\0'); ef->root->size = rootdir_size(ef); if (ef->root->size == 0) { free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } /* exFAT does not have time attributes for the root directory */ ef->root->mtime = 0; ef->root->atime = 0; /* always keep at least 1 reference to the root node */ exfat_get_node(ef->root); rc = exfat_cache_directory(ef, ef->root); if (rc != 0) goto error; if (ef->upcase == NULL) { exfat_error("upcase table is not found"); goto error; } if (ef->cmap.chunk == NULL) { exfat_error("clusters bitmap is not found"); goto error; } if (prepare_super_block(ef) != 0) goto error; return 0; error: exfat_put_node(ef, ef->root); exfat_reset_cache(ef); free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } Commit Message: Check sector and cluster size before use. Otherwise malformed FS can cause heap corruption. CWE ID: CWE-119 Target: 1 Example 2: Code: int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info) { bool pr = false; u32 msr = msr_info->index; u64 data = msr_info->data; switch (msr) { case MSR_AMD64_NB_CFG: case MSR_IA32_UCODE_REV: case MSR_IA32_UCODE_WRITE: case MSR_VM_HSAVE_PA: case MSR_AMD64_PATCH_LOADER: case MSR_AMD64_BU_CFG2: break; case MSR_EFER: return set_efer(vcpu, data); case MSR_K7_HWCR: data &= ~(u64)0x40; /* ignore flush filter disable */ data &= ~(u64)0x100; /* ignore ignne emulation enable */ data &= ~(u64)0x8; /* ignore TLB cache disable */ data &= ~(u64)0x40000; /* ignore Mc status write enable */ if (data != 0) { vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n", data); return 1; } break; case MSR_FAM10H_MMIO_CONF_BASE: if (data != 0) { vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: " "0x%llx\n", data); return 1; } break; case MSR_IA32_DEBUGCTLMSR: if (!data) { /* We support the non-activated case already */ break; } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) { /* Values other than LBR and BTF are vendor-specific, thus reserved and should throw a #GP */ return 1; } vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n", __func__, data); break; case 0x200 ... 0x2ff: return set_msr_mtrr(vcpu, msr, data); case MSR_IA32_APICBASE: return kvm_set_apic_base(vcpu, msr_info); case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff: return kvm_x2apic_msr_write(vcpu, msr, data); case MSR_IA32_TSCDEADLINE: kvm_set_lapic_tscdeadline_msr(vcpu, data); break; case MSR_IA32_TSC_ADJUST: if (guest_cpuid_has_tsc_adjust(vcpu)) { if (!msr_info->host_initiated) { u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr; kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true); } vcpu->arch.ia32_tsc_adjust_msr = data; } break; case MSR_IA32_MISC_ENABLE: vcpu->arch.ia32_misc_enable_msr = data; break; case MSR_KVM_WALL_CLOCK_NEW: case MSR_KVM_WALL_CLOCK: vcpu->kvm->arch.wall_clock = data; kvm_write_wall_clock(vcpu->kvm, data); break; case MSR_KVM_SYSTEM_TIME_NEW: case MSR_KVM_SYSTEM_TIME: { u64 gpa_offset; kvmclock_reset(vcpu); vcpu->arch.time = data; kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu); /* we verify if the enable bit is set... */ if (!(data & 1)) break; gpa_offset = data & ~(PAGE_MASK | 1); if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.pv_time, data & ~1ULL, sizeof(struct pvclock_vcpu_time_info))) vcpu->arch.pv_time_enabled = false; else vcpu->arch.pv_time_enabled = true; break; } case MSR_KVM_ASYNC_PF_EN: if (kvm_pv_enable_async_pf(vcpu, data)) return 1; break; case MSR_KVM_STEAL_TIME: if (unlikely(!sched_info_on())) return 1; if (data & KVM_STEAL_RESERVED_MASK) return 1; if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime, data & KVM_STEAL_VALID_BITS, sizeof(struct kvm_steal_time))) return 1; vcpu->arch.st.msr_val = data; if (!(data & KVM_MSR_ENABLED)) break; vcpu->arch.st.last_steal = current->sched_info.run_delay; preempt_disable(); accumulate_steal_time(vcpu); preempt_enable(); kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu); break; case MSR_KVM_PV_EOI_EN: if (kvm_lapic_enable_pv_eoi(vcpu, data)) return 1; break; case MSR_IA32_MCG_CTL: case MSR_IA32_MCG_STATUS: case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1: return set_msr_mce(vcpu, msr, data); /* Performance counters are not protected by a CPUID bit, * so we should check all of them in the generic path for the sake of * cross vendor migration. * Writing a zero into the event select MSRs disables them, * which we perfectly emulate ;-). Any other value should be at least * reported, some guests depend on them. */ case MSR_K7_EVNTSEL0: case MSR_K7_EVNTSEL1: case MSR_K7_EVNTSEL2: case MSR_K7_EVNTSEL3: if (data != 0) vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: " "0x%x data 0x%llx\n", msr, data); break; /* at least RHEL 4 unconditionally writes to the perfctr registers, * so we ignore writes to make it happy. */ case MSR_K7_PERFCTR0: case MSR_K7_PERFCTR1: case MSR_K7_PERFCTR2: case MSR_K7_PERFCTR3: vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: " "0x%x data 0x%llx\n", msr, data); break; case MSR_P6_PERFCTR0: case MSR_P6_PERFCTR1: pr = true; case MSR_P6_EVNTSEL0: case MSR_P6_EVNTSEL1: if (kvm_pmu_msr(vcpu, msr)) return kvm_pmu_set_msr(vcpu, msr_info); if (pr || data != 0) vcpu_unimpl(vcpu, "disabled perfctr wrmsr: " "0x%x data 0x%llx\n", msr, data); break; case MSR_K7_CLK_CTL: /* * Ignore all writes to this no longer documented MSR. * Writes are only relevant for old K7 processors, * all pre-dating SVM, but a recommended workaround from * AMD for these chips. It is possible to specify the * affected processor models on the command line, hence * the need to ignore the workaround. */ break; case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15: if (kvm_hv_msr_partition_wide(msr)) { int r; mutex_lock(&vcpu->kvm->lock); r = set_msr_hyperv_pw(vcpu, msr, data); mutex_unlock(&vcpu->kvm->lock); return r; } else return set_msr_hyperv(vcpu, msr, data); break; case MSR_IA32_BBL_CR_CTL3: /* Drop writes to this legacy MSR -- see rdmsr * counterpart for further detail. */ vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data); break; case MSR_AMD64_OSVW_ID_LENGTH: if (!guest_cpuid_has_osvw(vcpu)) return 1; vcpu->arch.osvw.length = data; break; case MSR_AMD64_OSVW_STATUS: if (!guest_cpuid_has_osvw(vcpu)) return 1; vcpu->arch.osvw.status = data; break; default: if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr)) return xen_hvm_config(vcpu, data); if (kvm_pmu_msr(vcpu, msr)) return kvm_pmu_set_msr(vcpu, msr_info); if (!ignore_msrs) { vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n", msr, data); return 1; } else { vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data); break; } } return 0; } Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is written to certain MSRs. The behavior is "almost" identical for AMD and Intel (ignoring MSRs that are not implemented in either architecture since they would anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if non-canonical address is written on Intel but not on AMD (which ignores the top 32-bits). Accordingly, this patch injects a #GP on the MSRs which behave identically on Intel and AMD. To eliminate the differences between the architecutres, the value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to canonical value before writing instead of injecting a #GP. Some references from Intel and AMD manuals: According to Intel SDM description of WRMSR instruction #GP is expected on WRMSR "If the source register contains a non-canonical address and ECX specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE, IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP." According to AMD manual instruction manual: LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical form, a general-protection exception (#GP) occurs." IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the base field must be in canonical form or a #GP fault will occur." IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must be in canonical form." This patch fixes CVE-2014-3610. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[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: virtual status_t createPlugin( const uint8_t uuid[16], const void *opaqueData, size_t opaqueSize) { Parcel data, reply; data.writeInterfaceToken(ICrypto::getInterfaceDescriptor()); data.write(uuid, 16); data.writeInt32(opaqueSize); if (opaqueSize > 0) { data.write(opaqueData, opaqueSize); } remote()->transact(CREATE_PLUGIN, data, &reply); return reply.readInt32(); } Commit Message: Fix security vulnerability in ICrypto DO NOT MERGE b/25800375 Change-Id: I03c9395f7c7de4ac5813a1207452aac57aa39484 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: PHPAPI char *php_lookup_class_name(zval *object, zend_uint *nlen) { zval **val; char *retval = NULL; HashTable *object_properties; TSRMLS_FETCH(); object_properties = Z_OBJPROP_P(object); if (zend_hash_find(object_properties, MAGIC_MEMBER, sizeof(MAGIC_MEMBER), (void **) &val) == SUCCESS) { retval = estrndup(Z_STRVAL_PP(val), Z_STRLEN_PP(val)); if (nlen) { *nlen = Z_STRLEN_PP(val); } } return retval; } Commit Message: CWE ID: Target: 1 Example 2: Code: IntPoint FrameView::convertFromContainingView(const IntPoint& parentPoint) const { if (const ScrollView* parentScrollView = toScrollView(parent())) { if (parentScrollView->isFrameView()) { const FrameView* parentView = toFrameView(parentScrollView); RenderPart* renderer = m_frame->ownerRenderer(); if (!renderer) return parentPoint; IntPoint point = parentView->convertToRenderer(*renderer, parentPoint); point.move(-renderer->borderLeft() - renderer->paddingLeft(), -renderer->borderTop() - renderer->paddingTop()); return point; } return Widget::convertFromContainingView(parentPoint); } return parentPoint; } 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 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 PostScript_MetaHandler::ExtractDocInfoDict(IOBuffer &ioBuf) { XMP_Uns8 ch; XMP_IO* fileRef = this->parent->ioRef; XMP_Int64 endofDocInfo=(ioBuf.ptr-ioBuf.data)+ioBuf.filePos; if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; if ( IsWhitespace (*ioBuf.ptr)) { if ( ! ( PostScript_Support::SkipTabsAndSpaces(fileRef, ioBuf))) return false; if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsPdfmarkString.length() ) ) return false; if ( ! CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsPdfmarkString.c_str()), kPSContainsPdfmarkString.length() ) ) return false; while(true) { if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; ch=*ioBuf.ptr; --ioBuf.ptr; if (ch=='/') break;//slash of /DOCINFO } while(true) { if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; if (!IsWhitespace(*ioBuf.ptr)) break; --ioBuf.ptr; } bool findingkey=false; std::string key, value; while(true) { XMP_Uns32 noOfMarks=0; if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; if (*ioBuf.ptr==')') { --ioBuf.ptr; while(true) { if (*ioBuf.ptr=='(') { if(findingkey) { reverse(key.begin(), key.end()); reverse(value.begin(), value.end()); RegisterKeyValue(key,value); } if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; --ioBuf.ptr; findingkey=!findingkey; break; } else { if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; if (findingkey) key+=*ioBuf.ptr; else value+=*ioBuf.ptr; --ioBuf.ptr; } } } else if(*ioBuf.ptr=='[') { break; } else { while(true) { if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; if (findingkey) key+=*ioBuf.ptr; else value+=*ioBuf.ptr; --ioBuf.ptr; if (*ioBuf.ptr=='/') { if(findingkey) { reverse(key.begin(), key.end()); reverse(value.begin(), value.end()); RegisterKeyValue(key,value); } if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; --ioBuf.ptr; findingkey=!findingkey; break; } else if(IsWhitespace(*ioBuf.ptr)) { break; } } } while(true) { if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false; if (!IsWhitespace(*ioBuf.ptr)) break; --ioBuf.ptr; } } fileRef->Rewind(); FillBuffer (fileRef, endofDocInfo, &ioBuf ); return true; }//white space not after DOCINFO return false; } Commit Message: 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: M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode, M_fs_progress_cb_t cb, M_uint32 progress_flags) { char *norm_path_old; char *norm_path_new; char *join_path_old; char *join_path_new; M_fs_dir_entries_t *entries; const M_fs_dir_entry_t *entry; M_fs_info_t *info; M_fs_progress_t *progress = NULL; M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE; M_fs_type_t type; size_t len; size_t i; M_uint64 total_count = 0; M_uint64 total_size = 0; M_uint64 total_size_progress = 0; M_uint64 entry_size; M_fs_error_t res; if (path_old == NULL || *path_old == '\0' || path_new == NULL || *path_new == '\0') { return M_FS_ERROR_INVALID; } /* It's okay if new path doesn't exist. */ res = M_fs_path_norm(&norm_path_new, path_new, M_FS_PATH_NORM_RESDIR, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path_new); return res; } /* If a path is a file and the destination is a directory the file should be copied * into the directory. E.g. /file.txt -> /dir = /dir/file.txt */ if (M_fs_isfileintodir(path_old, path_new, &norm_path_old)) { M_free(norm_path_new); res = M_fs_copy(path_old, norm_path_old, mode, cb, progress_flags); M_free(norm_path_old); return res; } /* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path * existing to rename because any check we perform may not be true when rename is called. */ res = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path_new); M_free(norm_path_old); return res; } progress = M_fs_progress_create(); res = M_fs_info(&info, path_old, (mode & M_FS_FILE_MODE_PRESERVE_PERMS)?M_FS_PATH_INFO_FLAGS_NONE:M_FS_PATH_INFO_FLAGS_BASIC); if (res != M_FS_ERROR_SUCCESS) { M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return res; } type = M_fs_info_get_type(info); /* There is a race condition where the path could not exist but be created between the exists check and calling * rename to move the file but there isn't much we can do in this case. copy will delete and the file so this * situation won't cause an error. */ if (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) { M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return M_FS_ERROR_FILE_EXISTS; } entries = M_fs_dir_entries_create(); /* No need to destroy info because it's now owned by entries and will be destroyed when entries is destroyed. * M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is * stored in the entry. */ M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path_new, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC)); if (type == M_FS_TYPE_DIR) { if (mode & M_FS_FILE_MODE_PRESERVE_PERMS) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_FULL; } else if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC; } /* Get all the files under the dir. */ M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path_old, NULL, filter)); } /* Put all dirs first. We need to ensure the dir(s) exist before we can copy files. */ M_fs_dir_entries_sort(entries, M_FS_DIR_SORT_ISDIR, M_TRUE, M_FS_DIR_SORT_NAME_CASECMP, M_TRUE); len = M_fs_dir_entries_len(entries); if (cb) { total_size = 0; for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size += entry_size; type = M_fs_dir_entry_get_type(entry); /* The total isn't the total number of files but the total number of operations. * Making dirs and symlinks is one operation and copying a file will be split into * multiple operations. Copying uses the M_FS_BUF_SIZE to read and write in * chunks. We determine how many chunks will be needed to read the entire file and * use that for the number of operations for the file. */ if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) { total_count++; } else { total_count += (entry_size + M_FS_BUF_SIZE - 1) / M_FS_BUF_SIZE; } } /* Change the progress total size to reflect all entries. */ if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total(progress, total_size); } /* Change the progress count to reflect the count. */ if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count_total(progress, total_count); } } for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); type = M_fs_dir_entry_get_type(entry); join_path_old = M_fs_path_join(norm_path_old, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); join_path_new = M_fs_path_join(norm_path_new, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size_progress += entry_size; if (cb) { M_fs_progress_set_path(progress, join_path_new); if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current(progress, entry_size); } } /* op */ if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) { if (type == M_FS_TYPE_DIR) { res = M_fs_dir_mkdir(join_path_new, M_FALSE, NULL); } else if (type == M_FS_TYPE_SYMLINK) { res = M_fs_symlink(join_path_new, M_fs_dir_entry_get_resolved_name(entry)); } if (res == M_FS_ERROR_SUCCESS && (mode & M_FS_FILE_MODE_PRESERVE_PERMS)) { res = M_fs_perms_set_perms(M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)), join_path_new); } } else { res = M_fs_copy_file(join_path_old, join_path_new, mode, cb, progress_flags, progress, M_fs_info_get_perms(M_fs_dir_entry_get_info(entry))); } M_free(join_path_old); M_free(join_path_new); /* Call the callback and stop processing if requested. */ if ((type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) && cb) { M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry)); M_fs_progress_set_result(progress, res); if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, total_size_progress); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current_progress(progress, entry_size); } if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1); } if (!cb(progress)) { res = M_FS_ERROR_CANCELED; } } if (res != M_FS_ERROR_SUCCESS) { break; } } /* Delete the file(s) if it could not be copied properly, but only if we are not overwriting. * If we're overwriting then there could be other files in that location (especially if it's a dir). */ if (res != M_FS_ERROR_SUCCESS && !(mode & M_FS_FILE_MODE_OVERWRITE)) { M_fs_delete(path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA); } M_fs_dir_entries_destroy(entries); M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return res; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732 Target: 1 Example 2: Code: v8::Persistent<v8::FunctionTemplate> V8TestInterface::GetRawTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->rawTemplateMap().find(&info); if (result != data->rawTemplateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = createRawTemplate(); data->rawTemplateMap().add(&info, templ); return templ; } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixel_info; register Quantum *q; register ssize_t i, x; register unsigned char *p; SGIInfo iris_info; size_t bytes_per_pixel, quantum; ssize_t count, y, z; unsigned char *pixels; /* 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 SGI raster header. */ iris_info.magic=ReadBlobMSBShort(image); do { /* Verify SGI identifier. */ if (iris_info.magic != 0x01DA) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.storage=(unsigned char) ReadBlobByte(image); switch (iris_info.storage) { case 0x00: image->compression=NoCompression; break; case 0x01: image->compression=RLECompression; break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image); if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.dimension=ReadBlobMSBShort(image); iris_info.columns=ReadBlobMSBShort(image); iris_info.rows=ReadBlobMSBShort(image); iris_info.depth=ReadBlobMSBShort(image); if ((iris_info.depth == 0) || (iris_info.depth > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.minimum_value=ReadBlobMSBLong(image); iris_info.maximum_value=ReadBlobMSBLong(image); iris_info.sans=ReadBlobMSBLong(image); count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); if ((size_t) count != sizeof(iris_info.name)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.name[sizeof(iris_info.name)-1]='\0'; if (*iris_info.name != '\0') (void) SetImageProperty(image,"label",iris_info.name,exception); iris_info.pixel_format=ReadBlobMSBLong(image); if (iris_info.pixel_format != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler); if ((size_t) count != sizeof(iris_info.filler)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=iris_info.columns; image->rows=iris_info.rows; image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.pixel_format == 0) image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel, MAGICKCORE_QUANTUM_DEPTH); if (iris_info.depth < 3) { image->storage_class=PseudoClass; image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate SGI pixels. */ bytes_per_pixel=(size_t) iris_info.bytes_per_pixel; number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows; if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*bytes_per_pixel*number_pixels))) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((int) iris_info.storage != 0x01) { unsigned char *scanline; /* Read standard image format. */ scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns, bytes_per_pixel*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels+bytes_per_pixel*z; for (y=0; y < (ssize_t) iris_info.rows; y++) { count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline); if (EOFBlob(image) != MagickFalse) break; if (bytes_per_pixel == 2) for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[2*x]; *(p+1)=scanline[2*x+1]; p+=8; } else for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[x]; p+=4; } } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); } else { MemoryInfo *packet_info; size_t *runlength; ssize_t offset, *offsets; unsigned char *packets; unsigned int data_order; /* Read runlength-encoded image format. */ offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL* sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets == (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength == (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info == (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) { runlength[i]=ReadBlobMSBLong(image); if (runlength[i] > (4*(size_t) iris_info.columns+10)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Check data order. */ offset=0; data_order=0; for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++) for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++) { if (offsets[y+z*iris_info.rows] < offset) data_order=1; offset=offsets[y+z*iris_info.rows]; } offset=(ssize_t) TellBlob(image); if (data_order == 1) { for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset, SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, (ssize_t) iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); p+=(iris_info.columns*4*bytes_per_pixel); } } } else { MagickOffsetType position; position=TellBlob(image); p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset, SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, (ssize_t) iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } p+=(iris_info.columns*4*bytes_per_pixel); } offset=(ssize_t) SeekBlob(image,position,SEEK_SET); } packet_info=RelinquishVirtualMemory(packet_info); runlength=(size_t *) RelinquishMagickMemory(runlength); offsets=(ssize_t *) RelinquishMagickMemory(offsets); } /* Initialize image structure. */ image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=iris_info.columns; image->rows=iris_info.rows; /* Convert SGI raster image to pixel packets. */ if (image->storage_class == DirectClass) { /* Convert SGI image to DirectClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleShortToQuantum((unsigned short) ((*(p+0) << 8) | (*(p+1)))),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) ((*(p+2) << 8) | (*(p+3)))),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) ((*(p+4) << 8) | (*(p+5)))),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) ((*(p+6) << 8) | (*(p+7)))),q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create grayscale map. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert SGI image to PseudoClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { quantum=(*p << 8); quantum|=(*(p+1)); SetPixelIndex(image,(Quantum) quantum,q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p,q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; iris_info.magic=ReadBlobMSBShort(image); if (iris_info.magic == 0x01DA) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (iris_info.magic == 0x01DA); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/301 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 ptrace_hbptriggered(struct perf_event *bp, int unused, struct perf_sample_data *data, struct pt_regs *regs) { struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp); long num; int i; siginfo_t info; for (i = 0; i < ARM_MAX_HBP_SLOTS; ++i) if (current->thread.debug.hbp[i] == bp) break; num = (i == ARM_MAX_HBP_SLOTS) ? 0 : ptrace_hbp_idx_to_num(i); info.si_signo = SIGTRAP; info.si_errno = (int)num; info.si_code = TRAP_HWBKPT; info.si_addr = (void __user *)(bkpt->trigger); force_sig_info(SIGTRAP, &info, current); } 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: rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s) { tor_assert(lst); tor_assert(s); tor_assert(s->directory); smartlist_add(lst, rend_service_path(s, private_key_fname)); smartlist_add(lst, rend_service_path(s, hostname_fname)); smartlist_add(lst, rend_service_path(s, client_keys_fname)); smartlist_add(lst, rend_service_sos_poison_path(s)); } Commit Message: Fix log-uninitialized-stack bug in rend_service_intro_established. Fixes bug 23490; bugfix on 0.2.7.2-alpha. TROVE-2017-008 CVE-2017-0380 CWE ID: CWE-532 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 AppControllerImpl::OnAppUpdate(const apps::AppUpdate& update) { if (!update.StateIsNull() && !update.NameChanged() && !update.ReadinessChanged()) { return; } if (client_) { client_->OnAppChanged(CreateAppPtr(update)); } } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416 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: SplashError Splash::fillImageMask(SplashImageMaskSource src, void *srcData, int w, int h, SplashCoord *mat, GBool glyphMode) { SplashPipe pipe; GBool rot; SplashCoord xScale, yScale, xShear, yShear, yShear1; int tx, tx2, ty, ty2, scaledWidth, scaledHeight, xSign, ySign; int ulx, uly, llx, lly, urx, ury, lrx, lry; int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1; int xMin, xMax, yMin, yMax; SplashClipResult clipRes, clipRes2; int yp, yq, yt, yStep, lastYStep; int xp, xq, xt, xStep, xSrc; int k1, spanXMin, spanXMax, spanY; SplashColorPtr pixBuf, p; int pixAcc; int x, y, x1, x2, y2; SplashCoord y1; int n, m, i, j; if (debugMode) { printf("fillImageMask: w=%d h=%d mat=[%.2f %.2f %.2f %.2f %.2f %.2f]\n", w, h, (double)mat[0], (double)mat[1], (double)mat[2], (double)mat[3], (double)mat[4], (double)mat[5]); } if (w == 0 && h == 0) return splashErrZeroImage; if (splashAbs(mat[0] * mat[3] - mat[1] * mat[2]) < 0.000001) { return splashErrSingularMatrix; } rot = splashAbs(mat[1]) > splashAbs(mat[0]); if (rot) { xScale = -mat[1]; yScale = mat[2] - (mat[0] * mat[3]) / mat[1]; xShear = -mat[3] / yScale; yShear = -mat[0] / mat[1]; } else { xScale = mat[0]; yScale = mat[3] - (mat[1] * mat[2]) / mat[0]; xShear = mat[2] / yScale; yShear = mat[1] / mat[0]; } if (glyphMode) { if (xScale >= 0) { tx = splashRound(mat[4]); tx2 = splashRound(mat[4] + xScale) - 1; } else { tx = splashRound(mat[4]) - 1; tx2 = splashRound(mat[4] + xScale); } } else { if (xScale >= 0) { tx = splashFloor(mat[4] - 0.01); tx2 = splashFloor(mat[4] + xScale + 0.01); } else { tx = splashFloor(mat[4] + 0.01); tx2 = splashFloor(mat[4] + xScale - 0.01); } } scaledWidth = abs(tx2 - tx) + 1; if (glyphMode) { if (yScale >= 0) { ty = splashRound(mat[5]); ty2 = splashRound(mat[5] + yScale) - 1; } else { ty = splashRound(mat[5]) - 1; ty2 = splashRound(mat[5] + yScale); } } else { if (yScale >= 0) { ty = splashFloor(mat[5] - 0.01); ty2 = splashFloor(mat[5] + yScale + 0.01); } else { ty = splashFloor(mat[5] + 0.01); ty2 = splashFloor(mat[5] + yScale - 0.01); } } scaledHeight = abs(ty2 - ty) + 1; xSign = (xScale < 0) ? -1 : 1; ySign = (yScale < 0) ? -1 : 1; yShear1 = (SplashCoord)xSign * yShear; ulx1 = 0; uly1 = 0; urx1 = xSign * (scaledWidth - 1); ury1 = (int)(yShear * urx1); llx1 = splashRound(xShear * ySign * (scaledHeight - 1)); lly1 = ySign * (scaledHeight - 1) + (int)(yShear * llx1); lrx1 = xSign * (scaledWidth - 1) + splashRound(xShear * ySign * (scaledHeight - 1)); lry1 = ySign * (scaledHeight - 1) + (int)(yShear * lrx1); if (rot) { ulx = tx + uly1; uly = ty - ulx1; urx = tx + ury1; ury = ty - urx1; llx = tx + lly1; lly = ty - llx1; lrx = tx + lry1; lry = ty - lrx1; } else { ulx = tx + ulx1; uly = ty + uly1; urx = tx + urx1; ury = ty + ury1; llx = tx + llx1; lly = ty + lly1; lrx = tx + lrx1; lry = ty + lry1; } xMin = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx : (llx < lrx) ? llx : lrx : (urx < llx) ? (urx < lrx) ? urx : lrx : (llx < lrx) ? llx : lrx; xMax = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx : (llx > lrx) ? llx : lrx : (urx > llx) ? (urx > lrx) ? urx : lrx : (llx > lrx) ? llx : lrx; yMin = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry : (lly < lry) ? lly : lry : (ury < lly) ? (ury < lry) ? ury : lry : (lly < lry) ? lly : lry; yMax = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry : (lly > lry) ? lly : lry : (ury > lly) ? (ury > lry) ? ury : lry : (lly > lry) ? lly : lry; clipRes = state->clip->testRect(xMin, yMin, xMax, yMax); opClipRes = clipRes; yp = h / scaledHeight; yq = h % scaledHeight; xp = w / scaledWidth; xq = w % scaledWidth; pixBuf = (SplashColorPtr)gmalloc((yp + 1) * w); pipeInit(&pipe, 0, 0, state->fillPattern, NULL, state->fillAlpha, gTrue, gFalse); if (vectorAntialias) { drawAAPixelInit(); } yt = 0; lastYStep = 1; for (y = 0; y < scaledHeight; ++y) { yStep = yp; yt += yq; if (yt >= scaledHeight) { yt -= scaledHeight; ++yStep; } n = (yp > 0) ? yStep : lastYStep; if (n > 0) { p = pixBuf; for (i = 0; i < n; ++i) { (*src)(srcData, p); p += w; } } lastYStep = yStep; k1 = splashRound(xShear * ySign * y); if (clipRes != splashClipAllInside && !rot && (int)(yShear * k1) == (int)(yShear * (xSign * (scaledWidth - 1) + k1))) { if (xSign > 0) { spanXMin = tx + k1; spanXMax = spanXMin + (scaledWidth - 1); } else { spanXMax = tx + k1; spanXMin = spanXMax - (scaledWidth - 1); } spanY = ty + ySign * y + (int)(yShear * k1); clipRes2 = state->clip->testSpan(spanXMin, spanXMax, spanY); if (clipRes2 == splashClipAllOutside) { continue; } } else { clipRes2 = clipRes; } xt = 0; xSrc = 0; x1 = k1; y1 = (SplashCoord)ySign * y + yShear * x1; if (yShear1 < 0) { y1 += 0.999; } n = yStep > 0 ? yStep : 1; for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; p = pixBuf + xSrc; pixAcc = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc += *p++; } p += w - m; } if (pixAcc != 0) { pipe.shape = (pixAcc == n * m) ? (SplashCoord)1 : (SplashCoord)pixAcc / (SplashCoord)(n * m); if (vectorAntialias && clipRes2 != splashClipAllInside) { drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } } xSrc += xStep; x1 += xSign; y1 += yShear1; } } gfree(pixBuf); return splashOk; } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo) { struct tcp_sock *tp = tcp_sk(sk); if (frto_undo || tcp_may_undo(tp)) { tcp_undo_cwnd_reduction(sk, true); DBGUNDO(sk, "partial loss"); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSSUNDO); if (frto_undo) NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSPURIOUSRTOS); inet_csk(sk)->icsk_retransmits = 0; if (frto_undo || tcp_is_sack(tp)) tcp_set_ca_state(sk, TCP_CA_Open); return true; } return false; } 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: uint32_t _WM_SetupMidiEvent(struct _mdi *mdi, uint8_t * event_data, uint8_t running_event) { /* Only add standard MIDI and Sysex events in here. Non-standard events need to be handled by calling function to avoid compatibility issues. TODO: Add value limit checks */ uint32_t ret_cnt = 0; uint8_t command = 0; uint8_t channel = 0; uint8_t data_1 = 0; uint8_t data_2 = 0; char *text = NULL; if (event_data[0] >= 0x80) { command = *event_data & 0xf0; channel = *event_data++ & 0x0f; ret_cnt++; } else { command = running_event & 0xf0; channel = running_event & 0x0f; } switch(command) { case 0x80: _SETUP_NOTEOFF: data_1 = *event_data++; data_2 = *event_data++; _WM_midi_setup_noteoff(mdi, channel, data_1, data_2); ret_cnt += 2; break; case 0x90: if (event_data[1] == 0) goto _SETUP_NOTEOFF; /* A velocity of 0 in a note on is actually a note off */ data_1 = *event_data++; data_2 = *event_data++; midi_setup_noteon(mdi, channel, data_1, data_2); ret_cnt += 2; break; case 0xa0: data_1 = *event_data++; data_2 = *event_data++; midi_setup_aftertouch(mdi, channel, data_1, data_2); ret_cnt += 2; break; case 0xb0: data_1 = *event_data++; data_2 = *event_data++; midi_setup_control(mdi, channel, data_1, data_2); ret_cnt += 2; break; case 0xc0: data_1 = *event_data++; midi_setup_patch(mdi, channel, data_1); ret_cnt++; break; case 0xd0: data_1 = *event_data++; midi_setup_channel_pressure(mdi, channel, data_1); ret_cnt++; break; case 0xe0: data_1 = *event_data++; data_2 = *event_data++; midi_setup_pitch(mdi, channel, ((data_2 << 7) | (data_1 & 0x7f))); ret_cnt += 2; break; case 0xf0: if (channel == 0x0f) { /* MIDI Meta Events */ uint32_t tmp_length = 0; if ((event_data[0] == 0x00) && (event_data[1] == 0x02)) { /* Sequence Number We only setting this up here for WM_Event2Midi function */ midi_setup_sequenceno(mdi, ((event_data[2] << 8) + event_data[3])); ret_cnt += 4; } else if (event_data[0] == 0x01) { /* Text Event */ /* Get Length */ event_data++; ret_cnt++; if (*event_data > 0x7f) { do { tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; } while (*event_data > 0x7f); } tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; text = malloc(tmp_length + 1); memcpy(text, event_data, tmp_length); text[tmp_length] = '\0'; midi_setup_text(mdi, text); ret_cnt += tmp_length; } else if (event_data[0] == 0x02) { /* Copyright Event */ /* Get Length */ event_data++; ret_cnt++; if (*event_data > 0x7f) { do { tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; } while (*event_data > 0x7f); } tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; /* Copy copyright info in the getinfo struct */ if (mdi->extra_info.copyright) { mdi->extra_info.copyright = realloc(mdi->extra_info.copyright,(strlen(mdi->extra_info.copyright) + 1 + tmp_length + 1)); memcpy(&mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1], event_data, tmp_length); mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1 + tmp_length] = '\0'; mdi->extra_info.copyright[strlen(mdi->extra_info.copyright)] = '\n'; } else { mdi->extra_info.copyright = malloc(tmp_length + 1); memcpy(mdi->extra_info.copyright, event_data, tmp_length); mdi->extra_info.copyright[tmp_length] = '\0'; } /* NOTE: free'd when events are cleared during closure of mdi */ text = malloc(tmp_length + 1); memcpy(text, event_data, tmp_length); text[tmp_length] = '\0'; midi_setup_copyright(mdi, text); ret_cnt += tmp_length; } else if (event_data[0] == 0x03) { /* Track Name Event */ /* Get Length */ event_data++; ret_cnt++; if (*event_data > 0x7f) { do { tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; } while (*event_data > 0x7f); } tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; text = malloc(tmp_length + 1); memcpy(text, event_data, tmp_length); text[tmp_length] = '\0'; midi_setup_trackname(mdi, text); ret_cnt += tmp_length; } else if (event_data[0] == 0x04) { /* Instrument Name Event */ /* Get Length */ event_data++; ret_cnt++; if (*event_data > 0x7f) { do { tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; } while (*event_data > 0x7f); } tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; text = malloc(tmp_length + 1); memcpy(text, event_data, tmp_length); text[tmp_length] = '\0'; midi_setup_instrumentname(mdi, text); ret_cnt += tmp_length; } else if (event_data[0] == 0x05) { /* Lyric Event */ /* Get Length */ event_data++; ret_cnt++; if (*event_data > 0x7f) { do { tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; } while (*event_data > 0x7f); } tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; text = malloc(tmp_length + 1); memcpy(text, event_data, tmp_length); text[tmp_length] = '\0'; midi_setup_lyric(mdi, text); ret_cnt += tmp_length; } else if (event_data[0] == 0x06) { /* Marker Event */ /* Get Length */ event_data++; ret_cnt++; if (*event_data > 0x7f) { do { tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; } while (*event_data > 0x7f); } tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; text = malloc(tmp_length + 1); memcpy(text, event_data, tmp_length); text[tmp_length] = '\0'; midi_setup_marker(mdi, text); ret_cnt += tmp_length; } else if (event_data[0] == 0x07) { /* Cue Point Event */ /* Get Length */ event_data++; ret_cnt++; if (*event_data > 0x7f) { do { tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; } while (*event_data > 0x7f); } tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; text = malloc(tmp_length + 1); memcpy(text, event_data, tmp_length); text[tmp_length] = '\0'; midi_setup_cuepoint(mdi, text); ret_cnt += tmp_length; } else if ((event_data[0] == 0x20) && (event_data[1] == 0x01)) { /* Channel Prefix We only setting this up here for WM_Event2Midi function */ midi_setup_channelprefix(mdi, event_data[2]); ret_cnt += 3; } else if ((event_data[0] == 0x21) && (event_data[1] == 0x01)) { /* Port Prefix We only setting this up here for WM_Event2Midi function */ midi_setup_portprefix(mdi, event_data[2]); ret_cnt += 3; } else if ((event_data[0] == 0x2F) && (event_data[1] == 0x00)) { /* End of Track Deal with this inside calling function We only setting this up here for _WM_Event2Midi function */ _WM_midi_setup_endoftrack(mdi); ret_cnt += 2; } else if ((event_data[0] == 0x51) && (event_data[1] == 0x03)) { /* Tempo Deal with this inside calling function. We only setting this up here for _WM_Event2Midi function */ _WM_midi_setup_tempo(mdi, ((event_data[2] << 16) + (event_data[3] << 8) + event_data[4])); ret_cnt += 5; } else if ((event_data[0] == 0x54) && (event_data[1] == 0x05)) { /* SMPTE Offset We only setting this up here for WM_Event2Midi function */ midi_setup_smpteoffset(mdi, ((event_data[3] << 24) + (event_data[4] << 16) + (event_data[5] << 8) + event_data[6])); /* Because this has 5 bytes of data we gonna "hack" it a little */ mdi->events[mdi->events_size - 1].event_data.channel = event_data[2]; ret_cnt += 7; } else if ((event_data[0] == 0x58) && (event_data[1] == 0x04)) { /* Time Signature We only setting this up here for WM_Event2Midi function */ midi_setup_timesignature(mdi, ((event_data[2] << 24) + (event_data[3] << 16) + (event_data[4] << 8) + event_data[5])); ret_cnt += 6; } else if ((event_data[0] == 0x59) && (event_data[1] == 0x02)) { /* Key Signature We only setting this up here for WM_Event2Midi function */ midi_setup_keysignature(mdi, ((event_data[2] << 8) + event_data[3])); ret_cnt += 4; } else { /* Unsupported Meta Event */ event_data++; ret_cnt++; if (*event_data > 0x7f) { do { tmp_length = (tmp_length << 7) + (*event_data & 0x7f); event_data++; ret_cnt++; } while (*event_data > 0x7f); } tmp_length = (tmp_length << 7) + (*event_data & 0x7f); ret_cnt++; ret_cnt += tmp_length; } } else if ((channel == 0) || (channel == 7)) { /* Sysex Events */ uint32_t sysex_len = 0; uint8_t *sysex_store = NULL; if (*event_data > 0x7f) { do { sysex_len = (sysex_len << 7) + (*event_data & 0x7F); event_data++; ret_cnt++; } while (*event_data > 0x7f); } sysex_len = (sysex_len << 7) + (*event_data & 0x7F); event_data++; if (!sysex_len) break; ret_cnt++; sysex_store = malloc(sizeof(uint8_t) * sysex_len); memcpy(sysex_store, event_data, sysex_len); if (sysex_store[sysex_len - 1] == 0xF7) { uint8_t rolandsysexid[] = { 0x41, 0x10, 0x42, 0x12 }; if (memcmp(rolandsysexid, sysex_store, 4) == 0) { /* For Roland Sysex Messages */ /* checksum */ uint8_t sysex_cs = 0; uint32_t sysex_ofs = 4; do { sysex_cs += sysex_store[sysex_ofs]; if (sysex_cs > 0x7F) { sysex_cs -= 0x80; } sysex_ofs++; } while (sysex_store[sysex_ofs + 1] != 0xf7); sysex_cs = 128 - sysex_cs; /* is roland sysex message valid */ if (sysex_cs == sysex_store[sysex_ofs]) { /* process roland sysex event */ if (sysex_store[4] == 0x40) { if (((sysex_store[5] & 0xf0) == 0x10) && (sysex_store[6] == 0x15)) { /* Roland Drum Track Setting */ uint8_t sysex_ch = 0x0f & sysex_store[5]; if (sysex_ch == 0x00) { sysex_ch = 0x09; } else if (sysex_ch <= 0x09) { sysex_ch -= 1; } midi_setup_sysex_roland_drum_track(mdi, sysex_ch, sysex_store[7]); } else if ((sysex_store[5] == 0x00) && (sysex_store[6] == 0x7F) && (sysex_store[7] == 0x00)) { /* Roland GS Reset */ midi_setup_sysex_roland_reset(mdi); } } } } else { /* For non-Roland Sysex Messages */ uint8_t gm_reset[] = {0x7e, 0x7f, 0x09, 0x01, 0xf7}; uint8_t yamaha_reset[] = {0x43, 0x10, 0x4c, 0x00, 0x00, 0x7e, 0x00, 0xf7}; if (memcmp(gm_reset, sysex_store, 5) == 0) { /* GM Reset */ midi_setup_sysex_gm_reset(mdi); } else if (memcmp(yamaha_reset,sysex_store,8) == 0) { /* Yamaha Reset */ midi_setup_sysex_yamaha_reset(mdi); } } } free(sysex_store); sysex_store = NULL; /* event_data += sysex_len; */ ret_cnt += sysex_len; } else { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(unrecognized meta type event)", 0); return 0; } break; default: /* Should NEVER get here */ ret_cnt = 0; break; } if (ret_cnt == 0) _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing event)", 0); return ret_cnt; } Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows where to stop reading, and adjust its users properly. Fixes bug #175 (CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.) 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 rsRetVal createSocket(instanceConf_t* info, void** sock) { int rv; sublist* sub; *sock = zsocket_new(s_context, info->type); if (!sock) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zsocket_new failed: %s, for type %d", zmq_strerror(errno),info->type); /* DK: invalid params seems right here */ return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: socket of type %d created successfully\n", info->type) /* Set options *before* the connect/bind. */ if (info->identity) zsocket_set_identity(*sock, info->identity); if (info->sndBuf > -1) zsocket_set_sndbuf(*sock, info->sndBuf); if (info->rcvBuf > -1) zsocket_set_rcvbuf(*sock, info->rcvBuf); if (info->linger > -1) zsocket_set_linger(*sock, info->linger); if (info->backlog > -1) zsocket_set_backlog(*sock, info->backlog); if (info->sndTimeout > -1) zsocket_set_sndtimeo(*sock, info->sndTimeout); if (info->rcvTimeout > -1) zsocket_set_rcvtimeo(*sock, info->rcvTimeout); if (info->maxMsgSize > -1) zsocket_set_maxmsgsize(*sock, info->maxMsgSize); if (info->rate > -1) zsocket_set_rate(*sock, info->rate); if (info->recoveryIVL > -1) zsocket_set_recovery_ivl(*sock, info->recoveryIVL); if (info->multicastHops > -1) zsocket_set_multicast_hops(*sock, info->multicastHops); if (info->reconnectIVL > -1) zsocket_set_reconnect_ivl(*sock, info->reconnectIVL); if (info->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(*sock, info->reconnectIVLMax); if (info->ipv4Only > -1) zsocket_set_ipv4only(*sock, info->ipv4Only); if (info->affinity > -1) zsocket_set_affinity(*sock, info->affinity); if (info->sndHWM > -1 ) zsocket_set_sndhwm(*sock, info->sndHWM); if (info->rcvHWM > -1 ) zsocket_set_rcvhwm(*sock, info->rcvHWM); /* Set subscriptions.*/ if (info->type == ZMQ_SUB) { for(sub = info->subscriptions; sub!=NULL; sub=sub->next) { zsocket_set_subscribe(*sock, sub->subscribe); } } /* Do the bind/connect... */ if (info->action==ACTION_CONNECT) { rv = zsocket_connect(*sock, info->description); if (rv == -1) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zmq_connect using %s failed: %s", info->description, zmq_strerror(errno)); return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: connect for %s successful\n",info->description); } else { rv = zsocket_bind(*sock, info->description); if (rv == -1) { errmsg.LogError(0, RS_RET_INVALID_PARAMS, "zmq_bind using %s failed: %s", info->description, zmq_strerror(errno)); return RS_RET_INVALID_PARAMS; } DBGPRINTF("imzmq3: bind for %s successful\n",info->description); } return RS_RET_OK; } Commit Message: Merge pull request #1565 from Whissi/fix-format-security-issue-in-zmq-modules Fix format security issue in zmq3 modules CWE ID: CWE-134 Target: 1 Example 2: Code: bool kvm_rdpmc(struct kvm_vcpu *vcpu) { u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX); u64 data; int err; err = kvm_pmu_read_pmc(vcpu, ecx, &data); if (err) return err; kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data); kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32); return err; } Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings (cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e) If some vcpus are created before KVM_CREATE_IRQCHIP, then irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading to potential NULL pointer dereferences. Fix by: - ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called - ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP This is somewhat long winded because vcpu->arch.apic is created without kvm->lock held. Based on earlier patch by Michael Ellerman. Signed-off-by: Michael Ellerman <[email protected]> Signed-off-by: Avi Kivity <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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 void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx) { struct blk_align_bitmap *bm = get_bm(hctx, ctx); if (!test_bit(CTX_TO_BIT(hctx, ctx), &bm->word)) set_bit(CTX_TO_BIT(hctx, ctx), &bm->word); } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 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: virtual void SendHandwritingStroke(const HandwritingStroke& stroke) { if (!initialized_successfully_) return; chromeos::SendHandwritingStroke(input_method_status_connection_, stroke); } 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 usb_root_hub_lost_power(struct usb_device *rhdev) { dev_warn(&rhdev->dev, "root hub lost power or was reset\n"); rhdev->reset_resume = 1; } Commit Message: USB: fix invalid memory access in hub_activate() Commit 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") changed the hub_activate() routine to make part of it run in a workqueue. However, the commit failed to take a reference to the usb_hub structure or to lock the hub interface while doing so. As a result, if a hub is plugged in and quickly unplugged before the work routine can run, the routine will try to access memory that has been deallocated. Or, if the hub is unplugged while the routine is running, the memory may be deallocated while it is in active use. This patch fixes the problem by taking a reference to the usb_hub at the start of hub_activate() and releasing it at the end (when the work is finished), and by locking the hub interface while the work routine is running. It also adds a check at the start of the routine to see if the hub has already been disconnected, in which nothing should be done. Signed-off-by: Alan Stern <[email protected]> Reported-by: Alexandru Cornea <[email protected]> Tested-by: Alexandru Cornea <[email protected]> Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") CC: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Document::InheritedBool Document::getDesignMode() const { return m_designMode; } Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document The member is used only in Document, thus no reason to stay in SecurityContext. TEST=none BUG=none [email protected], abarth, haraken, hayato Review URL: https://codereview.chromium.org/27615003 git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: UpdateAtlas::UpdateAtlas(int dimension, ShareableBitmap::Flags flags) : m_flags(flags) { IntSize size = nextPowerOfTwo(IntSize(dimension, dimension)); m_surface = ShareableSurface::create(size, flags, ShareableSurface::SupportsGraphicsSurface); } Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases https://bugs.webkit.org/show_bug.cgi?id=95072 Reviewed by Jocelyn Turcotte. Release graphic buffers that haven't been used for a while in order to save memory. This way we can give back memory to the system when no user interaction happens after a period of time, for example when we are in the background. * Shared/ShareableBitmap.h: * WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp: (WebKit::LayerTreeCoordinator::LayerTreeCoordinator): (WebKit::LayerTreeCoordinator::beginContentUpdate): (WebKit): (WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases): (WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired): * WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h: (LayerTreeCoordinator): * WebProcess/WebPage/UpdateAtlas.cpp: (WebKit::UpdateAtlas::UpdateAtlas): (WebKit::UpdateAtlas::didSwapBuffers): Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer and this way we can track whether this atlas is used with m_areaAllocator. (WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer): * WebProcess/WebPage/UpdateAtlas.h: (WebKit::UpdateAtlas::addTimeInactive): (WebKit::UpdateAtlas::isInactive): (WebKit::UpdateAtlas::isInUse): (UpdateAtlas): git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: vrend_shader_state_reference(struct vrend_shader_selector **ptr, struct vrend_shader_selector *shader) { struct vrend_shader_selector *old_shader = *ptr; if (pipe_reference(&(*ptr)->reference, &shader->reference)) vrend_destroy_shader_selector(old_shader); *ptr = shader; } 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: WORD32 ih264d_start_of_pic(dec_struct_t *ps_dec, WORD32 i4_poc, pocstruct_t *ps_temp_poc, UWORD16 u2_frame_num, dec_pic_params_t *ps_pps) { pocstruct_t *ps_prev_poc = &ps_dec->s_cur_pic_poc; pocstruct_t *ps_cur_poc = ps_temp_poc; pic_buffer_t *pic_buf; ivd_video_decode_op_t * ps_dec_output = (ivd_video_decode_op_t *)ps_dec->pv_dec_out; dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; dec_seq_params_t *ps_seq = ps_pps->ps_sps; UWORD8 u1_bottom_field_flag = ps_cur_slice->u1_bottom_field_flag; UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag; /* high profile related declarations */ high_profile_tools_t s_high_profile; WORD32 ret; H264_MUTEX_LOCK(&ps_dec->process_disp_mutex); ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0]; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1]; ps_prev_poc->u1_bot_field = ps_dec->ps_cur_slice->u1_bottom_field_flag; ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; ps_prev_poc->u2_frame_num = u2_frame_num; ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->i1_next_ctxt_idx = 0; ps_dec->u4_nmb_deblk = 0; if(ps_dec->u4_num_cores == 1) ps_dec->u4_nmb_deblk = 1; if(ps_seq->u1_mb_aff_flag == 1) { ps_dec->u4_nmb_deblk = 0; if(ps_dec->u4_num_cores > 2) ps_dec->u4_num_cores = 2; } ps_dec->u4_use_intrapred_line_copy = 0; if (ps_seq->u1_mb_aff_flag == 0) { ps_dec->u4_use_intrapred_line_copy = 1; } ps_dec->u4_app_disable_deblk_frm = 0; /* If degrade is enabled, set the degrade flags appropriately */ if(ps_dec->i4_degrade_type && ps_dec->i4_degrade_pics) { WORD32 degrade_pic; ps_dec->i4_degrade_pic_cnt++; degrade_pic = 0; /* If degrade is to be done in all frames, then do not check further */ switch(ps_dec->i4_degrade_pics) { case 4: { degrade_pic = 1; break; } case 3: { if(ps_cur_slice->u1_slice_type != I_SLICE) degrade_pic = 1; break; } case 2: { /* If pic count hits non-degrade interval or it is an islice, then do not degrade */ if((ps_cur_slice->u1_slice_type != I_SLICE) && (ps_dec->i4_degrade_pic_cnt != ps_dec->i4_nondegrade_interval)) degrade_pic = 1; break; } case 1: { /* Check if the current picture is non-ref */ if(0 == ps_cur_slice->u1_nal_ref_idc) { degrade_pic = 1; } break; } } if(degrade_pic) { if(ps_dec->i4_degrade_type & 0x2) ps_dec->u4_app_disable_deblk_frm = 1; /* MC degrading is done only for non-ref pictures */ if(0 == ps_cur_slice->u1_nal_ref_idc) { if(ps_dec->i4_degrade_type & 0x4) ps_dec->i4_mv_frac_mask = 0; if(ps_dec->i4_degrade_type & 0x8) ps_dec->i4_mv_frac_mask = 0; } } else ps_dec->i4_degrade_pic_cnt = 0; } { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_dec->u1_sl_typ_5_9 && ((ps_cur_slice->u1_slice_type == I_SLICE) || (ps_cur_slice->u1_slice_type == SI_SLICE))) ps_err->u1_cur_pic_type = PIC_TYPE_I; else ps_err->u1_cur_pic_type = PIC_TYPE_UNKNOWN; if(ps_err->u1_pic_aud_i == PIC_TYPE_I) { ps_err->u1_cur_pic_type = PIC_TYPE_I; ps_err->u1_pic_aud_i = PIC_TYPE_UNKNOWN; } if(ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { if(ps_err->u1_err_flag) ih264d_reset_ref_bufs(ps_dec->ps_dpb_mgr); ps_err->u1_err_flag = ACCEPT_ALL_PICS; } } if(ps_dec->u1_init_dec_flag && ps_dec->s_prev_seq_params.u1_eoseq_pending) { /* Reset the decoder picture buffers */ WORD32 j; for(j = 0; j < MAX_DISP_BUFS_NEW; j++) { ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, ps_dec->au1_pic_buf_id_mv_buf_id_map[j], BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_IO); } /* reset the decoder structure parameters related to buffer handling */ ps_dec->u1_second_field = 0; ps_dec->i4_cur_display_seq = 0; /********************************************************************/ /* indicate in the decoder output i4_status that some frames are being */ /* dropped, so that it resets timestamp and wait for a new sequence */ /********************************************************************/ ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; } ret = ih264d_init_pic(ps_dec, u2_frame_num, i4_poc, ps_pps); if(ret != OK) return ret; ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; ps_dec->ps_nmb_info = ps_dec->ps_frm_mb_info; if(ps_dec->u1_separate_parse) { UWORD16 pic_wd; UWORD16 pic_ht; UWORD32 num_mbs; pic_wd = ps_dec->u2_pic_wd; pic_ht = ps_dec->u2_pic_ht; num_mbs = (pic_wd * pic_ht) >> 8; if(ps_dec->pu1_dec_mb_map) { memset((void *)ps_dec->pu1_dec_mb_map, 0, num_mbs); } if(ps_dec->pu1_recon_mb_map) { memset((void *)ps_dec->pu1_recon_mb_map, 0, num_mbs); } if(ps_dec->pu2_slice_num_map) { memset((void *)ps_dec->pu2_slice_num_map, 0, (num_mbs * sizeof(UWORD16))); } } ps_dec->ps_parse_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); ps_dec->ps_decode_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); ps_dec->ps_computebs_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); /* Initialize all the HP toolsets to zero */ ps_dec->s_high_profile.u1_scaling_present = 0; ps_dec->s_high_profile.u1_transform8x8_present = 0; /* Get Next Free Picture */ if(1 == ps_dec->u4_share_disp_buf) { UWORD32 i; /* Free any buffer that is in the queue to be freed */ for(i = 0; i < MAX_DISP_BUFS_NEW; i++) { if(0 == ps_dec->u4_disp_buf_to_be_freed[i]) continue; ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, i, BUF_MGR_IO); ps_dec->u4_disp_buf_to_be_freed[i] = 0; ps_dec->u4_disp_buf_mapping[i] = 0; } } if(!(u1_field_pic_flag && 0 != ps_dec->u1_top_bottom_decoded)) //ps_dec->u1_second_field)) { pic_buffer_t *ps_cur_pic; WORD32 cur_pic_buf_id, cur_mv_buf_id; col_mv_buf_t *ps_col_mv; while(1) { ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &cur_pic_buf_id); if(ps_cur_pic == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; return ERROR_UNAVAIL_PICBUF_T; } if(0 == ps_dec->u4_disp_buf_mapping[cur_pic_buf_id]) { break; } } ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, &cur_mv_buf_id); if(ps_col_mv == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; return ERROR_UNAVAIL_MVBUF_T; } ps_dec->ps_cur_pic = ps_cur_pic; ps_dec->u1_pic_buf_id = cur_pic_buf_id; ps_cur_pic->u4_ts = ps_dec->u4_ts; ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; if(ps_dec->u1_first_slice_in_stream) { /*make first entry of list0 point to cur pic,so that if first Islice is in error, ref pic struct will have valid entries*/ ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0]; *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][0]) = *ps_cur_pic; } if(!ps_dec->ps_cur_pic) { WORD32 j; H264_DEC_DEBUG_PRINT("------- Display Buffers Reset --------\n"); for(j = 0; j < MAX_DISP_BUFS_NEW; j++) { ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, ps_dec->au1_pic_buf_id_mv_buf_id_map[j], BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_IO); } ps_dec->i4_cur_display_seq = 0; ps_dec->i4_prev_max_display_seq = 0; ps_dec->i4_max_poc = 0; ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &cur_pic_buf_id); if(ps_cur_pic == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; return ERROR_UNAVAIL_PICBUF_T; } ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, &cur_mv_buf_id); if(ps_col_mv == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; return ERROR_UNAVAIL_MVBUF_T; } ps_dec->ps_cur_pic = ps_cur_pic; ps_dec->u1_pic_buf_id = cur_pic_buf_id; ps_cur_pic->u4_ts = ps_dec->u4_ts; ps_dec->apv_buf_id_pic_buf_map[cur_pic_buf_id] = (void *)ps_cur_pic; ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; } ps_dec->ps_cur_pic->u1_picturetype = u1_field_pic_flag; ps_dec->ps_cur_pic->u4_pack_slc_typ = SKIP_NONE; H264_DEC_DEBUG_PRINT("got a buffer\n"); } else { H264_DEC_DEBUG_PRINT("did not get a buffer\n"); } ps_dec->u4_pic_buf_got = 1; ps_dec->ps_cur_pic->i4_poc = i4_poc; ps_dec->ps_cur_pic->i4_frame_num = u2_frame_num; ps_dec->ps_cur_pic->i4_pic_num = u2_frame_num; ps_dec->ps_cur_pic->i4_top_field_order_cnt = ps_pps->i4_top_field_order_cnt; ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = ps_pps->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_avg_poc = ps_pps->i4_avg_poc; ps_dec->ps_cur_pic->u4_time_stamp = ps_dec->u4_pts; ps_dec->s_cur_pic = *(ps_dec->ps_cur_pic); if(u1_field_pic_flag && u1_bottom_field_flag) { WORD32 i4_temp_poc; WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; /* Point to odd lines, since it's bottom field */ ps_dec->s_cur_pic.pu1_buf1 += ps_dec->s_cur_pic.u2_frm_wd_y; ps_dec->s_cur_pic.pu1_buf2 += ps_dec->s_cur_pic.u2_frm_wd_uv; ps_dec->s_cur_pic.pu1_buf3 += ps_dec->s_cur_pic.u2_frm_wd_uv; ps_dec->s_cur_pic.ps_mv += ((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5); ps_dec->s_cur_pic.pu1_col_zero_flag += ((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5); ps_dec->ps_cur_pic->u1_picturetype |= BOT_FLD; i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; i4_temp_poc = MIN(i4_top_field_order_poc, i4_bot_field_order_poc); ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; } ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); ps_dec->ps_cur_pic->u1_picturetype |= (ps_cur_slice->u1_mbaff_frame_flag << 2); ps_dec->ps_cur_mb_row = ps_dec->ps_nbr_mb_row; //[0]; ps_dec->ps_cur_mb_row += 2; ps_dec->ps_top_mb_row = ps_dec->ps_nbr_mb_row; ps_dec->ps_top_mb_row += ((ps_dec->u2_frm_wd_in_mbs + 2) << (1 - ps_dec->ps_cur_sps->u1_frame_mbs_only_flag)); ps_dec->ps_top_mb_row += 2; /* CHANGED CODE */ ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; ps_dec->ps_mv_top = ps_dec->ps_mv_top_p[0]; /* CHANGED CODE */ ps_dec->u1_mv_top_p = 0; ps_dec->u1_mb_idx = 0; /* CHANGED CODE */ ps_dec->ps_mv_left = ps_dec->s_cur_pic.ps_mv; ps_dec->u2_total_mbs_coded = 0; ps_dec->i4_submb_ofst = -(SUB_BLK_SIZE); ps_dec->u4_pred_info_idx = 0; ps_dec->u4_pred_info_pkd_idx = 0; ps_dec->u4_dma_buf_idx = 0; ps_dec->ps_mv = ps_dec->s_cur_pic.ps_mv; ps_dec->ps_mv_bank_cur = ps_dec->s_cur_pic.ps_mv; ps_dec->pu1_col_zero_flag = ps_dec->s_cur_pic.pu1_col_zero_flag; ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->i2_prev_slice_mbx = -1; ps_dec->i2_prev_slice_mby = 0; ps_dec->u2_mv_2mb[0] = 0; ps_dec->u2_mv_2mb[1] = 0; ps_dec->u1_last_pic_not_decoded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->u2_cur_slice_num_dec_thread = 0; ps_dec->u2_cur_slice_num_bs = 0; ps_dec->u4_intra_pred_line_ofst = 0; ps_dec->pu1_cur_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line; ps_dec->pu1_cur_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line; ps_dec->pu1_cur_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line; ps_dec->pu1_cur_y_intra_pred_line_base = ps_dec->pu1_y_intra_pred_line; ps_dec->pu1_cur_u_intra_pred_line_base = ps_dec->pu1_u_intra_pred_line; ps_dec->pu1_cur_v_intra_pred_line_base = ps_dec->pu1_v_intra_pred_line; ps_dec->pu1_prev_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line + (ps_dec->u2_frm_wd_in_mbs * MB_SIZE); ps_dec->pu1_prev_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE * YUV420SP_FACTOR; ps_dec->pu1_prev_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE; ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; /* Initialize The Function Pointer Depending Upon the Entropy and MbAff Flag */ { if(ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_compute_bs = ih264d_compute_bs_mbaff; ps_dec->pf_mvpred = ih264d_mvpred_mbaff; } else { ps_dec->pf_compute_bs = ih264d_compute_bs_non_mbaff; ps_dec->u1_cur_mb_fld_dec_flag = ps_cur_slice->u1_field_pic_flag; } } /* Set up the Parameter for DMA transfer */ { UWORD8 u1_field_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag; UWORD8 u1_mbaff = ps_cur_slice->u1_mbaff_frame_flag; UWORD8 uc_lastmbs = (((ps_dec->u2_pic_wd) >> 4) % (ps_dec->u1_recon_mb_grp >> u1_mbaff)); UWORD16 ui16_lastmbs_widthY = (uc_lastmbs ? (uc_lastmbs << 4) : ((ps_dec->u1_recon_mb_grp >> u1_mbaff) << 4)); UWORD16 ui16_lastmbs_widthUV = uc_lastmbs ? (uc_lastmbs << 3) : ((ps_dec->u1_recon_mb_grp >> u1_mbaff) << 3); ps_dec->s_tran_addrecon.pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; ps_dec->s_tran_addrecon.pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; ps_dec->s_tran_addrecon.pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; ps_dec->s_tran_addrecon.u2_frm_wd_y = ps_dec->u2_frm_wd_y << u1_field_pic_flag; ps_dec->s_tran_addrecon.u2_frm_wd_uv = ps_dec->u2_frm_wd_uv << u1_field_pic_flag; if(u1_field_pic_flag) { ui16_lastmbs_widthY += ps_dec->u2_frm_wd_y; ui16_lastmbs_widthUV += ps_dec->u2_frm_wd_uv; } /* Normal Increment of Pointer */ ps_dec->s_tran_addrecon.u4_inc_y[0] = ((ps_dec->u1_recon_mb_grp << 4) >> u1_mbaff); ps_dec->s_tran_addrecon.u4_inc_uv[0] = ((ps_dec->u1_recon_mb_grp << 4) >> u1_mbaff); /* End of Row Increment */ ps_dec->s_tran_addrecon.u4_inc_y[1] = (ui16_lastmbs_widthY + (PAD_LEN_Y_H << 1) + ps_dec->s_tran_addrecon.u2_frm_wd_y * ((15 << u1_mbaff) + u1_mbaff)); ps_dec->s_tran_addrecon.u4_inc_uv[1] = (ui16_lastmbs_widthUV + (PAD_LEN_UV_H << 2) + ps_dec->s_tran_addrecon.u2_frm_wd_uv * ((15 << u1_mbaff) + u1_mbaff)); /* Assign picture numbers to each frame/field */ /* only once per picture. */ ih264d_assign_pic_num(ps_dec); ps_dec->s_tran_addrecon.u2_mv_top_left_inc = (ps_dec->u1_recon_mb_grp << 2) - 1 - (u1_mbaff << 2); ps_dec->s_tran_addrecon.u2_mv_left_inc = ((ps_dec->u1_recon_mb_grp >> u1_mbaff) - 1) << (4 + u1_mbaff); } /**********************************************************************/ /* High profile related initialization at pictrue level */ /**********************************************************************/ if(ps_seq->u1_profile_idc == HIGH_PROFILE_IDC) { if((ps_seq->i4_seq_scaling_matrix_present_flag) || (ps_pps->i4_pic_scaling_matrix_present_flag)) { ih264d_form_scaling_matrix_picture(ps_seq, ps_pps, ps_dec); ps_dec->s_high_profile.u1_scaling_present = 1; } else { ih264d_form_default_scaling_matrix(ps_dec); } if(ps_pps->i4_transform_8x8_mode_flag) { ps_dec->s_high_profile.u1_transform8x8_present = 1; } } else { ih264d_form_default_scaling_matrix(ps_dec); } /* required while reading the transform_size_8x8 u4_flag */ ps_dec->s_high_profile.u1_direct_8x8_inference_flag = ps_seq->u1_direct_8x8_inference_flag; ps_dec->s_high_profile.s_cavlc_ctxt = ps_dec->s_cavlc_ctxt; ps_dec->i1_recon_in_thread3_flag = 1; ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_addrecon; if(ps_dec->u1_separate_parse) { memcpy(&ps_dec->s_tran_addrecon_parse, &ps_dec->s_tran_addrecon, sizeof(tfr_ctxt_t)); if(ps_dec->u4_num_cores >= 3 && ps_dec->i1_recon_in_thread3_flag) { memcpy(&ps_dec->s_tran_iprecon, &ps_dec->s_tran_addrecon, sizeof(tfr_ctxt_t)); ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_iprecon; } } ih264d_init_deblk_tfr_ctxt(ps_dec,&(ps_dec->s_pad_mgr), &(ps_dec->s_tran_addrecon), ps_dec->u2_frm_wd_in_mbs, 0); ps_dec->ps_cur_deblk_mb = ps_dec->ps_deblk_pic; ps_dec->u4_cur_deblk_mb_num = 0; ps_dec->u4_deblk_mb_x = 0; ps_dec->u4_deblk_mb_y = 0; H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); return OK; } Commit Message: Decoder: Initialize slice parameters before concealing error MBs Also memset ps_dec_op structure to zero. For error input, this ensures dimensions are initialized to zero Bug: 28165661 Change-Id: I66eb2ddc5e02e74b7ff04da5f749443920f37141 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 hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; int err; err = crypto_ahash_export(req, state); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = 1; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; } Commit Message: crypto: algif_hash - Only export and import on sockets with data The hash_accept call fails to work on sockets that have not received any data. For some algorithm implementations it may cause crashes. This patch fixes this by ensuring that we only export and import on sockets that have received data. Cc: [email protected] Reported-by: Harsh Jain <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Tested-by: Stephan Mueller <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: static void webkit_web_view_realize(GtkWidget* widget) { gtk_widget_set_realized(widget, TRUE); GtkAllocation allocation; #if GTK_CHECK_VERSION(2, 18, 0) gtk_widget_get_allocation(widget, &allocation); #else allocation = widget->allocation; #endif GdkWindowAttr attributes; attributes.window_type = GDK_WINDOW_CHILD; attributes.x = allocation.x; attributes.y = allocation.y; attributes.width = allocation.width; attributes.height = allocation.height; attributes.wclass = GDK_INPUT_OUTPUT; attributes.visual = gtk_widget_get_visual(widget); #ifdef GTK_API_VERSION_2 attributes.colormap = gtk_widget_get_colormap(widget); #endif attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_MOTION_MASK | GDK_BUTTON1_MOTION_MASK | GDK_BUTTON2_MOTION_MASK | GDK_BUTTON3_MOTION_MASK; gint attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL; #ifdef GTK_API_VERSION_2 attributes_mask |= GDK_WA_COLORMAP; #endif GdkWindow* window = gdk_window_new(gtk_widget_get_parent_window(widget), &attributes, attributes_mask); gtk_widget_set_window(widget, window); gdk_window_set_user_data(window, widget); #ifdef GTK_API_VERSION_2 #if GTK_CHECK_VERSION(2, 20, 0) gtk_widget_style_attach(widget); #else widget->style = gtk_style_attach(gtk_widget_get_style(widget), window); #endif gtk_style_set_background(gtk_widget_get_style(widget), window, GTK_STATE_NORMAL); #else gtk_style_context_set_background(gtk_widget_get_style_context(widget), window); #endif WebKitWebView* webView = WEBKIT_WEB_VIEW(widget); WebKitWebViewPrivate* priv = webView->priv; gtk_im_context_set_client_window(priv->imContext.get(), window); } Commit Message: 2011-06-02 Joone Hur <[email protected]> Reviewed by Martin Robinson. [GTK] Only load dictionaries if spell check is enabled https://bugs.webkit.org/show_bug.cgi?id=32879 We don't need to call enchant if enable-spell-checking is false. * webkit/webkitwebview.cpp: (webkit_web_view_update_settings): Skip loading dictionaries when enable-spell-checking is false. (webkit_web_view_settings_notify): Ditto. git-svn-id: svn://svn.chromium.org/blink/trunk@87925 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 AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { VLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (base::RandDouble() > upload_rate) { VLOG(1) << "AutofillDownloadManager: Upload request is ignored."; return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses BUG=84693 TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest Review URL: http://codereview.chromium.org/6969090 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 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 struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, u32 features) { struct sk_buff *segs = ERR_PTR(-EINVAL); unsigned int mss; unsigned int unfrag_ip6hlen, unfrag_len; struct frag_hdr *fptr; u8 *mac_start, *prevhdr; u8 nexthdr; u8 frag_hdr_sz = sizeof(struct frag_hdr); int offset; __wsum csum; mss = skb_shinfo(skb)->gso_size; if (unlikely(skb->len <= mss)) goto out; if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) { /* Packet is from an untrusted source, reset gso_segs. */ int type = skb_shinfo(skb)->gso_type; if (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY) || !(type & (SKB_GSO_UDP)))) goto out; skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss); segs = NULL; goto out; } /* Do software UFO. Complete and fill in the UDP checksum as HW cannot * do checksum of UDP packets sent as multiple IP fragments. */ offset = skb_checksum_start_offset(skb); csum = skb_checksum(skb, offset, skb->len- offset, 0); offset += skb->csum_offset; *(__sum16 *)(skb->data + offset) = csum_fold(csum); skb->ip_summed = CHECKSUM_NONE; /* Check if there is enough headroom to insert fragment header. */ if ((skb_mac_header(skb) < skb->head + frag_hdr_sz) && pskb_expand_head(skb, frag_hdr_sz, 0, GFP_ATOMIC)) goto out; /* Find the unfragmentable header and shift it left by frag_hdr_sz * bytes to insert fragment header. */ unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; *prevhdr = NEXTHDR_FRAGMENT; unfrag_len = skb_network_header(skb) - skb_mac_header(skb) + unfrag_ip6hlen; mac_start = skb_mac_header(skb); memmove(mac_start-frag_hdr_sz, mac_start, unfrag_len); skb->mac_header -= frag_hdr_sz; skb->network_header -= frag_hdr_sz; fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen); fptr->nexthdr = nexthdr; fptr->reserved = 0; ipv6_select_ident(fptr); /* Fragment the skb. ipv6 header and the remaining fields of the * fragment header are updated in ipv6_gso_segment() */ segs = skb_segment(skb, features); out: return segs; } Commit Message: ipv6: make fragment identifications less predictable IPv6 fragment identification generation is way beyond what we use for IPv4 : It uses a single generator. Its not scalable and allows DOS attacks. Now inetpeer is IPv6 aware, we can use it to provide a more secure and scalable frag ident generator (per destination, instead of system wide) This patch : 1) defines a new secure_ipv6_id() helper 2) extends inet_getid() to provide 32bit results 3) extends ipv6_select_ident() with a new dest parameter Reported-by: Fernando Gont <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 1 Example 2: Code: PanoramiXRenderCreateRadialGradient(ClientPtr client) { REQUEST(xRenderCreateRadialGradientReq); PanoramiXRes *newPict; int result = Success, j; REQUEST_AT_LEAST_SIZE(xRenderCreateRadialGradientReq); if (!(newPict = (PanoramiXRes *) malloc(sizeof(PanoramiXRes)))) return BadAlloc; newPict->type = XRT_PICTURE; panoramix_setup_ids(newPict, client, stuff->pid); newPict->u.pict.root = FALSE; FOR_NSCREENS_BACKWARD(j) { stuff->pid = newPict->info[j].id; result = (*PanoramiXSaveRenderVector[X_RenderCreateRadialGradient]) (client); if (result != Success) break; } if (result == Success) AddResource(newPict->info[0].id, XRT_PICTURE, newPict); else free(newPict); return result; } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int crypto_rng_reset(struct crypto_rng *tfm, const u8 *seed, unsigned int slen) { u8 *buf = NULL; int err; if (!seed && slen) { buf = kmalloc(slen, GFP_KERNEL); if (!buf) return -ENOMEM; get_random_bytes(buf, slen); seed = buf; } err = tfm->seed(tfm, seed, slen); kfree(buf); return err; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476 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 RunFwdTxfm(int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoCopyTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { TextureManager::TextureInfo* info = GetTextureInfoForTarget(target); if (!info) { SetGLError(GL_INVALID_OPERATION, "glCopyTexSubImage2D", "unknown texture for target"); return; } GLenum type = 0; GLenum format = 0; if (!info->GetLevelType(target, level, &type, &format) || !info->ValidForTexture( target, level, xoffset, yoffset, width, height, format, type)) { SetGLError(GL_INVALID_VALUE, "glCopyTexSubImage2D", "bad dimensions."); return; } GLenum read_format = GetBoundReadFrameBufferInternalFormat(); uint32 channels_exist = GLES2Util::GetChannelsForFormat(read_format); uint32 channels_needed = GLES2Util::GetChannelsForFormat(format); if ((channels_needed & channels_exist) != channels_needed) { SetGLError( GL_INVALID_OPERATION, "glCopyTexSubImage2D", "incompatible format"); return; } if ((channels_needed & (GLES2Util::kDepth | GLES2Util::kStencil)) != 0) { SetGLError( GL_INVALID_OPERATION, "glCopySubImage2D", "can not be used with depth or stencil textures"); return; } if (!CheckBoundFramebuffersValid("glCopyTexSubImage2D")) { return; } ScopedResolvedFrameBufferBinder binder(this, false, true); gfx::Size size = GetBoundReadFrameBufferSize(); GLint copyX = 0; GLint copyY = 0; GLint copyWidth = 0; GLint copyHeight = 0; Clip(x, width, size.width(), &copyX, &copyWidth); Clip(y, height, size.height(), &copyY, &copyHeight); if (!texture_manager()->ClearTextureLevel(this, info, target, level)) { SetGLError(GL_OUT_OF_MEMORY, "glCopyTexSubImage2D", "dimensions too big"); return; } if (copyX != x || copyY != y || copyWidth != width || copyHeight != height) { uint32 pixels_size = 0; if (!GLES2Util::ComputeImageDataSizes( width, height, format, type, unpack_alignment_, &pixels_size, NULL, NULL)) { SetGLError( GL_INVALID_VALUE, "glCopyTexSubImage2D", "dimensions too large"); return; } scoped_array<char> zero(new char[pixels_size]); memset(zero.get(), 0, pixels_size); glTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, zero.get()); } if (copyHeight > 0 && copyWidth > 0) { GLint dx = copyX - x; GLint dy = copyY - y; GLint destX = xoffset + dx; GLint destY = yoffset + dy; glCopyTexSubImage2D(target, level, destX, destY, copyX, copyY, copyWidth, copyHeight); } } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 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 f2fs_sync_fs(struct super_block *sb, int sync) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int err = 0; trace_f2fs_sync_fs(sb, sync); if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING))) return -EAGAIN; if (sync) { struct cp_control cpc; cpc.reason = __get_cp_reason(sbi); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); } f2fs_trace_ios(NULL, 1); return err; } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: u32 h264bsdActivateParamSets(storage_t *pStorage, u32 ppsId, u32 isIdr) { /* Variables */ u32 tmp; u32 flag; /* Code */ ASSERT(pStorage); ASSERT(ppsId < MAX_NUM_PIC_PARAM_SETS); /* check that pps and corresponding sps exist */ if ( (pStorage->pps[ppsId] == NULL) || (pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId] == NULL) ) { return(HANTRO_NOK); } /* check that pps parameters do not violate picture size constraints */ tmp = CheckPps(pStorage->pps[ppsId], pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId]); if (tmp != HANTRO_OK) return(tmp); /* first activation part1 */ if (pStorage->activePpsId == MAX_NUM_PIC_PARAM_SETS) { pStorage->activePpsId = ppsId; pStorage->activePps = pStorage->pps[ppsId]; pStorage->activeSpsId = pStorage->activePps->seqParameterSetId; pStorage->activeSps = pStorage->sps[pStorage->activeSpsId]; pStorage->picSizeInMbs = pStorage->activeSps->picWidthInMbs * pStorage->activeSps->picHeightInMbs; pStorage->currImage->width = pStorage->activeSps->picWidthInMbs; pStorage->currImage->height = pStorage->activeSps->picHeightInMbs; pStorage->pendingActivation = HANTRO_TRUE; } /* first activation part2 */ else if (pStorage->pendingActivation) { pStorage->pendingActivation = HANTRO_FALSE; FREE(pStorage->mb); FREE(pStorage->sliceGroupMap); ALLOCATE(pStorage->mb, pStorage->picSizeInMbs, mbStorage_t); ALLOCATE(pStorage->sliceGroupMap, pStorage->picSizeInMbs, u32); if (pStorage->mb == NULL || pStorage->sliceGroupMap == NULL) return(MEMORY_ALLOCATION_ERROR); H264SwDecMemset(pStorage->mb, 0, pStorage->picSizeInMbs * sizeof(mbStorage_t)); h264bsdInitMbNeighbours(pStorage->mb, pStorage->activeSps->picWidthInMbs, pStorage->picSizeInMbs); /* dpb output reordering disabled if * 1) application set noReordering flag * 2) POC type equal to 2 * 3) num_reorder_frames in vui equal to 0 */ if ( pStorage->noReordering || pStorage->activeSps->picOrderCntType == 2 || (pStorage->activeSps->vuiParametersPresentFlag && pStorage->activeSps->vuiParameters->bitstreamRestrictionFlag && !pStorage->activeSps->vuiParameters->numReorderFrames) ) flag = HANTRO_TRUE; else flag = HANTRO_FALSE; tmp = h264bsdResetDpb(pStorage->dpb, pStorage->activeSps->picWidthInMbs * pStorage->activeSps->picHeightInMbs, pStorage->activeSps->maxDpbSize, pStorage->activeSps->numRefFrames, pStorage->activeSps->maxFrameNum, flag); if (tmp != HANTRO_OK) return(tmp); } else if (ppsId != pStorage->activePpsId) { /* sequence parameter set shall not change but before an IDR picture */ if (pStorage->pps[ppsId]->seqParameterSetId != pStorage->activeSpsId) { DEBUG(("SEQ PARAM SET CHANGING...\n")); if (isIdr) { pStorage->activePpsId = ppsId; pStorage->activePps = pStorage->pps[ppsId]; pStorage->activeSpsId = pStorage->activePps->seqParameterSetId; pStorage->activeSps = pStorage->sps[pStorage->activeSpsId]; pStorage->picSizeInMbs = pStorage->activeSps->picWidthInMbs * pStorage->activeSps->picHeightInMbs; pStorage->currImage->width = pStorage->activeSps->picWidthInMbs; pStorage->currImage->height = pStorage->activeSps->picHeightInMbs; pStorage->pendingActivation = HANTRO_TRUE; } else { DEBUG(("TRYING TO CHANGE SPS IN NON-IDR SLICE\n")); return(HANTRO_NOK); } } else { pStorage->activePpsId = ppsId; pStorage->activePps = pStorage->pps[ppsId]; } } return(HANTRO_OK); } Commit Message: h264bsdActivateParamSets: Prevent multiplication overflow. Report MEMORY_ALLOCATION_ERROR if pStorage->picSizeInMbs would exceed UINT32_MAX bytes. Bug: 28532266 Change-Id: Ia6f11efb18818afcdb5fa2a38a14f2a2d8c8447a CWE ID: CWE-119 Target: 1 Example 2: Code: const BlockEntry* Track::GetEOS() const { return &m_eos; } 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 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 DesktopWindowTreeHostX11::EnableEventListening() { DCHECK_GT(modal_dialog_counter_, 0UL); if (!--modal_dialog_counter_) targeter_for_modal_.reset(); } Commit Message: Fix PIP window being blank after minimize/show DesktopWindowTreeHostX11::SetVisible only made the call into OnNativeWidgetVisibilityChanged when transitioning from shown to minimized and not vice versa. This is because this change https://chromium-review.googlesource.com/c/chromium/src/+/1437263 considered IsVisible to be true when minimized, which made IsVisible always true in this case. This caused layers to be hidden but never shown again. This is a reland of: https://chromium-review.googlesource.com/c/chromium/src/+/1580103 Bug: 949199 Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617 Reviewed-by: Scott Violet <[email protected]> Commit-Queue: enne <[email protected]> Cr-Commit-Position: refs/heads/master@{#654280} CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PluginInfoMessageFilter::PluginsLoaded( const GetPluginInfo_Params& params, IPC::Message* reply_msg, const std::vector<WebPluginInfo>& plugins) { ChromeViewHostMsg_GetPluginInfo_Output output; scoped_ptr<PluginMetadata> plugin_metadata; if (context_.FindEnabledPlugin(params.render_view_id, params.url, params.top_origin_url, params.mime_type, &output.status, &output.plugin, &output.actual_mime_type, &plugin_metadata)) { context_.DecidePluginStatus(params, output.plugin, plugin_metadata.get(), &output.status); } if (plugin_metadata) { output.group_identifier = plugin_metadata->identifier(); output.group_name = plugin_metadata->name(); } context_.GrantAccess(output.status, output.plugin.path); ChromeViewHostMsg_GetPluginInfo::WriteReplyParams(reply_msg, output); Send(reply_msg); } 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 Target: 1 Example 2: Code: ext4_ext_new_meta_block(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_extent *ex, int *err) { ext4_fsblk_t goal, newblock; goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block)); newblock = ext4_new_meta_blocks(handle, inode, goal, NULL, err); return newblock; } Commit Message: ext4: reimplement convert and split_unwritten Reimplement ext4_ext_convert_to_initialized() and ext4_split_unwritten_extents() using ext4_split_extent() Signed-off-by: Yongqiang Yang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Tested-by: Allison Henderson <[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: status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val) { return writeNullableTypedVector(val, &Parcel::writeChar); } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a (cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719) 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 mem_cgroup_usage_unregister_event(struct cgroup *cgrp, struct cftype *cft, struct eventfd_ctx *eventfd) { struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); struct mem_cgroup_thresholds *thresholds; struct mem_cgroup_threshold_ary *new; int type = MEMFILE_TYPE(cft->private); u64 usage; int i, j, size; mutex_lock(&memcg->thresholds_lock); if (type == _MEM) thresholds = &memcg->thresholds; else if (type == _MEMSWAP) thresholds = &memcg->memsw_thresholds; else BUG(); /* * Something went wrong if we trying to unregister a threshold * if we don't have thresholds */ BUG_ON(!thresholds); usage = mem_cgroup_usage(memcg, type == _MEMSWAP); /* Check if a threshold crossed before removing */ __mem_cgroup_threshold(memcg, type == _MEMSWAP); /* Calculate new number of threshold */ size = 0; for (i = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd != eventfd) size++; } new = thresholds->spare; /* Set thresholds array to NULL if we don't have thresholds */ if (!size) { kfree(new); new = NULL; goto swap_buffers; } new->size = size; /* Copy thresholds and find current threshold */ new->current_threshold = -1; for (i = 0, j = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd == eventfd) continue; new->entries[j] = thresholds->primary->entries[i]; if (new->entries[j].threshold < usage) { /* * new->current_threshold will not be used * until rcu_assign_pointer(), so it's safe to increment * it here. */ ++new->current_threshold; } j++; } swap_buffers: /* Swap primary and spare array */ thresholds->spare = thresholds->primary; rcu_assign_pointer(thresholds->primary, new); /* To be sure that nobody uses thresholds */ synchronize_rcu(); mutex_unlock(&memcg->thresholds_lock); } Commit Message: mm: memcg: Correct unregistring of events attached to the same eventfd There is an issue when memcg unregisters events that were attached to the same eventfd: - On the first call mem_cgroup_usage_unregister_event() removes all events attached to a given eventfd, and if there were no events left, thresholds->primary would become NULL; - Since there were several events registered, cgroups core will call mem_cgroup_usage_unregister_event() again, but now kernel will oops, as the function doesn't expect that threshold->primary may be NULL. That's a good question whether mem_cgroup_usage_unregister_event() should actually remove all events in one go, but nowadays it can't do any better as cftype->unregister_event callback doesn't pass any private event-associated cookie. So, let's fix the issue by simply checking for threshold->primary. FWIW, w/o the patch the following oops may be observed: BUG: unable to handle kernel NULL pointer dereference at 0000000000000004 IP: [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0 Pid: 574, comm: kworker/0:2 Not tainted 3.3.0-rc4+ #9 Bochs Bochs RIP: 0010:[<ffffffff810be32c>] [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0 RSP: 0018:ffff88001d0b9d60 EFLAGS: 00010246 Process kworker/0:2 (pid: 574, threadinfo ffff88001d0b8000, task ffff88001de91cc0) Call Trace: [<ffffffff8107092b>] cgroup_event_remove+0x2b/0x60 [<ffffffff8103db94>] process_one_work+0x174/0x450 [<ffffffff8103e413>] worker_thread+0x123/0x2d0 Cc: stable <[email protected]> Signed-off-by: Anton Vorontsov <[email protected]> Acked-by: KAMEZAWA Hiroyuki <[email protected]> Cc: Kirill A. Shutemov <[email protected]> Cc: Michal Hocko <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: Target: 1 Example 2: Code: int ssl3_get_req_cert_type(SSL *s, unsigned char *p) { int ret = 0; const unsigned char *sig; size_t i, siglen; int have_rsa_sign = 0, have_dsa_sign = 0; #ifndef OPENSSL_NO_ECDSA int have_ecdsa_sign = 0; #endif int nostrict = 1; unsigned long alg_k; /* If we have custom certificate types set, use them */ if (s->cert->ctypes) { memcpy(p, s->cert->ctypes, s->cert->ctype_num); return (int)s->cert->ctype_num; } /* get configured sigalgs */ siglen = tls12_get_psigalgs(s, &sig); if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT) nostrict = 0; for (i = 0; i < siglen; i += 2, sig += 2) { switch (sig[1]) { case TLSEXT_signature_rsa: have_rsa_sign = 1; break; case TLSEXT_signature_dsa: have_dsa_sign = 1; break; #ifndef OPENSSL_NO_ECDSA case TLSEXT_signature_ecdsa: have_ecdsa_sign = 1; break; #endif } } alg_k = s->s3->tmp.new_cipher->algorithm_mkey; #ifndef OPENSSL_NO_GOST if (s->version >= TLS1_VERSION) { if (alg_k & SSL_kGOST) { p[ret++] = TLS_CT_GOST94_SIGN; p[ret++] = TLS_CT_GOST01_SIGN; return (ret); } } #endif #ifndef OPENSSL_NO_DH if (alg_k & (SSL_kDHr | SSL_kEDH)) { # ifndef OPENSSL_NO_RSA /* * Since this refers to a certificate signed with an RSA algorithm, * only check for rsa signing in strict mode. */ if (nostrict || have_rsa_sign) p[ret++] = SSL3_CT_RSA_FIXED_DH; # endif # ifndef OPENSSL_NO_DSA if (nostrict || have_dsa_sign) p[ret++] = SSL3_CT_DSS_FIXED_DH; # endif } if ((s->version == SSL3_VERSION) && (alg_k & (SSL_kEDH | SSL_kDHd | SSL_kDHr))) { # ifndef OPENSSL_NO_RSA p[ret++] = SSL3_CT_RSA_EPHEMERAL_DH; # endif # ifndef OPENSSL_NO_DSA p[ret++] = SSL3_CT_DSS_EPHEMERAL_DH; # endif } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_RSA if (have_rsa_sign) p[ret++] = SSL3_CT_RSA_SIGN; #endif #ifndef OPENSSL_NO_DSA if (have_dsa_sign) p[ret++] = SSL3_CT_DSS_SIGN; #endif #ifndef OPENSSL_NO_ECDH if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->version >= TLS1_VERSION)) { if (nostrict || have_rsa_sign) p[ret++] = TLS_CT_RSA_FIXED_ECDH; if (nostrict || have_ecdsa_sign) p[ret++] = TLS_CT_ECDSA_FIXED_ECDH; } #endif #ifndef OPENSSL_NO_ECDSA /* * ECDSA certs can be used with RSA cipher suites as well so we don't * need to check for SSL_kECDH or SSL_kEECDH */ if (s->version >= TLS1_VERSION) { if (have_ecdsa_sign) p[ret++] = TLS_CT_ECDSA_SIGN; } #endif return (ret); } 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: void SetUpEnvironment() { ImageTransportFactory::SetFactory( std::make_unique<TestImageTransportFactory>()); aura_test_helper_.reset(new aura::test::AuraTestHelper()); aura_test_helper_->SetUp( ImageTransportFactory::GetInstance()->GetContextFactory(), ImageTransportFactory::GetInstance()->GetContextFactoryPrivate()); new wm::DefaultActivationClient(aura_test_helper_->root_window()); browser_context_.reset(new TestBrowserContext); process_host_ = new MockRenderProcessHost(browser_context_.get()); process_host_->Init(); sink_ = &process_host_->sink(); int32_t routing_id = process_host_->GetNextRoutingID(); delegates_.push_back(base::WrapUnique(new MockRenderWidgetHostDelegate)); parent_host_ = MockRenderWidgetHostImpl::Create(delegates_.back().get(), process_host_, routing_id); delegates_.back()->set_widget_host(parent_host_); const bool is_mus_browser_plugin_guest = false; parent_view_ = new RenderWidgetHostViewAura( parent_host_, is_guest_view_hack_, is_mus_browser_plugin_guest); parent_view_->InitAsChild(nullptr); aura::client::ParentWindowWithContext(parent_view_->GetNativeView(), aura_test_helper_->root_window(), gfx::Rect()); view_ = CreateView(is_guest_view_hack_); widget_host_ = static_cast<MockRenderWidgetHostImpl*>(view_->host()); view_->event_handler()->set_mouse_wheel_wheel_phase_handler_timeout( base::TimeDelta::FromMilliseconds(100)); base::RunLoop().RunUntilIdle(); } Commit Message: Start rendering timer after first navigation Currently the new content rendering timer in the browser process, which clears an old page's contents 4 seconds after a navigation if the new page doesn't draw in that time, is not set on the first navigation for a top-level frame. This is problematic because content can exist before the first navigation, for instance if it was created by a javascript: URL. This CL removes the code that skips the timer activation on the first navigation. Bug: 844881 Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584 Reviewed-on: https://chromium-review.googlesource.com/1188589 Reviewed-by: Fady Samuel <[email protected]> Reviewed-by: ccameron <[email protected]> Commit-Queue: Ken Buchanan <[email protected]> Cr-Commit-Position: refs/heads/master@{#586913} 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: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 4; fwd_txfm_ref = fdct4x4_ref; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: media_status_t AMediaCodecCryptoInfo_getEncryptedBytes(AMediaCodecCryptoInfo* ci, size_t *dst) { if (!ci) { return AMEDIA_ERROR_INVALID_OBJECT; } if (!dst) { return AMEDIA_ERROR_INVALID_PARAMETER; } memcpy(dst, ci->encryptedbytes, sizeof(size_t) * ci->numsubsamples); return AMEDIA_OK; } Commit Message: Check for overflow of crypto size Bug: 111603051 Test: CTS Change-Id: Ib5b1802b9b35769a25c16e2b977308cf7a810606 (cherry picked from commit d1fd02761236b35a336434367131f71bef7405c9) 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 kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid) { struct kvm_lapic_irq lapic_irq; lapic_irq.shorthand = 0; lapic_irq.dest_mode = 0; lapic_irq.dest_id = apicid; lapic_irq.delivery_mode = APIC_DM_REMRD; kvm_irq_delivery_to_apic(kvm, 0, &lapic_irq, NULL); } 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 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: struct crypto_template *crypto_lookup_template(const char *name) { return try_then_request_module(__crypto_lookup_template(name), "%s", name); } 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 Target: 1 Example 2: Code: krb5_keyblock_key_proc (krb5_context context, krb5_keytype type, krb5_data *salt, krb5_const_pointer keyseed, krb5_keyblock **key) { return krb5_copy_keyblock (context, keyseed, key); } Commit Message: CVE-2019-12098: krb5: always confirm PA-PKINIT-KX for anon PKINIT RFC8062 Section 7 requires verification of the PA-PKINIT-KX key excahnge when anonymous PKINIT is used. Failure to do so can permit an active attacker to become a man-in-the-middle. Introduced by a1ef548600c5bb51cf52a9a9ea12676506ede19f. First tagged release Heimdal 1.4.0. CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N (4.8) Change-Id: I6cc1c0c24985936468af08693839ac6c3edda133 Signed-off-by: Jeffrey Altman <[email protected]> Approved-by: Jeffrey Altman <[email protected]> (cherry picked from commit 38c797e1ae9b9c8f99ae4aa2e73957679031fd2b) CWE ID: CWE-320 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: spnego_gss_acquire_cred_with_password(OM_uint32 *minor_status, const gss_name_t desired_name, const gss_buffer_t password, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { OM_uint32 status, tmpmin; gss_OID_set amechs = GSS_C_NULL_OID_SET; gss_cred_id_t mcred = NULL; spnego_gss_cred_id_t spcred = NULL; dsyslog("Entering spnego_gss_acquire_cred_with_password\n"); if (actual_mechs) *actual_mechs = NULL; if (time_rec) *time_rec = 0; status = get_available_mechs(minor_status, desired_name, cred_usage, GSS_C_NO_CRED_STORE, NULL, &amechs); if (status != GSS_S_COMPLETE) goto cleanup; status = gss_acquire_cred_with_password(minor_status, desired_name, password, time_req, amechs, cred_usage, &mcred, actual_mechs, time_rec); if (status != GSS_S_COMPLETE) goto cleanup; spcred = malloc(sizeof(spnego_gss_cred_id_rec)); if (spcred == NULL) { *minor_status = ENOMEM; status = GSS_S_FAILURE; goto cleanup; } spcred->neg_mechs = GSS_C_NULL_OID_SET; spcred->mcred = mcred; mcred = GSS_C_NO_CREDENTIAL; *output_cred_handle = (gss_cred_id_t)spcred; cleanup: (void) gss_release_oid_set(&tmpmin, &amechs); (void) gss_release_cred(&tmpmin, &mcred); dsyslog("Leaving spnego_gss_acquire_cred_with_password\n"); return (status); } Commit Message: Fix null deref in SPNEGO acceptor [CVE-2014-4344] When processing a continuation token, acc_ctx_cont was dereferencing the initial byte of the token without checking the length. This could result in a null dereference. CVE-2014-4344: In MIT krb5 1.5 and newer, an unauthenticated or partially authenticated remote attacker can cause a NULL dereference and application crash during a SPNEGO negotiation by sending an empty token as the second or later context token from initiator to acceptor. The attacker must provide at least one valid context token in the security context negotiation before sending the empty token. This can be done by an unauthenticated attacker by forcing SPNEGO to renegotiate the underlying mechanism, or by using IAKERB to wrap an unauthenticated AS-REQ as the first token. CVSSv2 Vector: AV:N/AC:L/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: CVE summary, CVSSv2 vector] (cherry picked from commit 524688ce87a15fc75f87efc8c039ba4c7d5c197b) ticket: 7970 version_fixed: 1.12.2 status: resolved CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) { char str[R_FLAG_NAME_SIZE]; RList *entries = r_bin_get_entries (r->bin); RListIter *iter; RBinAddr *entry = NULL; int i = 0; ut64 baddr = r_bin_get_baddr (r->bin); if (IS_MODE_RAD (mode)) { r_cons_printf ("fs symbols\n"); } else if (IS_MODE_JSON (mode)) { r_cons_printf ("["); } else if (IS_MODE_NORMAL (mode)) { if (inifin) { r_cons_printf ("[Constructors]\n"); } else { r_cons_printf ("[Entrypoints]\n"); } } r_list_foreach (entries, iter, entry) { ut64 paddr = entry->paddr; ut64 haddr = UT64_MAX; if (mode != R_CORE_BIN_SET) { if (inifin) { if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) { continue; } } else { if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) { continue; } } } switch (entry->type) { case R_BIN_ENTRY_TYPE_INIT: case R_BIN_ENTRY_TYPE_FINI: case R_BIN_ENTRY_TYPE_PREINIT: if (r->io->va && entry->paddr == entry->vaddr) { RIOMap *map = r_io_map_get (r->io, entry->vaddr); if (map) { paddr = entry->vaddr - map->itv.addr + map->delta; } } } if (entry->haddr) { haddr = entry->haddr; } ut64 at = rva (r->bin, paddr, entry->vaddr, va); const char *type = r_bin_entry_type_string (entry->type); if (!type) { type = "unknown"; } if (IS_MODE_SET (mode)) { r_flag_space_set (r->flags, "symbols"); if (entry->type == R_BIN_ENTRY_TYPE_INIT) { snprintf (str, R_FLAG_NAME_SIZE, "entry%i.init", i); } else if (entry->type == R_BIN_ENTRY_TYPE_FINI) { snprintf (str, R_FLAG_NAME_SIZE, "entry%i.fini", i); } else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) { snprintf (str, R_FLAG_NAME_SIZE, "entry%i.preinit", i); } else { snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i); } r_flag_set (r->flags, str, at, 1); } else if (IS_MODE_SIMPLE (mode)) { r_cons_printf ("0x%08"PFMT64x"\n", at); } else if (IS_MODE_JSON (mode)) { r_cons_printf ("%s{\"vaddr\":%" PFMT64d "," "\"paddr\":%" PFMT64d "," "\"baddr\":%" PFMT64d "," "\"laddr\":%" PFMT64d "," "\"haddr\":%" PFMT64d "," "\"type\":\"%s\"}", iter->p ? "," : "", at, paddr, baddr, laddr, haddr, type); } else if (IS_MODE_RAD (mode)) { char *name = NULL; if (entry->type == R_BIN_ENTRY_TYPE_INIT) { name = r_str_newf ("entry%i.init", i); } else if (entry->type == R_BIN_ENTRY_TYPE_FINI) { name = r_str_newf ("entry%i.fini", i); } else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) { name = r_str_newf ("entry%i.preinit", i); } else { name = r_str_newf ("entry%i", i); } r_cons_printf ("f %s 1 @ 0x%08"PFMT64x"\n", name, at); r_cons_printf ("f %s_haddr 1 @ 0x%08"PFMT64x"\n", name, haddr); r_cons_printf ("s %s\n", name); free (name); } else { r_cons_printf ( "vaddr=0x%08"PFMT64x " paddr=0x%08"PFMT64x " baddr=0x%08"PFMT64x " laddr=0x%08"PFMT64x, at, paddr, baddr, laddr); if (haddr == UT64_MAX) { r_cons_printf ( " haddr=%"PFMT64d " type=%s\n", haddr, type); } else { r_cons_printf ( " haddr=0x%08"PFMT64x " type=%s\n", haddr, type); } } i++; } if (IS_MODE_SET (mode)) { if (entry) { ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va); r_core_seek (r, at, 0); } } else if (IS_MODE_JSON (mode)) { r_cons_printf ("]"); r_cons_newline (); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf ("\n%i entrypoints\n", i); } return true; } Commit Message: Fix #9904 - crash in r2_hoobr_r_read_le32 (over 9000 entrypoints) and read_le oobread (#9923) CWE ID: CWE-125 Target: 1 Example 2: Code: static void dec_mnt_namespaces(struct ucounts *ucounts) { dec_ucount(ucounts, UCOUNT_MNT_NAMESPACES); } 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 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 ShellSurface::CreateShellSurfaceWidget(ui::WindowShowState show_state) { DCHECK(enabled()); DCHECK(!widget_); views::Widget::InitParams params; params.type = views::Widget::InitParams::TYPE_WINDOW; params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET; params.delegate = this; params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.show_state = show_state; params.parent = ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), container_); params.bounds = initial_bounds_; bool activatable = activatable_ && !surface_->GetHitTestBounds().IsEmpty(); params.activatable = activatable ? views::Widget::InitParams::ACTIVATABLE_YES : views::Widget::InitParams::ACTIVATABLE_NO; widget_ = new ShellSurfaceWidget(this); widget_->Init(params); widget_->set_movement_disabled(!initial_bounds_.IsEmpty()); aura::Window* window = widget_->GetNativeWindow(); window->SetName("ExoShellSurface"); window->AddChild(surface_->window()); window->SetEventTargeter(base::WrapUnique(new CustomWindowTargeter)); SetApplicationId(window, &application_id_); SetMainSurface(window, surface_); window->AddObserver(this); ash::wm::GetWindowState(window)->AddObserver(this); if (parent_) wm::AddTransientChild(parent_, window); ash::wm::GetWindowState(window)->set_window_position_managed( ash::wm::ToWindowShowState(ash::wm::WINDOW_STATE_TYPE_AUTO_POSITIONED) == show_state && initial_bounds_.IsEmpty()); views::FocusManager* focus_manager = widget_->GetFocusManager(); for (const auto& entry : kCloseWindowAccelerators) { focus_manager->RegisterAccelerator( ui::Accelerator(entry.keycode, entry.modifiers), ui::AcceleratorManager::kNormalPriority, this); } pending_show_widget_ = true; } Commit Message: exo: Reduce side-effects of dynamic activation code. This code exists for clients that need to managed their own system modal dialogs. Since the addition of the remote surface API we can limit the impact of this to surfaces created for system modal container. BUG=29528396 Review-Url: https://codereview.chromium.org/2084023003 Cr-Commit-Position: refs/heads/master@{#401115} 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: bool mkvparser::Match( IMkvReader* pReader, long long& pos, unsigned long id_, unsigned char*& buf, size_t& buflen) { assert(pReader); assert(pos >= 0); long long total, available; long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; //consume id const long long size_ = ReadUInt(pReader, pos, len); assert(size_ >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; //consume length of size of payload assert((pos + size_) <= available); const long buflen_ = static_cast<long>(size_); buf = new (std::nothrow) unsigned char[buflen_]; assert(buf); //TODO status = pReader->Read(pos, buflen_, buf); assert(status == 0); //TODO buflen = buflen_; pos += size_; //consume size of payload return true; } 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: int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_key *cpu_key, void *data, u32 data_size) { int ret = 0; struct btrfs_path *path; struct extent_buffer *leaf; unsigned long ptr; path = btrfs_alloc_path(); if (!path) return -ENOMEM; ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size); if (!ret) { leaf = path->nodes[0]; ptr = btrfs_item_ptr_offset(leaf, path->slots[0]); write_extent_buffer(leaf, data, ptr, data_size); btrfs_mark_buffer_dirty(leaf); } btrfs_free_path(path); return ret; } Commit Message: Btrfs: make xattr replace operations atomic Replacing a xattr consists of doing a lookup for its existing value, delete the current value from the respective leaf, release the search path and then finally insert the new value. This leaves a time window where readers (getxattr, listxattrs) won't see any value for the xattr. Xattrs are used to store ACLs, so this has security implications. This change also fixes 2 other existing issues which were: *) Deleting the old xattr value without verifying first if the new xattr will fit in the existing leaf item (in case multiple xattrs are packed in the same item due to name hash collision); *) Returning -EEXIST when the flag XATTR_CREATE is given and the xattr doesn't exist but we have have an existing item that packs muliple xattrs with the same name hash as the input xattr. In this case we should return ENOSPC. A test case for xfstests follows soon. Thanks to Alexandre Oliva for reporting the non-atomicity of the xattr replace implementation. Reported-by: Alexandre Oliva <[email protected]> Signed-off-by: Filipe Manana <[email protected]> Signed-off-by: Chris Mason <[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 nf_tables_delsetelem(struct sock *nlsk, struct sk_buff *skb, const struct nlmsghdr *nlh, const struct nlattr * const nla[]) { const struct nlattr *attr; struct nft_set *set; struct nft_ctx ctx; int rem, err = 0; if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL) return -EINVAL; err = nft_ctx_init_from_elemattr(&ctx, skb, nlh, nla, false); if (err < 0) return err; set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET]); if (IS_ERR(set)) return PTR_ERR(set); if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT) return -EBUSY; nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) { err = nft_del_setelem(&ctx, set, attr); if (err < 0) break; set->nelems--; } return err; } Commit Message: netfilter: nf_tables: fix flush ruleset chain dependencies Jumping between chains doesn't mix well with flush ruleset. Rules from a different chain and set elements may still refer to us. [ 353.373791] ------------[ cut here ]------------ [ 353.373845] kernel BUG at net/netfilter/nf_tables_api.c:1159! [ 353.373896] invalid opcode: 0000 [#1] SMP [ 353.373942] Modules linked in: intel_powerclamp uas iwldvm iwlwifi [ 353.374017] CPU: 0 PID: 6445 Comm: 31c3.nft Not tainted 3.18.0 #98 [ 353.374069] Hardware name: LENOVO 5129CTO/5129CTO, BIOS 6QET47WW (1.17 ) 07/14/2010 [...] [ 353.375018] Call Trace: [ 353.375046] [<ffffffff81964c31>] ? nf_tables_commit+0x381/0x540 [ 353.375101] [<ffffffff81949118>] nfnetlink_rcv+0x3d8/0x4b0 [ 353.375150] [<ffffffff81943fc5>] netlink_unicast+0x105/0x1a0 [ 353.375200] [<ffffffff8194438e>] netlink_sendmsg+0x32e/0x790 [ 353.375253] [<ffffffff818f398e>] sock_sendmsg+0x8e/0xc0 [ 353.375300] [<ffffffff818f36b9>] ? move_addr_to_kernel.part.20+0x19/0x70 [ 353.375357] [<ffffffff818f44f9>] ? move_addr_to_kernel+0x19/0x30 [ 353.375410] [<ffffffff819016d2>] ? verify_iovec+0x42/0xd0 [ 353.375459] [<ffffffff818f3e10>] ___sys_sendmsg+0x3f0/0x400 [ 353.375510] [<ffffffff810615fa>] ? native_sched_clock+0x2a/0x90 [ 353.375563] [<ffffffff81176697>] ? acct_account_cputime+0x17/0x20 [ 353.375616] [<ffffffff8110dc78>] ? account_user_time+0x88/0xa0 [ 353.375667] [<ffffffff818f4bbd>] __sys_sendmsg+0x3d/0x80 [ 353.375719] [<ffffffff81b184f4>] ? int_check_syscall_exit_work+0x34/0x3d [ 353.375776] [<ffffffff818f4c0d>] SyS_sendmsg+0xd/0x20 [ 353.375823] [<ffffffff81b1826d>] system_call_fastpath+0x16/0x1b Release objects in this order: rules -> sets -> chains -> tables, to make sure no references to chains are held anymore. Reported-by: Asbjoern Sloth Toennesen <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-19 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 struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt = (struct rt6_info *)dst; if (!dst) goto out; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) { dst_release(dst); dst = NULL; } out: return dst; } Commit Message: ipv6: ip6_sk_dst_check() must not assume ipv6 dst It's possible to use AF_INET6 sockets and to connect to an IPv4 destination. After this, socket dst cache is a pointer to a rtable, not rt6_info. ip6_sk_dst_check() should check the socket dst cache is IPv6, or else various corruptions/crashes can happen. Dave Jones can reproduce immediate crash with trinity -q -l off -n -c sendmsg -c connect With help from Hannes Frederic Sowa Reported-by: Dave Jones <[email protected]> Reported-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: __declspec(dllexport) #endif SQLITE_API int sqlite3_fts5_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return fts5Init(db); } 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: void RenderFrameHostImpl::OnForwardResourceTimingToParent( const ResourceTimingInfo& resource_timing) { if (!is_active()) return; RenderFrameProxyHost* proxy = frame_tree_node()->render_manager()->GetProxyToParent(); if (!proxy) { bool is_current = IsCurrent(); bool has_parent = GetParent(); bool has_parent_ftn = frame_tree_node()->parent(); base::debug::Alias(&is_current); base::debug::Alias(&has_parent); base::debug::Alias(&has_parent_ftn); bool parent_is_current = false; bool parent_is_related_site_instance = false; bool parent_is_top = false; int32_t parent_site_instance_id = -1; DEBUG_ALIAS_FOR_GURL( parent_site_url, has_parent ? GetParent()->GetSiteInstance()->GetSiteURL() : GURL()); if (has_parent) { parent_is_current = GetParent()->IsCurrent(); parent_is_related_site_instance = GetSiteInstance()->IsRelatedSiteInstance( GetParent()->GetSiteInstance()); parent_is_top = !GetParent()->GetParent(); parent_site_instance_id = GetParent()->GetSiteInstance()->GetId(); } base::debug::Alias(&parent_is_current); base::debug::Alias(&parent_is_related_site_instance); base::debug::Alias(&parent_is_top); base::debug::Alias(&parent_site_instance_id); bool parent_ftn_is_related_site_instance = false; int32_t parent_ftn_site_instance_id = -1; DEBUG_ALIAS_FOR_GURL(parent_ftn_site_url, frame_tree_node()->parent() ? frame_tree_node() ->parent() ->render_manager() ->current_frame_host() ->GetSiteInstance() ->GetSiteURL() : GURL()); bool parent_ftn_has_speculative_rfh = false; int32_t parent_ftn_speculative_site_instance_id = -1; if (has_parent_ftn) { parent_is_related_site_instance = GetSiteInstance()->IsRelatedSiteInstance(frame_tree_node() ->parent() ->render_manager() ->current_frame_host() ->GetSiteInstance()); parent_ftn_has_speculative_rfh = frame_tree_node() ->parent() ->render_manager() ->speculative_frame_host(); if (parent_ftn_has_speculative_rfh) { parent_ftn_speculative_site_instance_id = frame_tree_node() ->parent() ->render_manager() ->speculative_frame_host() ->GetSiteInstance() ->GetId(); } } base::debug::Alias(&parent_ftn_is_related_site_instance); base::debug::Alias(&parent_ftn_site_instance_id); base::debug::Alias(&parent_ftn_has_speculative_rfh); base::debug::Alias(&parent_ftn_speculative_site_instance_id); bool is_speculative = frame_tree_node()->render_manager()->speculative_frame_host() == this; int32_t site_instance_id = GetSiteInstance()->GetId(); DEBUG_ALIAS_FOR_GURL(ftn_site_url, GetSiteInstance()->GetSiteURL()); base::debug::Alias(&is_speculative); base::debug::Alias(&site_instance_id); bool ftn_has_speculative_rfh = frame_tree_node()->render_manager()->speculative_frame_host(); int32_t speculative_site_instance_id = -1; if (ftn_has_speculative_rfh) { speculative_site_instance_id = frame_tree_node() ->render_manager() ->speculative_frame_host() ->GetSiteInstance() ->GetId(); } base::debug::Alias(&ftn_has_speculative_rfh); base::debug::Alias(&speculative_site_instance_id); bool rvh_is_active = render_view_host()->is_active(); bool rvh_is_live = render_view_host()->IsRenderViewLive(); base::debug::Alias(&rvh_is_active); base::debug::Alias(&rvh_is_live); bool is_root = frame_tree_node()->frame_tree()->root() == frame_tree_node(); base::debug::Alias(&is_root); bool root_rvh_is_active = frame_tree_node() ->frame_tree() ->root() ->current_frame_host() ->render_view_host() ->is_active(); bool root_rvh_is_live = frame_tree_node() ->frame_tree() ->root() ->current_frame_host() ->render_view_host() ->IsRenderViewLive(); bool root_rvh_is_waiting_for_close_ack = frame_tree_node() ->frame_tree() ->root() ->current_frame_host() ->render_view_host() ->is_waiting_for_close_ack(); base::debug::Alias(&root_rvh_is_active); base::debug::Alias(&root_rvh_is_live); base::debug::Alias(&root_rvh_is_waiting_for_close_ack); bad_message::ReceivedBadMessage(GetProcess(), bad_message::RFH_NO_PROXY_TO_PARENT); return; } proxy->Send(new FrameMsg_ForwardResourceTimingToParent(proxy->GetRoutingID(), resource_timing)); } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nick Carter <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#553867} 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 GestureProviderAura::OnGestureEvent( const GestureEventData& gesture) { GestureEventDetails details = gesture.details; if (gesture.type == ET_GESTURE_TAP) { int tap_count = 1; if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture)) tap_count = 1 + (previous_tap_->details.tap_count() % 3); details.set_tap_count(tap_count); if (!previous_tap_) previous_tap_.reset(new GestureEventData(gesture)); else *previous_tap_ = gesture; previous_tap_->details = details; } else if (gesture.type == ET_GESTURE_TAP_CANCEL) { previous_tap_.reset(); } scoped_ptr<ui::GestureEvent> event( new ui::GestureEvent(gesture.type, gesture.x, gesture.y, last_touch_event_flags_, gesture.time - base::TimeTicks(), details, 1 << gesture.motion_event_id)); if (!handling_event_) { client_->OnGestureEvent(event.get()); } else { pending_gestures_.push_back(event.release()); } } Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: bool Extension::CanExecuteScriptOnPage(const GURL& document_url, const GURL& top_frame_url, int tab_id, const UserScript* script, std::string* error) const { base::AutoLock auto_lock(runtime_data_lock_); GURL store_url(extension_urls::GetWebstoreLaunchURL()); if ((document_url.host() == store_url.host()) && !CanExecuteScriptEverywhere() && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kAllowScriptingGallery)) { if (error) *error = errors::kCannotScriptGallery; return false; } if (document_url.SchemeIs(chrome::kChromeUIScheme) && !CanExecuteScriptEverywhere()) { return false; } if (top_frame_url.SchemeIs(extensions::kExtensionScheme) && top_frame_url.GetOrigin() != GetBaseURLFromExtensionId(id()).GetOrigin() && !CanExecuteScriptEverywhere()) { return false; } if (tab_id >= 0) { scoped_refptr<const PermissionSet> tab_permissions = runtime_data_.GetTabSpecificPermissions(tab_id); if (tab_permissions.get() && tab_permissions->explicit_hosts().MatchesSecurityOrigin(document_url)) { return true; } } if (script) return script->MatchesURL(document_url); if (runtime_data_.GetActivePermissions()->HasExplicitAccessToOrigin( document_url)) { return true; } if (error) { *error = ErrorUtils::FormatErrorMessage(errors::kCannotAccessPage, document_url.spec()); } return false; } Commit Message: Tighten restrictions on hosted apps calling extension APIs Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this). BUG=172369 Review URL: https://chromiumcodereview.appspot.com/12095095 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 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: void BluetoothDeviceChromeOS::AuthorizeService( const dbus::ObjectPath& device_path, const std::string& uuid, const ConfirmationCallback& callback) { callback.Run(CANCELLED); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(interstitial_page); render_manager_.set_interstitial_page(interstitial_page); FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidAttachInterstitialPage()); } Commit Message: Cancel JavaScript dialogs when an interstitial appears. BUG=295695 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/24360011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: static void __init trim_snb_memory(void) { static const __initconst unsigned long bad_pages[] = { 0x20050000, 0x20110000, 0x20130000, 0x20138000, 0x40004000, }; int i; if (!snb_gfx_workaround_needed()) return; printk(KERN_DEBUG "reserving inaccessible SNB gfx pages\n"); /* * Reserve all memory below the 1 MB mark that has not * already been reserved. */ memblock_reserve(0, 1<<20); for (i = 0; i < ARRAY_SIZE(bad_pages); i++) { if (memblock_reserve(bad_pages[i], PAGE_SIZE)) printk(KERN_WARNING "failed to reserve 0x%08lx\n", bad_pages[i]); } } Commit Message: acpi: Disable ACPI table override if securelevel is set From the kernel documentation (initrd_table_override.txt): If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible to override nearly any ACPI table provided by the BIOS with an instrumented, modified one. When securelevel is set, the kernel should disallow any unauthenticated changes to kernel space. ACPI tables contain code invoked by the kernel, so do not allow ACPI tables to be overridden if securelevel is set. Signed-off-by: Linn Crosetto <[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: JSValue jsTestSerializedScriptValueInterfacePorts(ExecState* exec, JSValue slotBase, const Identifier&) { JSTestSerializedScriptValueInterface* castedThis = jsCast<JSTestSerializedScriptValueInterface*>(asObject(slotBase)); UNUSED_PARAM(exec); TestSerializedScriptValueInterface* impl = static_cast<TestSerializedScriptValueInterface*>(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->ports())); 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 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: LosslessTestLarge() : EncoderTest(GET_PARAM(0)), psnr_(kMaxPsnr), nframes_(0), encoding_mode_(GET_PARAM(1)) { } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static void tipc_sk_remove(struct tipc_sock *tsk) { struct sock *sk = &tsk->sk; struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id); if (!rhashtable_remove_fast(&tn->sk_rht, &tsk->node, tsk_rht_params)) { WARN_ON(atomic_read(&sk->sk_refcnt) == 1); __sock_put(sk); } } Commit Message: tipc: check nl sock before parsing nested attributes Make sure the socket for which the user is listing publication exists before parsing the socket netlink attributes. Prior to this patch a call without any socket caused a NULL pointer dereference in tipc_nl_publ_dump(). Tested-and-reported-by: Baozeng Ding <[email protected]> Signed-off-by: Richard Alpe <[email protected]> Acked-by: Jon Maloy <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: NDIS_STATUS ParaNdis_SetMulticastList( PARANDIS_ADAPTER *pContext, PVOID Buffer, ULONG BufferSize, PUINT pBytesRead, PUINT pBytesNeeded) { NDIS_STATUS status; ULONG length = BufferSize; if (length > sizeof(pContext->MulticastData.MulticastList)) { status = NDIS_STATUS_MULTICAST_FULL; *pBytesNeeded = sizeof(pContext->MulticastData.MulticastList); } else if (length % ETH_LENGTH_OF_ADDRESS) { status = NDIS_STATUS_INVALID_LENGTH; *pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS; } else { NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList)); if (length) NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length); pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS; DPrintf(1, ("[%s] New multicast list of %d bytes\n", __FUNCTION__, length)); *pBytesRead = length; status = NDIS_STATUS_SUCCESS; } return status; } Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: spnego_gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { OM_uint32 ret; ret = gss_pseudo_random(minor_status, context, prf_key, prf_in, desired_output_len, prf_out); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18 Target: 1 Example 2: Code: static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate( bool isAMRWB, int32_t bps) { if (isAMRWB) { if (bps <= 6600) { return OMX_AUDIO_AMRBandModeWB0; } else if (bps <= 8850) { return OMX_AUDIO_AMRBandModeWB1; } else if (bps <= 12650) { return OMX_AUDIO_AMRBandModeWB2; } else if (bps <= 14250) { return OMX_AUDIO_AMRBandModeWB3; } else if (bps <= 15850) { return OMX_AUDIO_AMRBandModeWB4; } else if (bps <= 18250) { return OMX_AUDIO_AMRBandModeWB5; } else if (bps <= 19850) { return OMX_AUDIO_AMRBandModeWB6; } else if (bps <= 23050) { return OMX_AUDIO_AMRBandModeWB7; } return OMX_AUDIO_AMRBandModeWB8; } else { // AMRNB if (bps <= 4750) { return OMX_AUDIO_AMRBandModeNB0; } else if (bps <= 5150) { return OMX_AUDIO_AMRBandModeNB1; } else if (bps <= 5900) { return OMX_AUDIO_AMRBandModeNB2; } else if (bps <= 6700) { return OMX_AUDIO_AMRBandModeNB3; } else if (bps <= 7400) { return OMX_AUDIO_AMRBandModeNB4; } else if (bps <= 7950) { return OMX_AUDIO_AMRBandModeNB5; } else if (bps <= 10200) { return OMX_AUDIO_AMRBandModeNB6; } return OMX_AUDIO_AMRBandModeNB7; } } Commit Message: Fix initialization of AAC presentation struct Otherwise the new size checks trip on this. Bug: 27207275 Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766 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: SplashBitmap::~SplashBitmap() { if (rowSize < 0) { gfree(data + (height - 1) * rowSize); } else { gfree(data); } gfree(alpha); } 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: read_packet(int fd, gss_buffer_t buf, int timeout, int first) { int ret; static uint32_t len = 0; static char len_buf[4]; static int len_buf_pos = 0; static char * tmpbuf = 0; static int tmpbuf_pos = 0; if (first) { len_buf_pos = 0; return -2; } if (len_buf_pos < 4) { ret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); return -1; } if (ret == 0) { /* EOF */ /* Failure to read ANY length just means we're done */ if (len_buf_pos == 0) return 0; /* * Otherwise, we got EOF mid-length, and that's * a protocol error. */ LOG(LOG_INFO, ("EOF reading packet len")); return -1; } len_buf_pos += ret; } /* Not done reading the length? */ if (len_buf_pos != 4) return -2; /* We have the complete length */ len = ntohl(*(uint32_t *)len_buf); /* * We make sure recvd length is reasonable, allowing for some * slop in enc overhead, beyond the actual maximum number of * bytes of decrypted payload. */ if (len > GSTD_MAXPACKETCONTENTS + 512) { LOG(LOG_ERR, ("ridiculous length, %ld", len)); return -1; } if (!tmpbuf) { if ((tmpbuf = malloc(len)) == NULL) { LOG(LOG_CRIT, ("malloc failure, %ld bytes", len)); return -1; } } ret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); return -1; } if (ret == 0) { LOG(LOG_ERR, ("EOF while reading packet (len=%d)", len)); return -1; } tmpbuf_pos += ret; if (tmpbuf_pos == len) { buf->length = len; buf->value = tmpbuf; len = len_buf_pos = tmpbuf_pos = 0; tmpbuf = NULL; LOG(LOG_DEBUG, ("read packet of length %d", buf->length)); return 1; } return -2; } Commit Message: knc: fix a couple of memory leaks. One of these can be remotely triggered during the authentication phase which leads to a remote DoS possibility. Pointed out by: Imre Rad <[email protected]> CWE ID: CWE-400 Target: 1 Example 2: Code: bool Extension::InitExtensionID(extensions::Manifest* manifest, const FilePath& path, const std::string& explicit_id, int creation_flags, string16* error) { if (!explicit_id.empty()) { manifest->set_extension_id(explicit_id); return true; } if (manifest->HasKey(keys::kPublicKey)) { std::string public_key; std::string public_key_bytes; std::string extension_id; if (!manifest->GetString(keys::kPublicKey, &public_key) || !ParsePEMKeyBytes(public_key, &public_key_bytes) || !GenerateId(public_key_bytes, &extension_id)) { *error = ASCIIToUTF16(errors::kInvalidKey); return false; } manifest->set_extension_id(extension_id); return true; } if (creation_flags & REQUIRE_KEY) { *error = ASCIIToUTF16(errors::kInvalidKey); return false; } else { std::string extension_id = GenerateIdForPath(path); if (extension_id.empty()) { NOTREACHED() << "Could not create ID from path."; return false; } manifest->set_extension_id(extension_id); return true; } } Commit Message: Tighten restrictions on hosted apps calling extension APIs Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this). BUG=172369 Review URL: https://chromiumcodereview.appspot.com/12095095 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 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: error::Error GLES2DecoderPassthroughImpl::DoSetDrawRectangleCHROMIUM( GLint x, GLint y, GLint width, GLint height) { GLint current_framebuffer = 0; api()->glGetIntegervFn(GL_FRAMEBUFFER_BINDING, &current_framebuffer); if (current_framebuffer != 0) { InsertError(GL_INVALID_OPERATION, "framebuffer must not be bound."); return error::kNoError; } if (!surface_->SupportsDCLayers()) { InsertError(GL_INVALID_OPERATION, "surface doesn't support SetDrawRectangle."); return error::kNoError; } gfx::Rect rect(x, y, width, height); if (!surface_->SetDrawRectangle(rect)) { InsertError(GL_INVALID_OPERATION, "SetDrawRectangle failed on surface"); return error::kNoError; } ApplySurfaceDrawOffset(); 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 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: xmlParseMisc(xmlParserCtxtPtr ctxt) { while (((RAW == '<') && (NXT(1) == '?')) || (CMP4(CUR_PTR, '<', '!', '-', '-')) || IS_BLANK_CH(CUR)) { if ((RAW == '<') && (NXT(1) == '?')) { xmlParsePI(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else xmlParseComment(ctxt); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void do_sys_vm86(struct kernel_vm86_struct *info, struct task_struct *tsk) { struct tss_struct *tss; /* * make sure the vm86() system call doesn't try to do anything silly */ info->regs.pt.ds = 0; info->regs.pt.es = 0; info->regs.pt.fs = 0; #ifndef CONFIG_X86_32_LAZY_GS info->regs.pt.gs = 0; #endif /* * The flags register is also special: we cannot trust that the user * has set it up safely, so this makes sure interrupt etc flags are * inherited from protected mode. */ VEFLAGS = info->regs.pt.flags; info->regs.pt.flags &= SAFE_MASK; info->regs.pt.flags |= info->regs32->flags & ~SAFE_MASK; info->regs.pt.flags |= X86_VM_MASK; switch (info->cpu_type) { case CPU_286: tsk->thread.v86mask = 0; break; case CPU_386: tsk->thread.v86mask = X86_EFLAGS_NT | X86_EFLAGS_IOPL; break; case CPU_486: tsk->thread.v86mask = X86_EFLAGS_AC | X86_EFLAGS_NT | X86_EFLAGS_IOPL; break; default: tsk->thread.v86mask = X86_EFLAGS_ID | X86_EFLAGS_AC | X86_EFLAGS_NT | X86_EFLAGS_IOPL; break; } /* * Save old state, set default return value (%ax) to 0 (VM86_SIGNAL) */ info->regs32->ax = VM86_SIGNAL; tsk->thread.saved_sp0 = tsk->thread.sp0; tsk->thread.saved_fs = info->regs32->fs; tsk->thread.saved_gs = get_user_gs(info->regs32); tss = &per_cpu(init_tss, get_cpu()); tsk->thread.sp0 = (unsigned long) &info->VM86_TSS_ESP0; if (cpu_has_sep) tsk->thread.sysenter_cs = 0; load_sp0(tss, &tsk->thread); put_cpu(); tsk->thread.screen_bitmap = info->screen_bitmap; if (info->flags & VM86_SCREEN_BITMAP) mark_screen_rdonly(tsk->mm); /*call __audit_syscall_exit since we do not exit via the normal paths */ #ifdef CONFIG_AUDITSYSCALL if (unlikely(current->audit_context)) __audit_syscall_exit(1, 0); #endif __asm__ __volatile__( "movl %0,%%esp\n\t" "movl %1,%%ebp\n\t" #ifdef CONFIG_X86_32_LAZY_GS "mov %2, %%gs\n\t" #endif "jmp resume_userspace" : /* no outputs */ :"r" (&info->regs), "r" (task_thread_info(tsk)), "r" (0)); /* we never return here */ } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BpMemoryHeap::BpMemoryHeap(const sp<IBinder>& impl) : BpInterface<IMemoryHeap>(impl), mHeapId(-1), mBase(MAP_FAILED), mSize(0), mFlags(0), mOffset(0), mRealHeap(false) { } Commit Message: Sanity check IMemory access versus underlying mmap Bug 26877992 Change-Id: Ibbf4b1061e4675e4e96bc944a865b53eaf6984fe CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static noinline int hiddev_ioctl_usage(struct hiddev *hiddev, unsigned int cmd, void __user *user_arg) { struct hid_device *hid = hiddev->hid; struct hiddev_report_info rinfo; struct hiddev_usage_ref_multi *uref_multi = NULL; struct hiddev_usage_ref *uref; struct hid_report *report; struct hid_field *field; int i; uref_multi = kmalloc(sizeof(struct hiddev_usage_ref_multi), GFP_KERNEL); if (!uref_multi) return -ENOMEM; uref = &uref_multi->uref; if (cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) { if (copy_from_user(uref_multi, user_arg, sizeof(*uref_multi))) goto fault; } else { if (copy_from_user(uref, user_arg, sizeof(*uref))) goto fault; } switch (cmd) { case HIDIOCGUCODE: rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (uref->usage_index >= field->maxusage) goto inval; uref->usage_code = field->usage[uref->usage_index].hid; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; default: if (cmd != HIDIOCGUSAGE && cmd != HIDIOCGUSAGES && uref->report_type == HID_REPORT_TYPE_INPUT) goto inval; if (uref->report_id == HID_REPORT_ID_UNKNOWN) { field = hiddev_lookup_usage(hid, uref); if (field == NULL) goto inval; } else { rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (cmd == HIDIOCGCOLLECTIONINDEX) { if (uref->usage_index >= field->maxusage) goto inval; } else if (uref->usage_index >= field->report_count) goto inval; else if ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) && (uref_multi->num_values > HID_MAX_MULTI_USAGES || uref->usage_index + uref_multi->num_values > field->report_count)) goto inval; } switch (cmd) { case HIDIOCGUSAGE: uref->value = field->value[uref->usage_index]; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; case HIDIOCSUSAGE: field->value[uref->usage_index] = uref->value; goto goodreturn; case HIDIOCGCOLLECTIONINDEX: i = field->usage[uref->usage_index].collection_index; kfree(uref_multi); return i; case HIDIOCGUSAGES: for (i = 0; i < uref_multi->num_values; i++) uref_multi->values[i] = field->value[uref->usage_index + i]; if (copy_to_user(user_arg, uref_multi, sizeof(*uref_multi))) goto fault; goto goodreturn; case HIDIOCSUSAGES: for (i = 0; i < uref_multi->num_values; i++) field->value[uref->usage_index + i] = uref_multi->values[i]; goto goodreturn; } goodreturn: kfree(uref_multi); return 0; fault: kfree(uref_multi); return -EFAULT; inval: kfree(uref_multi); return -EINVAL; } } Commit Message: HID: hiddev: validate num_values for HIDIOCGUSAGES, HIDIOCSUSAGES commands This patch validates the num_values parameter from userland during the HIDIOCGUSAGES and HIDIOCSUSAGES commands. Previously, if the report id was set to HID_REPORT_ID_UNKNOWN, we would fail to validate the num_values parameter leading to a heap overflow. Cc: [email protected] Signed-off-by: Scott Bauer <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: mrb_mod_cvar_set(mrb_state *mrb, mrb_value mod) { mrb_value value; mrb_sym id; mrb_get_args(mrb, "no", &id, &value); check_cv_name_sym(mrb, id); mrb_cv_set(mrb, mod, id, value); return value; } Commit Message: `mrb_class_real()` did not work for `BasicObject`; fix #4037 CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static v8::Handle<v8::Value> uniformMatrixHelper(const v8::Arguments& args, int matrixSize) { if (args.Length() != 3) return V8Proxy::throwNotEnoughArgumentsError(); WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } bool ok = false; WebGLUniformLocation* location = toWebGLUniformLocation(args[0], ok); bool transpose = args[1]->BooleanValue(); if (V8Float32Array::HasInstance(args[2])) { Float32Array* array = V8Float32Array::toNative(args[2]->ToObject()); ASSERT(array != NULL); ExceptionCode ec = 0; switch (matrixSize) { case 2: context->uniformMatrix2fv(location, transpose, array, ec); break; case 3: context->uniformMatrix3fv(location, transpose, array, ec); break; case 4: context->uniformMatrix4fv(location, transpose, array, ec); break; default: ASSERT_NOT_REACHED(); break; } if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } if (args[2].IsEmpty() || !args[2]->IsArray()) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } v8::Handle<v8::Array> array = v8::Local<v8::Array>::Cast(args[2]); uint32_t len = array->Length(); float* data = jsArrayToFloatArray(array, len); if (!data) { V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate()); return notHandledByInterceptor(); } ExceptionCode ec = 0; switch (matrixSize) { case 2: context->uniformMatrix2fv(location, transpose, data, len, ec); break; case 3: context->uniformMatrix3fv(location, transpose, data, len, ec); break; case 4: context->uniformMatrix4fv(location, transpose, data, len, ec); break; default: ASSERT_NOT_REACHED(); break; } fastFree(data); if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } 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 MemBackendImpl::EvictIfNeeded() { if (current_size_ <= max_size_) return; int target_size = std::max(0, max_size_ - kDefaultEvictionSize); base::LinkNode<MemEntryImpl>* entry = lru_list_.head(); while (current_size_ > target_size && entry != lru_list_.end()) { MemEntryImpl* to_doom = entry->value(); entry = entry->next(); if (!to_doom->InUse()) to_doom->Doom(); } } Commit Message: [MemCache] Fix bug while iterating LRU list in eviction It was possible to reanalyze a previously doomed entry. Bug: 827492 Change-Id: I5d34d2ae87c96e0d2099e926e6eb2c1b30b01d63 Reviewed-on: https://chromium-review.googlesource.com/987919 Commit-Queue: Josh Karlin <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Cr-Commit-Position: refs/heads/master@{#547236} CWE ID: CWE-416 Target: 1 Example 2: Code: int snd_timer_global_register(struct snd_timer *timer) { struct snd_device dev; memset(&dev, 0, sizeof(dev)); dev.device_data = timer; return snd_timer_dev_register(&dev); } Commit Message: ALSA: timer: Fix leak in events via snd_timer_user_tinterrupt The stack object “r1” has a total size of 32 bytes. Its field “event” and “val” both contain 4 bytes padding. These 8 bytes padding bytes are sent to user without being initialized. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> 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: void SettingLevelBubble::HideBubble() { hide_timer_.Stop(); if (view_) { view_->GetWidget()->Close(); view_ = NULL; } } 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: static ps_sd *ps_sd_new(ps_mm *data, const char *key) { php_uint32 hv, slot; ps_sd *sd; int keylen; keylen = strlen(key); sd = mm_malloc(data->mm, sizeof(ps_sd) + keylen); if (!sd) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mm_malloc failed, avail %d, err %s", mm_available(data->mm), mm_error()); return NULL; } hv = ps_sd_hash(key, keylen); slot = hv & data->hash_max; sd->ctime = 0; sd->hv = hv; sd->data = NULL; sd->alloclen = sd->datalen = 0; memcpy(sd->key, key, keylen + 1); sd->next = data->hash[slot]; data->hash[slot] = sd; data->hash_cnt++; if (!sd->next) { if (data->hash_cnt >= data->hash_max) { hash_split(data); } } ps_mm_debug(("inserting %s(%p) into slot %d\n", key, sd, slot)); return sd; } Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { struct preempt_notifier *notifier; hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) notifier->ops->sched_out(notifier, next); } Commit Message: sched: Fix information leak in sys_sched_getattr() We're copying the on-stack structure to userspace, but forgot to give the right number of bytes to copy. This allows the calling process to obtain up to PAGE_SIZE bytes from the stack (and possibly adjacent kernel memory). This fix copies only as much as we actually have on the stack (attr->size defaults to the size of the struct) and leaves the rest of the userspace-provided buffer untouched. Found using kmemcheck + trinity. Fixes: d50dde5a10f30 ("sched: Add new scheduler syscalls to support an extended scheduling parameters ABI") Cc: Dario Faggioli <[email protected]> Cc: Juri Lelli <[email protected]> Cc: Ingo Molnar <[email protected]> Signed-off-by: Vegard Nossum <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Thomas Gleixner <[email protected]> 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: static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) { char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL; PGconn *pgsql; smart_str str = {0}; zval **args[5]; int i, connect_type = 0; PGresult *pg_result; if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5 || zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) { WRONG_PARAM_COUNT; } smart_str_appends(&str, "pgsql"); for (i = 0; i < ZEND_NUM_ARGS(); i++) { /* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections * can re-use this connection. Bug #39979 */ if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE_PP(args[i]) == IS_LONG) { if (Z_LVAL_PP(args[1]) == PGSQL_CONNECT_FORCE_NEW) { continue; } else if (Z_LVAL_PP(args[1]) & PGSQL_CONNECT_FORCE_NEW) { smart_str_append_long(&str, Z_LVAL_PP(args[1]) ^ PGSQL_CONNECT_FORCE_NEW); } } convert_to_string_ex(args[i]); smart_str_appendc(&str, '_'); smart_str_appendl(&str, Z_STRVAL_PP(args[i]), Z_STRLEN_PP(args[i])); } smart_str_0(&str); if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */ connstring = Z_STRVAL_PP(args[0]); } else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */ connstring = Z_STRVAL_PP(args[0]); convert_to_long_ex(args[1]); connect_type = Z_LVAL_PP(args[1]); } else { host = Z_STRVAL_PP(args[0]); port = Z_STRVAL_PP(args[1]); dbname = Z_STRVAL_PP(args[ZEND_NUM_ARGS()-1]); switch (ZEND_NUM_ARGS()) { case 5: tty = Z_STRVAL_PP(args[3]); /* fall through */ case 4: options = Z_STRVAL_PP(args[2]); break; } } if (persistent && PGG(allow_persistent)) { zend_rsrc_list_entry *le; /* try to find if we already have this link in our persistent list */ if (zend_hash_find(&EG(persistent_list), str.c, str.len+1, (void **) &le)==FAILURE) { /* we don't */ zend_rsrc_list_entry new_le; if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links)); goto err; } if (PGG(max_persistent)!=-1 && PGG(num_persistent)>=PGG(max_persistent)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open persistent links (%ld)", PGG(num_persistent)); goto err; } /* create the link */ if (connstring) { pgsql=PQconnectdb(connstring); } else { pgsql=PQsetdb(host,port,options,tty,dbname); } if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) { PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql) if (pgsql) { PQfinish(pgsql); } goto err; } /* hash it up */ Z_TYPE(new_le) = le_plink; new_le.ptr = pgsql; if (zend_hash_update(&EG(persistent_list), str.c, str.len+1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) { goto err; } PGG(num_links)++; PGG(num_persistent)++; } else { /* we do */ if (Z_TYPE_P(le) != le_plink) { RETURN_FALSE; } /* ensure that the link did not die */ if (PGG(auto_reset_persistent) & 1) { /* need to send & get something from backend to make sure we catch CONNECTION_BAD everytime */ PGresult *pg_result; pg_result = PQexec(le->ptr, "select 1"); PQclear(pg_result); } if (PQstatus(le->ptr)==CONNECTION_BAD) { /* the link died */ if (le->ptr == NULL) { if (connstring) { le->ptr=PQconnectdb(connstring); } else { le->ptr=PQsetdb(host,port,options,tty,dbname); } } else { PQreset(le->ptr); } if (le->ptr==NULL || PQstatus(le->ptr)==CONNECTION_BAD) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"PostgreSQL link lost, unable to reconnect"); zend_hash_del(&EG(persistent_list),str.c,str.len+1); goto err; } } pgsql = (PGconn *) le->ptr; #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) { #else if (atof(PG_VERSION) >= 7.2) { #endif pg_result = PQexec(pgsql, "RESET ALL;"); PQclear(pg_result); } } ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink); } else { /* Non persistent connection */ zend_rsrc_list_entry *index_ptr,new_index_ptr; /* first we check the hash for the hashed_details key. if it exists, * it should point us to the right offset where the actual pgsql link sits. * if it doesn't, open a new pgsql link, add it to the resource list, * and add a pointer to it with hashed_details as the key. */ if (!(connect_type & PGSQL_CONNECT_FORCE_NEW) && zend_hash_find(&EG(regular_list),str.c,str.len+1,(void **) &index_ptr)==SUCCESS) { int type; ulong link; void *ptr; if (Z_TYPE_P(index_ptr) != le_index_ptr) { RETURN_FALSE; } link = (ulong) index_ptr->ptr; ptr = zend_list_find(link,&type); /* check if the link is still there */ if (ptr && (type==le_link || type==le_plink)) { Z_LVAL_P(return_value) = link; zend_list_addref(link); php_pgsql_set_default_link(link TSRMLS_CC); Z_TYPE_P(return_value) = IS_RESOURCE; goto cleanup; } else { zend_hash_del(&EG(regular_list),str.c,str.len+1); } } if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links)); goto err; } if (connstring) { pgsql = PQconnectdb(connstring); } else { pgsql = PQsetdb(host,port,options,tty,dbname); } if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) { PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql); if (pgsql) { PQfinish(pgsql); } goto err; } /* add it to the list */ ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link); /* add it to the hash */ new_index_ptr.ptr = (void *) Z_LVAL_P(return_value); Z_TYPE(new_index_ptr) = le_index_ptr; if (zend_hash_update(&EG(regular_list),str.c,str.len+1,(void *) &new_index_ptr, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) { goto err; } PGG(num_links)++; } /* set notice processer */ if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) { PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)Z_RESVAL_P(return_value)); } php_pgsql_set_default_link(Z_LVAL_P(return_value) TSRMLS_CC); cleanup: smart_str_free(&str); return; err: smart_str_free(&str); RETURN_FALSE; } /* }}} */ #if 0 /* {{{ php_pgsql_get_default_link */ static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS) { if (PGG(default_link)==-1) { /* no link opened yet, implicitly open one */ ht = 0; php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0); } return PGG(default_link); } /* }}} */ #endif /* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database) Open a PostgreSQL connection */ PHP_FUNCTION(pg_connect) { php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0); } /* }}} */ /* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database) Open a persistent PostgreSQL connection */ PHP_FUNCTION(pg_pconnect) { php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1); } /* }}} */ /* {{{ proto bool pg_close([resource connection]) Close a PostgreSQL connection */ PHP_FUNCTION(pg_close) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (id==-1) { /* explicit resource number */ zend_list_delete(Z_RESVAL_P(pgsql_link)); } if (id!=-1 || (pgsql_link && Z_RESVAL_P(pgsql_link)==PGG(default_link))) { zend_list_delete(PGG(default_link)); PGG(default_link) = -1; } RETURN_TRUE; } /* }}} */ #define PHP_PG_DBNAME 1 #define PHP_PG_ERROR_MESSAGE 2 #define PHP_PG_OPTIONS 3 #define PHP_PG_PORT 4 #define PHP_PG_TTY 5 #define PHP_PG_HOST 6 #define PHP_PG_VERSION 7 /* {{{ php_pgsql_get_link_info */ static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; char *msgbuf; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); switch(entry_type) { case PHP_PG_DBNAME: Z_STRVAL_P(return_value) = PQdb(pgsql); break; case PHP_PG_ERROR_MESSAGE: RETURN_STRING(PQErrorMessageTrim(pgsql, &msgbuf), 0); return; case PHP_PG_OPTIONS: Z_STRVAL_P(return_value) = PQoptions(pgsql); break; case PHP_PG_PORT: Z_STRVAL_P(return_value) = PQport(pgsql); break; case PHP_PG_TTY: Z_STRVAL_P(return_value) = PQtty(pgsql); break; case PHP_PG_HOST: Z_STRVAL_P(return_value) = PQhost(pgsql); break; case PHP_PG_VERSION: array_init(return_value); add_assoc_string(return_value, "client", PG_VERSION, 1); #if HAVE_PQPROTOCOLVERSION add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql)); #if HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3) { add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version"), 1); } #endif #endif return; default: RETURN_FALSE; } if (Z_STRVAL_P(return_value)) { Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value)); } else { Z_STRLEN_P(return_value) = 0; Z_STRVAL_P(return_value) = (char *) estrdup(""); } Z_TYPE_P(return_value) = IS_STRING; } /* }}} */ /* {{{ proto string pg_dbname([resource connection]) Get the database name */ PHP_FUNCTION(pg_dbname) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME); } /* }}} */ /* {{{ proto string pg_last_error([resource connection]) Get the error message string */ PHP_FUNCTION(pg_last_error) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE); } /* }}} */ /* {{{ proto string pg_options([resource connection]) Get the options associated with the connection */ PHP_FUNCTION(pg_options) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS); } /* }}} */ /* {{{ proto int pg_port([resource connection]) Return the port number associated with the connection */ PHP_FUNCTION(pg_port) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT); } /* }}} */ /* {{{ proto string pg_tty([resource connection]) Return the tty name associated with the connection */ PHP_FUNCTION(pg_tty) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY); } /* }}} */ /* {{{ proto string pg_host([resource connection]) Returns the host name associated with the connection */ PHP_FUNCTION(pg_host) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST); } /* }}} */ /* {{{ proto array pg_version([resource connection]) Returns an array with client, protocol and server version (when available) */ PHP_FUNCTION(pg_version) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION); } /* }}} */ #if HAVE_PQPARAMETERSTATUS /* {{{ proto string|false pg_parameter_status([resource connection,] string param_name) Returns the value of a server parameter */ PHP_FUNCTION(pg_parameter_status) { zval *pgsql_link; int id; PGconn *pgsql; char *param; int len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &param, &len) == SUCCESS) { id = -1; } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &param, &len) == SUCCESS) { pgsql_link = NULL; id = PGG(default_link); } else { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); param = (char*)PQparameterStatus(pgsql, param); if (param) { RETURN_STRING(param, 1); } else { RETURN_FALSE; } } /* }}} */ #endif /* {{{ proto bool pg_ping([resource connection]) Ping database. If connection is bad, try to reconnect. */ PHP_FUNCTION(pg_ping) { zval *pgsql_link; int id; PGconn *pgsql; PGresult *res; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == SUCCESS) { id = -1; } else { pgsql_link = NULL; id = PGG(default_link); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); /* ping connection */ res = PQexec(pgsql, "SELECT 1;"); PQclear(res); /* check status. */ if (PQstatus(pgsql) == CONNECTION_OK) RETURN_TRUE; /* reset connection if it's broken */ PQreset(pgsql); if (PQstatus(pgsql) == CONNECTION_OK) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto resource pg_query([resource connection,] string query) Execute a query */ PHP_FUNCTION(pg_query) { zval *pgsql_link = NULL; char *query; int id = -1, query_len, argc = ZEND_NUM_ARGS(); int leftover = 0; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &query, &query_len) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } pgsql_result = PQexec(pgsql, query); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexec(pgsql, query); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED /* {{{ _php_pgsql_free_params */ static void _php_pgsql_free_params(char **params, int num_params) { if (num_params > 0) { int i; for (i = 0; i < num_params; i++) { if (params[i]) { efree(params[i]); } } efree(params); } } /* }}} */ #endif #if HAVE_PQEXECPARAMS /* {{{ proto resource pg_query_params([resource connection,] string query, array params) Execute a query */ PHP_FUNCTION(pg_query_params) { zval *pgsql_link = NULL; zval *pv_param_arr, **tmp; char *query; int query_len, id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; int num_params = 0; char **params = NULL; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "sa", &query, &query_len, &pv_param_arr) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr)); num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); for(i = 0; i < num_params; i++) { if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter"); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } if (Z_TYPE_PP(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val = **tmp; zval_copy_ctor(&tmp_val); convert_to_string(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter"); zval_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_dtor(&tmp_val); } zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr)); } } pgsql_result = PQexecParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexecParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } _php_pgsql_free_params(params, num_params); switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #if HAVE_PQPREPARE /* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query) Prepare a query for future execution */ PHP_FUNCTION(pg_prepare) { zval *pgsql_link = NULL; char *query, *stmtname; int query_len, stmtname_len, id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "ss", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #if HAVE_PQEXECPREPARED /* {{{ proto resource pg_execute([resource connection,] string stmtname, array params) Execute a prepared query */ PHP_FUNCTION(pg_execute) { zval *pgsql_link = NULL; zval *pv_param_arr, **tmp; char *stmtname; int stmtname_len, id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; int num_params = 0; char **params = NULL; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "sa/", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rsa/", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr)); num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); for(i = 0; i < num_params; i++) { if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter"); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } if (Z_TYPE_PP(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val = **tmp; zval_copy_ctor(&tmp_val); convert_to_string(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter"); zval_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_dtor(&tmp_val); } zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr)); } } pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } _php_pgsql_free_params(params, num_params); switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #define PHP_PG_NUM_ROWS 1 #define PHP_PG_NUM_FIELDS 2 #define PHP_PG_CMD_TUPLES 3 /* {{{ php_pgsql_get_result_info */ static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; switch (entry_type) { case PHP_PG_NUM_ROWS: Z_LVAL_P(return_value) = PQntuples(pgsql_result); break; case PHP_PG_NUM_FIELDS: Z_LVAL_P(return_value) = PQnfields(pgsql_result); break; case PHP_PG_CMD_TUPLES: #if HAVE_PQCMDTUPLES Z_LVAL_P(return_value) = atoi(PQcmdTuples(pgsql_result)); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not supported under this build"); Z_LVAL_P(return_value) = 0; #endif break; default: RETURN_FALSE; } Z_TYPE_P(return_value) = IS_LONG; } /* }}} */ /* {{{ proto int pg_num_rows(resource result) Return the number of rows in the result */ PHP_FUNCTION(pg_num_rows) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS); } /* }}} */ /* {{{ proto int pg_num_fields(resource result) Return the number of fields in the result */ PHP_FUNCTION(pg_num_fields) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS); } /* }}} */ #if HAVE_PQCMDTUPLES /* {{{ proto int pg_affected_rows(resource result) Returns the number of affected tuples */ PHP_FUNCTION(pg_affected_rows) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES); } /* }}} */ #endif /* {{{ proto string pg_last_notice(resource connection) Returns the last notice set by the backend */ PHP_FUNCTION(pg_last_notice) { zval *pgsql_link; PGconn *pg_link; int id = -1; php_pgsql_notice **notice; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) { return; } /* Just to check if user passed valid resoruce */ ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (zend_hash_index_find(&PGG(notices), Z_RESVAL_P(pgsql_link), (void **)&notice) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL((*notice)->message, (*notice)->len, 1); } /* }}} */ /* {{{ get_field_name */ static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list TSRMLS_DC) { PGresult *result; smart_str str = {0}; zend_rsrc_list_entry *field_type; char *ret=NULL; /* try to lookup the type in the resource list */ smart_str_appends(&str, "pgsql_oid_"); smart_str_append_unsigned(&str, oid); smart_str_0(&str); if (zend_hash_find(list,str.c,str.len+1,(void **) &field_type)==SUCCESS) { ret = estrdup((char *)field_type->ptr); } else { /* hash all oid's */ int i,num_rows; int oid_offset,name_offset; char *tmp_oid, *end_ptr, *tmp_name; zend_rsrc_list_entry new_oid_entry; if ((result = PQexec(pgsql,"select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) { if (result) { PQclear(result); } smart_str_free(&str); return STR_EMPTY_ALLOC(); } num_rows = PQntuples(result); oid_offset = PQfnumber(result,"oid"); name_offset = PQfnumber(result,"typname"); for (i=0; i<num_rows; i++) { if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) { continue; } str.len = 0; smart_str_appends(&str, "pgsql_oid_"); smart_str_appends(&str, tmp_oid); smart_str_0(&str); if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) { continue; } Z_TYPE(new_oid_entry) = le_string; new_oid_entry.ptr = estrdup(tmp_name); zend_hash_update(list,str.c,str.len+1,(void *) &new_oid_entry, sizeof(zend_rsrc_list_entry), NULL); if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) { ret = estrdup(tmp_name); } } PQclear(result); } smart_str_free(&str); return ret; } /* }}} */ #ifdef HAVE_PQFTABLE /* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only]) Returns the name of the table field belongs to, or table's oid if oid_only is true */ PHP_FUNCTION(pg_field_table) { zval *result; pgsql_result_handle *pg_result; long fnum = -1; zend_bool return_oid = 0; Oid oid; smart_str hash_key = {0}; char *table_name; zend_rsrc_list_entry *field_table; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|b", &result, &fnum, &return_oid) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); if (fnum < 0 || fnum >= PQnfields(pg_result->result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified"); RETURN_FALSE; } oid = PQftable(pg_result->result, fnum); if (InvalidOid == oid) { RETURN_FALSE; } if (return_oid) { #if UINT_MAX > LONG_MAX /* Oid is unsigned int, we don't need this code, where LONG is wider */ if (oid > LONG_MAX) { smart_str oidstr = {0}; smart_str_append_unsigned(&oidstr, oid); smart_str_0(&oidstr); RETURN_STRINGL(oidstr.c, oidstr.len, 0); } else #endif RETURN_LONG((long)oid); } /* try to lookup the table name in the resource list */ smart_str_appends(&hash_key, "pgsql_table_oid_"); smart_str_append_unsigned(&hash_key, oid); smart_str_0(&hash_key); if (zend_hash_find(&EG(regular_list), hash_key.c, hash_key.len+1, (void **) &field_table) == SUCCESS) { smart_str_free(&hash_key); RETURN_STRING((char *)field_table->ptr, 1); } else { /* Not found, lookup by querying PostgreSQL system tables */ PGresult *tmp_res; smart_str querystr = {0}; zend_rsrc_list_entry new_field_table; smart_str_appends(&querystr, "select relname from pg_class where oid="); smart_str_append_unsigned(&querystr, oid); smart_str_0(&querystr); if ((tmp_res = PQexec(pg_result->conn, querystr.c)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) { if (tmp_res) { PQclear(tmp_res); } smart_str_free(&querystr); smart_str_free(&hash_key); RETURN_FALSE; } smart_str_free(&querystr); if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) { PQclear(tmp_res); smart_str_free(&hash_key); RETURN_FALSE; } Z_TYPE(new_field_table) = le_string; new_field_table.ptr = estrdup(table_name); zend_hash_update(&EG(regular_list), hash_key.c, hash_key.len+1, (void *) &new_field_table, sizeof(zend_rsrc_list_entry), NULL); smart_str_free(&hash_key); PQclear(tmp_res); RETURN_STRING(table_name, 1); } } /* }}} */ #endif #define PHP_PG_FIELD_NAME 1 #define PHP_PG_FIELD_SIZE 2 #define PHP_PG_FIELD_TYPE 3 #define PHP_PG_FIELD_TYPE_OID 4 /* {{{ php_pgsql_get_field_info */ static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result; long field; PGresult *pgsql_result; pgsql_result_handle *pg_result; Oid oid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &field) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; if (field < 0 || field >= PQnfields(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified"); RETURN_FALSE; } switch (entry_type) { case PHP_PG_FIELD_NAME: Z_STRVAL_P(return_value) = PQfname(pgsql_result, field); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_STRVAL_P(return_value) = estrndup(Z_STRVAL_P(return_value),Z_STRLEN_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; break; case PHP_PG_FIELD_SIZE: Z_LVAL_P(return_value) = PQfsize(pgsql_result, field); Z_TYPE_P(return_value) = IS_LONG; break; case PHP_PG_FIELD_TYPE: Z_STRVAL_P(return_value) = get_field_name(pg_result->conn, PQftype(pgsql_result, field), &EG(regular_list) TSRMLS_CC); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; break; case PHP_PG_FIELD_TYPE_OID: oid = PQftype(pgsql_result, field); #if UINT_MAX > LONG_MAX if (oid > LONG_MAX) { smart_str s = {0}; smart_str_append_unsigned(&s, oid); smart_str_0(&s); Z_STRVAL_P(return_value) = s.c; Z_STRLEN_P(return_value) = s.len; Z_TYPE_P(return_value) = IS_STRING; } else #endif { Z_LVAL_P(return_value) = (long)oid; Z_TYPE_P(return_value) = IS_LONG; } break; default: RETURN_FALSE; } } /* }}} */ /* {{{ proto string pg_field_name(resource result, int field_number) Returns the name of the field */ PHP_FUNCTION(pg_field_name) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME); } /* }}} */ /* {{{ proto int pg_field_size(resource result, int field_number) Returns the internal size of the field */ PHP_FUNCTION(pg_field_size) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE); } /* }}} */ /* {{{ proto string pg_field_type(resource result, int field_number) Returns the type name for the given field */ PHP_FUNCTION(pg_field_type) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE); } /* }}} */ /* {{{ proto string pg_field_type_oid(resource result, int field_number) Returns the type oid for the given field */ PHP_FUNCTION(pg_field_type_oid) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID); } /* }}} */ /* {{{ proto int pg_field_num(resource result, string field_name) Returns the field number of the named field */ PHP_FUNCTION(pg_field_num) { zval *result; char *field; int field_len; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &result, &field, &field_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; Z_LVAL_P(return_value) = PQfnumber(pgsql_result, field); Z_TYPE_P(return_value) = IS_LONG; } /* }}} */ /* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name) Returns values from a result identifier */ PHP_FUNCTION(pg_fetch_result) { zval *result, **field=NULL; long row; PGresult *pgsql_result; pgsql_result_handle *pg_result; int field_offset, pgsql_row, argc = ZEND_NUM_ARGS(); if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) { return; } } else { if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) { return; } } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; if (argc == 2) { if (pg_result->row < 0) { pg_result->row = 0; } pgsql_row = pg_result->row; if (pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } } else { pgsql_row = row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld", row, Z_LVAL_P(result)); RETURN_FALSE; } } switch(Z_TYPE_PP(field)) { case IS_STRING: field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field)); break; default: convert_to_long_ex(field); field_offset = Z_LVAL_PP(field); break; } if (field_offset<0 || field_offset>=PQnfields(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified"); RETURN_FALSE; } if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) { Z_TYPE_P(return_value) = IS_NULL; } else { char *value = PQgetvalue(pgsql_result, pgsql_row, field_offset); int value_len = PQgetlength(pgsql_result, pgsql_row, field_offset); ZVAL_STRINGL(return_value, value, value_len, 1); } } /* }}} */ /* {{{ void php_pgsql_fetch_hash */ static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, long result_type, int into_object) { zval *result, *zrow = NULL; PGresult *pgsql_result; pgsql_result_handle *pg_result; int i, num_fields, pgsql_row, use_row; long row = -1; char *field_name; zval *ctor_params = NULL; zend_class_entry *ce = NULL; if (into_object) { char *class_name = NULL; int class_name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!sz", &result, &zrow, &class_name, &class_name_len, &ctor_params) == FAILURE) { return; } if (!class_name) { ce = zend_standard_class_def; } else { ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC); } if (!ce) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find class '%s'", class_name); return; } result_type = PGSQL_ASSOC; } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!l", &result, &zrow, &result_type) == FAILURE) { return; } } if (zrow == NULL) { row = -1; } else { convert_to_long(zrow); row = Z_LVAL_P(zrow); if (row < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The row parameter must be greater or equal to zero"); RETURN_FALSE; } } use_row = ZEND_NUM_ARGS() > 1 && row != -1; if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type"); RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; if (use_row) { pgsql_row = row; pg_result->row = pgsql_row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld", row, Z_LVAL_P(result)); RETURN_FALSE; } } else { /* If 2nd param is NULL, use internal row counter to access next row */ pgsql_row = pg_result->row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } pg_result->row++; } array_init(return_value); for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) { if (PQgetisnull(pgsql_result, pgsql_row, i)) { if (result_type & PGSQL_NUM) { add_index_null(return_value, i); } if (result_type & PGSQL_ASSOC) { field_name = PQfname(pgsql_result, i); add_assoc_null(return_value, field_name); } } else { char *element = PQgetvalue(pgsql_result, pgsql_row, i); if (element) { char *data; int data_len; int should_copy=0; const uint element_len = strlen(element); data = safe_estrndup(element, element_len); data_len = element_len; if (result_type & PGSQL_NUM) { add_index_stringl(return_value, i, data, data_len, should_copy); should_copy=1; } if (result_type & PGSQL_ASSOC) { field_name = PQfname(pgsql_result, i); add_assoc_stringl(return_value, field_name, data, data_len, should_copy); } } } } if (into_object) { zval dataset = *return_value; zend_fcall_info fci; zend_fcall_info_cache fcc; zval *retval_ptr; object_and_properties_init(return_value, ce, NULL); zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC); if (ce->constructor) { fci.size = sizeof(fci); fci.function_table = &ce->function_table; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = return_value; fci.retval_ptr_ptr = &retval_ptr; if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) { if (Z_TYPE_P(ctor_params) == IS_ARRAY) { HashTable *ht = Z_ARRVAL_P(ctor_params); Bucket *p; fci.param_count = 0; fci.params = safe_emalloc(sizeof(zval***), ht->nNumOfElements, 0); p = ht->pListHead; while (p != NULL) { fci.params[fci.param_count++] = (zval**)p->pData; p = p->pListNext; } } else { /* Two problems why we throw exceptions here: PHP is typeless * and hence passing one argument that's not an array could be * by mistake and the other way round is possible, too. The * single value is an array. Also we'd have to make that one * argument passed by reference. */ zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Parameter ctor_params must be an array", 0 TSRMLS_CC); return; } } else { fci.param_count = 0; fci.params = NULL; } fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(return_value); fcc.object_ptr = return_value; if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Could not execute %s::%s()", ce->name, ce->constructor->common.function_name); } else { if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } if (fci.params) { efree(fci.params); } } else if (ctor_params) { zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Class %s does not have a constructor hence you cannot use ctor_params", ce->name); } } } /* }}} */ /* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]]) Get a row as an enumerated array */ PHP_FUNCTION(pg_fetch_row) { php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0); } /* }}} */ /* {{{ proto array pg_fetch_assoc(resource result [, int row]) Fetch a row as an assoc array */ PHP_FUNCTION(pg_fetch_assoc) { /* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when there is 3rd parameter */ if (ZEND_NUM_ARGS() > 2) WRONG_PARAM_COUNT; php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0); } /* }}} */ /* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]]) Fetch a row as an array */ PHP_FUNCTION(pg_fetch_array) { php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0); } /* }}} */ /* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]]) Fetch a row as an object */ PHP_FUNCTION(pg_fetch_object) { /* pg_fetch_object() allowed result_type used to be. 3rd parameter must be allowed for compatibility */ php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1); } /* }}} */ /* {{{ proto array pg_fetch_all(resource result) Fetch all rows into array */ PHP_FUNCTION(pg_fetch_all) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; array_init(return_value); if (php_pgsql_result2array(pgsql_result, return_value TSRMLS_CC) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ /* {{{ proto array pg_fetch_all_columns(resource result [, int column_number]) Fetch all rows into array */ PHP_FUNCTION(pg_fetch_all_columns) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; unsigned long colno=0; int pg_numrows, pg_row; size_t num_fields; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &result, &colno) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; num_fields = PQnfields(pgsql_result); if (colno >= num_fields || colno < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid column number '%ld'", colno); RETURN_FALSE; } array_init(return_value); if ((pg_numrows = PQntuples(pgsql_result)) <= 0) { return; } for (pg_row = 0; pg_row < pg_numrows; pg_row++) { if (PQgetisnull(pgsql_result, pg_row, colno)) { add_next_index_null(return_value); } else { add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, colno), 1); } } } /* }}} */ /* {{{ proto bool pg_result_seek(resource result, int offset) Set internal row offset */ PHP_FUNCTION(pg_result_seek) { zval *result; long row; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &row) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); if (row < 0 || row >= PQntuples(pg_result->result)) { RETURN_FALSE; } /* seek to offset */ pg_result->row = row; RETURN_TRUE; } /* }}} */ #define PHP_PG_DATA_LENGTH 1 #define PHP_PG_DATA_ISNULL 2 /* {{{ php_pgsql_data_info */ static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result, **field; long row; PGresult *pgsql_result; pgsql_result_handle *pg_result; int field_offset, pgsql_row, argc = ZEND_NUM_ARGS(); if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) { return; } } else { if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) { return; } } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; if (argc == 2) { if (pg_result->row < 0) { pg_result->row = 0; } pgsql_row = pg_result->row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } } else { pgsql_row = row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld", row, Z_LVAL_P(result)); RETURN_FALSE; } } switch(Z_TYPE_PP(field)) { case IS_STRING: convert_to_string_ex(field); field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field)); break; default: convert_to_long_ex(field); field_offset = Z_LVAL_PP(field); break; } if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified"); RETURN_FALSE; } switch (entry_type) { case PHP_PG_DATA_LENGTH: Z_LVAL_P(return_value) = PQgetlength(pgsql_result, pgsql_row, field_offset); break; case PHP_PG_DATA_ISNULL: Z_LVAL_P(return_value) = PQgetisnull(pgsql_result, pgsql_row, field_offset); break; } Z_TYPE_P(return_value) = IS_LONG; } /* }}} */ /* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number) Returns the printed length */ PHP_FUNCTION(pg_field_prtlen) { php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH); } /* }}} */ /* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number) Test if a field is NULL */ PHP_FUNCTION(pg_field_is_null) { php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL); } /* }}} */ /* {{{ proto bool pg_free_result(resource result) Free result memory */ PHP_FUNCTION(pg_free_result) { zval *result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); if (Z_LVAL_P(result) == 0) { RETURN_FALSE; } zend_list_delete(Z_RESVAL_P(result)); RETURN_TRUE; } /* }}} */ /* {{{ proto string pg_last_oid(resource result) Returns the last object identifier */ PHP_FUNCTION(pg_last_oid) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; #ifdef HAVE_PQOIDVALUE Oid oid; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; #ifdef HAVE_PQOIDVALUE oid = PQoidValue(pgsql_result); if (oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(oid); #else Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result); if (Z_STRVAL_P(return_value)) { RETURN_STRING(Z_STRVAL_P(return_value), 1); } RETURN_STRING("", 1); #endif } /* }}} */ /* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]]) Enable tracing a PostgreSQL connection */ PHP_FUNCTION(pg_trace) { char *z_filename, *mode = "w"; int z_filename_len, mode_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; FILE *fp = NULL; php_stream *stream; id = PGG(default_link); if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) { return; } if (argc < 3) { CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL); if (!stream) { RETURN_FALSE; } if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { php_stream_close(stream); RETURN_FALSE; } php_stream_auto_cleanup(stream); PQtrace(pgsql, fp); RETURN_TRUE; } /* }}} */ /* {{{ proto bool pg_untrace([resource connection]) Disable tracing of a PostgreSQL connection */ PHP_FUNCTION(pg_untrace) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); PQuntrace(pgsql); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid]) Create a large object */ PHP_FUNCTION(pg_lo_create) { zval *pgsql_link = NULL, *oid = NULL; PGconn *pgsql; Oid pgsql_oid, wanted_oid = InvalidOid; int id = -1, argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "|zz", &pgsql_link, &oid) == FAILURE) { return; } if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) { oid = pgsql_link; pgsql_link = NULL; } if (pgsql_link == NULL) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); if (id == -1) { RETURN_FALSE; } } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (oid) { #ifndef HAVE_PG_LO_CREATE php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Passing OID value is not supported. Upgrade your PostgreSQL"); #else switch (Z_TYPE_P(oid)) { case IS_STRING: { char *end_ptr; wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10); if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } } break; case IS_LONG: if (Z_LVAL_P(oid) < (long)InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } wanted_oid = (Oid)Z_LVAL_P(oid); break; default: php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } PGSQL_RETURN_OID(pgsql_oid); #endif } if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } PGSQL_RETURN_OID(pgsql_oid); } /* }}} */ /* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid) Delete a large object */ PHP_FUNCTION(pg_lo_unlink) { zval *pgsql_link = NULL; long oid_long; char *oid_string, *end_ptr; int oid_strlen; PGconn *pgsql; Oid oid; int id = -1; int argc = ZEND_NUM_ARGS(); /* accept string type since Oid type is unsigned int */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rs", &pgsql_link, &oid_string, &oid_strlen) == 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, "rl", &pgsql_link, &oid_long) == 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, "s", &oid_string, &oid_strlen) == 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, "l", &oid_long) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID is specified"); RETURN_FALSE; } oid = (Oid)oid_long; id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments"); 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_unlink(pgsql, oid) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete PostgreSQL large object %u", oid); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode) Open a large object and return fd */ PHP_FUNCTION(pg_lo_open) { zval *pgsql_link = NULL; long oid_long; char *oid_string, *end_ptr, *mode_string; int oid_strlen, mode_strlen; PGconn *pgsql; Oid oid; int id = -1, pgsql_mode=0, pgsql_lofd; int create=0; pgLofp *pgsql_lofp; int argc = ZEND_NUM_ARGS(); /* accept string type since Oid is unsigned int */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == 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, "rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == 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, "ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == 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, "ls", &oid_long, &mode_string, &mode_strlen) == 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 { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments"); RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); /* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of faster to type. Unfortunately, doesn't behave the same way as fopen()... (Jouni) */ if (strchr(mode_string, 'r') == mode_string) { pgsql_mode |= INV_READ; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_WRITE; } } if (strchr(mode_string, 'w') == mode_string) { pgsql_mode |= INV_WRITE; create = 1; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_READ; } } pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp)); if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (create) { if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } else { if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (lo_unlink(pgsql, oid) == -1) { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP"); RETURN_FALSE; } efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object"); RETURN_FALSE; } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; Z_LVAL_P(return_value) = zend_list_insert(pgsql_lofp, le_lofp TSRMLS_CC); Z_TYPE_P(return_value) = IS_LONG; } } } else { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object"); RETURN_FALSE; } } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp); } } /* }}} */ /* {{{ proto bool pg_lo_close(resource large_object) Close a large object */ PHP_FUNCTION(pg_lo_close) { zval *pgsql_lofp; pgLofp *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_lofp) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_lofp, -1, "PostgreSQL large object", le_lofp); if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd); RETVAL_FALSE; } else { RETVAL_TRUE; } zend_list_delete(Z_RESVAL_P(pgsql_lofp)); return; } /* }}} */ #define PGSQL_LO_READ_BUF_SIZE 8192 /* {{{ proto string pg_lo_read(resource large_object [, int len]) Read a large object */ PHP_FUNCTION(pg_lo_read) { zval *pgsql_id; long len; int buf_len = PGSQL_LO_READ_BUF_SIZE, nbytes, argc = ZEND_NUM_ARGS(); char *buf; pgLofp *pgsql; if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &pgsql_id, &len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); if (argc > 1) { buf_len = len; } buf = (char *) safe_emalloc(sizeof(char), (buf_len+1), 0); if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, buf_len))<0) { efree(buf); RETURN_FALSE; } buf[nbytes] = '\0'; RETURN_STRINGL(buf, nbytes, 0); } /* }}} */ /* {{{ proto int pg_lo_write(resource large_object, string buf [, int len]) Write a large object */ PHP_FUNCTION(pg_lo_write) { zval *pgsql_id; char *str; long z_len; int str_len, nbytes; int len; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "rs|l", &pgsql_id, &str, &str_len, &z_len) == FAILURE) { return; } if (argc > 2) { if (z_len > str_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot write more than buffer size %d. Tried to write %ld", str_len, z_len); RETURN_FALSE; } if (z_len < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Buffer size must be larger than 0, but %ld was specified", z_len); RETURN_FALSE; } len = z_len; } else { len = str_len; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == -1) { RETURN_FALSE; } RETURN_LONG(nbytes); } /* }}} */ /* {{{ proto int pg_lo_read_all(resource large_object) Read a large object and send straight to browser */ PHP_FUNCTION(pg_lo_read_all) { zval *pgsql_id; int tbytes; volatile int nbytes; char buf[PGSQL_LO_READ_BUF_SIZE]; pgLofp *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); tbytes = 0; while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) { PHPWRITE(buf, nbytes); tbytes += nbytes; } RETURN_LONG(tbytes); } /* }}} */ /* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid]) Import large object direct from filesystem */ PHP_FUNCTION(pg_lo_import) { zval *pgsql_link = NULL, *oid = NULL; char *file_in; int id = -1, name_len; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; Oid returned_oid; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rp|z", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) { ; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "p|z", &file_in, &name_len, &oid) == SUCCESS) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } /* old calling convention, deprecated since PHP 4.2 */ else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "pr", &file_in, &name_len, &pgsql_link ) == SUCCESS) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used"); } else { WRONG_PARAM_COUNT; } if (php_check_open_basedir(file_in 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 (oid) { #ifndef HAVE_PG_LO_IMPORT_WITH_OID php_error_docref(NULL TSRMLS_CC, E_NOTICE, "OID value passing not supported"); #else Oid wanted_oid; switch (Z_TYPE_P(oid)) { case IS_STRING: { char *end_ptr; wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10); if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } } break; case IS_LONG: if (Z_LVAL_P(oid) < (long)InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } wanted_oid = (Oid)Z_LVAL_P(oid); break; default: php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid); if (returned_oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(returned_oid); #endif } returned_oid = lo_import(pgsql, file_in); if (returned_oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(returned_oid); } /* }}} */ /* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename) Export large object direct to filesystem */ 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)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence]) Seeks position of large object */ PHP_FUNCTION(pg_lo_seek) { zval *pgsql_id = NULL; long offset = 0, whence = SEEK_CUR; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) { return; } if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid whence parameter"); return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); if (lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence) > -1) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto int pg_lo_tell(resource large_object) Returns current position of large object */ PHP_FUNCTION(pg_lo_tell) { zval *pgsql_id = NULL; int offset = 0; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "r", &pgsql_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd); RETURN_LONG(offset); } /* }}} */ #if HAVE_PQSETERRORVERBOSITY /* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity) Set error verbosity */ PHP_FUNCTION(pg_set_error_verbosity) { zval *pgsql_link = NULL; long verbosity; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (argc == 1) { if (zend_parse_parameters(argc TSRMLS_CC, "l", &verbosity) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rl", &pgsql_link, &verbosity) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) { Z_LVAL_P(return_value) = PQsetErrorVerbosity(pgsql, verbosity); Z_TYPE_P(return_value) = IS_LONG; } else { RETURN_FALSE; } } /* }}} */ #endif #ifdef HAVE_PQCLIENTENCODING /* {{{ proto int pg_set_client_encoding([resource connection,] string encoding) Set client encoding */ PHP_FUNCTION(pg_set_client_encoding) { char *encoding; int encoding_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (argc == 1) { if (zend_parse_parameters(argc TSRMLS_CC, "s", &encoding, &encoding_len) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &encoding, &encoding_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); Z_LVAL_P(return_value) = PQsetClientEncoding(pgsql, encoding); Z_TYPE_P(return_value) = IS_LONG; } /* }}} */ /* {{{ proto string pg_client_encoding([resource connection]) Get the current client encoding */ PHP_FUNCTION(pg_client_encoding) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); /* Just do the same as found in PostgreSQL sources... */ Z_STRVAL_P(return_value) = (char *) pg_encoding_to_char(PQclientEncoding(pgsql)); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; } /* }}} */ #endif #if !HAVE_PQGETCOPYDATA #define COPYBUFSIZ 8192 #endif /* {{{ proto bool pg_end_copy([resource connection]) Sync with backend. Completes the Copy command */ PHP_FUNCTION(pg_end_copy) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; int result = 0; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); result = PQendcopy(pgsql); if (result!=0) { PHP_PQ_ERROR("Query failed: %s", pgsql); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pg_put_line([resource connection,] string query) Send null-terminated string to backend server*/ PHP_FUNCTION(pg_put_line) { char *query; zval *pgsql_link = NULL; int query_len, id = -1; PGconn *pgsql; int result = 0, argc = ZEND_NUM_ARGS(); if (argc == 1) { if (zend_parse_parameters(argc TSRMLS_CC, "s", &query, &query_len) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); result = PQputline(pgsql, query); if (result==EOF) { PHP_PQ_ERROR("Query failed: %s", pgsql); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]]) Copy table to array */ PHP_FUNCTION(pg_copy_to) { zval *pgsql_link; char *table_name, *pg_delim = NULL, *pg_null_as = NULL; int table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0; char *query; int id = -1; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; int copydone = 0; #if !HAVE_PQGETCOPYDATA char copybuf[COPYBUFSIZ]; #endif char *csv = (char *)NULL; int ret; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "rs|ss", &pgsql_link, &table_name, &table_name_len, &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) { return; } if (!pg_delim) { pg_delim = "\t"; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (!pg_null_as) { pg_null_as = safe_estrdup("\\\\N"); free_pg_null = 1; } spprintf(&query, 0, "COPY %s TO STDOUT DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } pgsql_result = PQexec(pgsql, query); if (free_pg_null) { efree(pg_null_as); } efree(query); if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_COPY_OUT: if (pgsql_result) { PQclear(pgsql_result); array_init(return_value); #if HAVE_PQGETCOPYDATA while (!copydone) { ret = PQgetCopyData(pgsql, &csv, 0); switch (ret) { case -1: copydone = 1; break; case 0: case -2: PHP_PQ_ERROR("getline failed: %s", pgsql); RETURN_FALSE; break; default: add_next_index_string(return_value, csv, 1); PQfreemem(csv); break; } } #else while (!copydone) { if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) { PHP_PQ_ERROR("getline failed: %s", pgsql); RETURN_FALSE; } if (copybuf[0] == '\\' && copybuf[1] == '.' && copybuf[2] == '\0') { copydone = 1; } else { if (csv == (char *)NULL) { csv = estrdup(copybuf); } else { csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1)); strcat(csv, copybuf); } switch (ret) { case EOF: copydone = 1; case 0: add_next_index_string(return_value, csv, 1); efree(csv); csv = (char *)NULL; break; case 1: break; } } } if (PQendcopy(pgsql)) { PHP_PQ_ERROR("endcopy failed: %s", pgsql); RETURN_FALSE; } #endif while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } } else { PQclear(pgsql_result); RETURN_FALSE; } break; default: PQclear(pgsql_result); PHP_PQ_ERROR("Copy command failed: %s", pgsql); RETURN_FALSE; break; } } /* }}} */ /* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]]) Copy table from array */ PHP_FUNCTION(pg_copy_from) { zval *pgsql_link = NULL, *pg_rows; zval **tmp; char *table_name, *pg_delim = NULL, *pg_null_as = NULL; int table_name_len, pg_delim_len, pg_null_as_len; int pg_null_as_free = 0; char *query; HashPosition pos; int id = -1; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "rsa|ss", &pgsql_link, &table_name, &table_name_len, &pg_rows, &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) { return; } if (!pg_delim) { pg_delim = "\t"; } if (!pg_null_as) { pg_null_as = safe_estrdup("\\\\N"); pg_null_as_free = 1; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } pgsql_result = PQexec(pgsql, query); if (pg_null_as_free) { efree(pg_null_as); } efree(query); if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_COPY_IN: if (pgsql_result) { int command_failed = 0; PQclear(pgsql_result); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos); #if HAVE_PQPUTCOPYDATA while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) { convert_to_string_ex(tmp); query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2); strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2); if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') { strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2); } if (PQputCopyData(pgsql, query, strlen(query)) != 1) { efree(query); PHP_PQ_ERROR("copy failed: %s", pgsql); RETURN_FALSE; } efree(query); zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos); } if (PQputCopyEnd(pgsql, NULL) != 1) { PHP_PQ_ERROR("putcopyend failed: %s", pgsql); RETURN_FALSE; } #else while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) { convert_to_string_ex(tmp); query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2); strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2); if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') { strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2); } if (PQputline(pgsql, query)==EOF) { efree(query); PHP_PQ_ERROR("copy failed: %s", pgsql); RETURN_FALSE; } efree(query); zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos); } if (PQputline(pgsql, "\\.\n") == EOF) { PHP_PQ_ERROR("putline failed: %s", pgsql); RETURN_FALSE; } if (PQendcopy(pgsql)) { PHP_PQ_ERROR("endcopy failed: %s", pgsql); RETURN_FALSE; } #endif while ((pgsql_result = PQgetResult(pgsql))) { if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) { PHP_PQ_ERROR("Copy command failed: %s", pgsql); command_failed = 1; } PQclear(pgsql_result); } if (command_failed) { RETURN_FALSE; } } else { PQclear(pgsql_result); RETURN_FALSE; } RETURN_TRUE; break; default: PQclear(pgsql_result); PHP_PQ_ERROR("Copy command failed: %s", pgsql); RETURN_FALSE; break; } } /* }}} */ #ifdef HAVE_PQESCAPE /* {{{ proto string pg_escape_string([resource connection,] string data) Escape string for text/char type */ PHP_FUNCTION(pg_escape_string) { char *from = NULL, *to = NULL; zval *pgsql_link; #ifdef HAVE_PQESCAPE_CONN PGconn *pgsql; #endif int to_len; int from_len; int id = -1; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) { return; } pgsql_link = NULL; id = PGG(default_link); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) { return; } break; } to = (char *) safe_emalloc(from_len, 2, 1); #ifdef HAVE_PQESCAPE_CONN if (pgsql_link != NULL || id != -1) { ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); to_len = (int) PQescapeStringConn(pgsql, to, from, (size_t)from_len, NULL); } else #endif to_len = (int) PQescapeString(to, from, (size_t)from_len); RETURN_STRINGL(to, to_len, 0); } /* }}} */ /* {{{ proto string pg_escape_bytea([resource connection,] string data) Escape binary for bytea type */ PHP_FUNCTION(pg_escape_bytea) { char *from = NULL, *to = NULL; size_t to_len; int from_len, id = -1; #ifdef HAVE_PQESCAPE_BYTEA_CONN PGconn *pgsql; #endif zval *pgsql_link; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) { return; } pgsql_link = NULL; id = PGG(default_link); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) { return; } break; } #ifdef HAVE_PQESCAPE_BYTEA_CONN if (pgsql_link != NULL || id != -1) { ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len); } else #endif to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len); RETVAL_STRINGL(to, to_len-1, 1); /* to_len includes addtional '\0' */ PQfreemem(to); } /* }}} */ #if !HAVE_PQUNESCAPEBYTEA /* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users. Renamed to php_pgsql_unescape_bytea() */ /* * PQunescapeBytea - converts the null terminated string representation * of a bytea, strtext, into binary, filling a buffer. It returns a * pointer to the buffer which is NULL on error, and the size of the * buffer in retbuflen. The pointer may subsequently be used as an * argument to the function free(3). It is the reverse of PQescapeBytea. * * The following transformations are reversed: * '\0' == ASCII 0 == \000 * '\'' == ASCII 39 == \' * '\\' == ASCII 92 == \\ * * States: * 0 normal 0->1->2->3->4 * 1 \ 1->5 * 2 \0 1->6 * 3 \00 * 4 \000 * 5 \' * 6 \\ */ static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen) { size_t buflen; unsigned char *buffer, *sp, *bp; unsigned int state = 0; if (strtext == NULL) return NULL; buflen = strlen(strtext); /* will shrink, also we discover if * strtext */ buffer = (unsigned char *) emalloc(buflen); /* isn't NULL terminated */ for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++) { Commit Message: 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: long Chapters::ParseEdition( long long pos, long long size) { if (!ExpandEditionsArray()) return -1; Edition& e = m_editions[m_editions_count++]; e.Init(); return e.Parse(m_pSegment->m_pReader, pos, size); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: bool NaClIPCAdapter::SendCompleteMessage(const char* buffer, size_t buffer_len) { const NaClMessageHeader* header = reinterpret_cast<const NaClMessageHeader*>(buffer); int body_len = static_cast<int>(buffer_len - sizeof(NaClMessageHeader)); DCHECK(body_len == static_cast<int>(header->payload_size)); scoped_ptr<IPC::Message> msg( new IPC::Message(header->routing, header->type, IPC::Message::PRIORITY_NORMAL)); if (header->flags & IPC::Message::SYNC_BIT) msg->set_sync(); if (header->flags & IPC::Message::REPLY_BIT) msg->set_reply(); if (header->flags & IPC::Message::REPLY_ERROR_BIT) msg->set_reply_error(); if (header->flags & IPC::Message::UNBLOCK_BIT) msg->set_unblock(true); msg->WriteBytes(&buffer[sizeof(NaClMessageHeader)], body_len); lock_.AssertAcquired(); if (locked_data_.channel_closed_) return false; // TODO(brettw) clean up handles here when we add support! task_runner_->PostTask(FROM_HERE, base::Bind(&NaClIPCAdapter::SendMessageOnIOThread, this, base::Passed(&msg))); return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 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 freeHintsCallback(void *ptr) { sdsfree(ptr); } Commit Message: Security: fix redis-cli buffer overflow. Thanks to Fakhri Zulkifli for reporting it. The fix switched to dynamic allocation, copying the final prompt in the static buffer only at the end. 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 atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct atl2_adapter *adapter; static int cards_found; unsigned long mmio_start; int mmio_len; int err; cards_found = 0; err = pci_enable_device(pdev); if (err) return err; /* * atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA * until the kernel has the proper infrastructure to support 64-bit DMA * on these devices. */ if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) && pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) { printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n"); goto err_dma; } /* Mark all PCI regions associated with PCI device * pdev as being reserved by owner atl2_driver_name */ err = pci_request_regions(pdev, atl2_driver_name); if (err) goto err_pci_reg; /* Enables bus-mastering on the device and calls * pcibios_set_master to do the needed arch specific settings */ pci_set_master(pdev); err = -ENOMEM; netdev = alloc_etherdev(sizeof(struct atl2_adapter)); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; adapter->hw.back = adapter; mmio_start = pci_resource_start(pdev, 0x0); mmio_len = pci_resource_len(pdev, 0x0); adapter->hw.mem_rang = (u32)mmio_len; adapter->hw.hw_addr = ioremap(mmio_start, mmio_len); if (!adapter->hw.hw_addr) { err = -EIO; goto err_ioremap; } atl2_setup_pcicmd(pdev); netdev->netdev_ops = &atl2_netdev_ops; netdev->ethtool_ops = &atl2_ethtool_ops; netdev->watchdog_timeo = 5 * HZ; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); netdev->mem_start = mmio_start; netdev->mem_end = mmio_start + mmio_len; adapter->bd_number = cards_found; adapter->pci_using_64 = false; /* setup the private structure */ err = atl2_sw_init(adapter); if (err) goto err_sw_init; err = -EIO; netdev->hw_features = NETIF_F_SG | NETIF_F_HW_VLAN_CTAG_RX; netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX); /* Init PHY as early as possible due to power saving issue */ atl2_phy_init(&adapter->hw); /* reset the controller to * put the device in a known good starting state */ if (atl2_reset_hw(&adapter->hw)) { err = -EIO; goto err_reset; } /* copy the MAC address out of the EEPROM */ atl2_read_mac_addr(&adapter->hw); memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len); if (!is_valid_ether_addr(netdev->dev_addr)) { err = -EIO; goto err_eeprom; } atl2_check_options(adapter); setup_timer(&adapter->watchdog_timer, atl2_watchdog, (unsigned long)adapter); setup_timer(&adapter->phy_config_timer, atl2_phy_config, (unsigned long)adapter); INIT_WORK(&adapter->reset_task, atl2_reset_task); INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task); strcpy(netdev->name, "eth%d"); /* ?? */ err = register_netdev(netdev); if (err) goto err_register; /* assume we have no link for now */ netif_carrier_off(netdev); netif_stop_queue(netdev); cards_found++; return 0; err_reset: err_register: err_sw_init: err_eeprom: iounmap(adapter->hw.hw_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; } Commit Message: atl2: Disable unimplemented scatter/gather feature atl2 includes NETIF_F_SG in hw_features even though it has no support for non-linear skbs. This bug was originally harmless since the driver does not claim to implement checksum offload and that used to be a requirement for SG. Now that SG and checksum offload are independent features, if you explicitly enable SG *and* use one of the rare protocols that can use SG without checkusm offload, this potentially leaks sensitive information (before you notice that it just isn't working). Therefore this obscure bug has been designated CVE-2016-2117. Reported-by: Justin Yackoski <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> Fixes: ec5f06156423 ("net: Kill link between CSUM and SG features.") Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: virtual status_t getState( node_id node, OMX_STATETYPE* state) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); remote()->transact(GET_STATE, data, &reply); *state = static_cast<OMX_STATETYPE>(reply.readInt32()); return reply.readInt32(); } Commit Message: Fix size check for OMX_IndexParamConsumerUsageBits since it doesn't follow the OMX convention. And remove support for the kClientNeedsFrameBuffer flag. Bug: 27207275 Change-Id: Ia2c119e2456ebf9e2f4e1de5104ef9032a212255 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: ResourceRequestBlockedReason BaseFetchContext::CanRequest( Resource::Type type, const ResourceRequest& resource_request, const KURL& url, const ResourceLoaderOptions& options, SecurityViolationReportingPolicy reporting_policy, FetchParameters::OriginRestriction origin_restriction, ResourceRequest::RedirectStatus redirect_status) const { ResourceRequestBlockedReason blocked_reason = CanRequestInternal(type, resource_request, url, options, reporting_policy, origin_restriction, redirect_status); if (blocked_reason != ResourceRequestBlockedReason::kNone && reporting_policy == SecurityViolationReportingPolicy::kReport) { DispatchDidBlockRequest(resource_request, options.initiator_info, blocked_reason); } return blocked_reason; } 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 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 jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = joinbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int hstartcol; /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide. */ abort(); } } hstartcol = (numrows + 1 - parity) >> 1; /* Save the samples from the lowpass channel. */ n = hstartcol; srcptr = &a[0]; dstptr = buf; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } srcptr += stride; dstptr += JPC_QMFB_COLGRPSIZE; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol * stride]; dstptr = &a[(1 - parity) * stride]; n = numrows - hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += stride; } /* Copy the samples from the lowpass channel into place. */ srcptr = buf; dstptr = &a[parity * stride]; n = hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += JPC_QMFB_COLGRPSIZE; } /* If the join buffer was allocated on the heap, free this memory. */ if (buf != joinbuf) { jas_free(buf); } } Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec that was caused by a buffer being allocated with a size that was too small in some cases. Added a new regression test case. CWE ID: CWE-119 Target: 1 Example 2: Code: static boolean parse_float( const char **pcur, float *val ) { const char *cur = *pcur; boolean integral_part = FALSE; boolean fractional_part = FALSE; if (*cur == '0' && *(cur + 1) == 'x') { union fi fi; fi.ui = strtoul(cur, NULL, 16); *val = fi.f; cur += 10; goto out; } *val = (float) atof( cur ); if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; integral_part = TRUE; while (is_digit( cur )) cur++; } if (*cur == '.') { cur++; if (is_digit( cur )) { cur++; fractional_part = TRUE; while (is_digit( cur )) cur++; } } if (!integral_part && !fractional_part) return FALSE; if (uprcase( *cur ) == 'E') { cur++; if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; while (is_digit( cur )) cur++; } else return FALSE; } out: *pcur = cur; return TRUE; } 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: SortDirection AXTableCell::getSortDirection() const { if (roleValue() != RowHeaderRole && roleValue() != ColumnHeaderRole) return SortDirectionUndefined; const AtomicString& ariaSort = getAOMPropertyOrARIAAttribute(AOMStringProperty::kSort); if (ariaSort.isEmpty()) return SortDirectionUndefined; if (equalIgnoringCase(ariaSort, "none")) return SortDirectionNone; if (equalIgnoringCase(ariaSort, "ascending")) return SortDirectionAscending; if (equalIgnoringCase(ariaSort, "descending")) return SortDirectionDescending; if (equalIgnoringCase(ariaSort, "other")) return SortDirectionOther; return SortDirectionUndefined; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254 Output:
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 SanitizeFrontendPath(const std::string& path) { for (size_t i = 0; i < path.length(); i++) { if (path[i] != '/' && path[i] != '-' && path[i] != '_' && path[i] != '.' && path[i] != '@' && !(path[i] >= '0' && path[i] <= '9') && !(path[i] >= 'a' && path[i] <= 'z') && !(path[i] >= 'A' && path[i] <= 'Z')) { return std::string(); } } return path; } 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: json_each(PG_FUNCTION_ARGS) { return each_worker(fcinfo, false); } 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 float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; assert(0); return NULL; } Commit Message: Fix seven bugs discovered and fixed by ForAllSecure: CVE-2019-13217: heap buffer overflow in start_decoder() CVE-2019-13218: stack buffer overflow in compute_codewords() CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest() CVE-2019-13220: out-of-range read in draw_line() CVE-2019-13221: issue with large 1D codebooks in lookup1_values() CVE-2019-13222: unchecked NULL returned by get_window() CVE-2019-13223: division by zero in predict_point() CWE ID: CWE-20 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 verify_source_vc(char **ret_path, const char *src_vc) { _cleanup_close_ int fd = -1; char *path; int r; fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(fd, "Failed to open %s: %m", src_vc); r = verify_vc_device(fd); if (r < 0) return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc); r = verify_vc_allocation_byfd(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc); r = verify_vc_kbmode(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc); path = strdup(src_vc); if (!path) return log_oom(); *ret_path = path; return TAKE_FD(fd); } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255 Target: 1 Example 2: Code: void set_scl(int state) { I2C_SCL(state); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes 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: WebDateTimeChooserCompletion* ChooserCompletion() { return chooser_completion_; } 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: check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { uint8 header[27], lacing[255]; int i,len; z->page_start = stb_vorbis_get_file_offset(f); getn(f, header, 27); if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; getn(f, lacing, header[26]); len = 0; for (i=0; i < header[26]; ++i) len += lacing[i]; z->page_end = z->page_start + 27 + header[26] + len; z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); set_file_offset(f, z->page_start); return 1; } Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files 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: CStarter::RemoveRecoveryFile() { if ( m_recoveryFile.Length() > 0 ) { unlink( m_recoveryFile.Value() ); m_recoveryFile = ""; } } Commit Message: CWE ID: CWE-134 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 sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) { struct sctp_association *asoc = sctp_id2assoc(sk, id); struct sctp_sock *sp = sctp_sk(sk); struct socket *sock; int err = 0; if (!asoc) return -EINVAL; /* An association cannot be branched off from an already peeled-off * socket, nor is this supported for tcp style sockets. */ if (!sctp_style(sk, UDP)) return -EINVAL; /* Create a new socket. */ err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock); if (err < 0) return err; sctp_copy_sock(sock->sk, sk, asoc); /* Make peeled-off sockets more like 1-1 accepted sockets. * Set the daddr and initialize id to something more random */ sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk); /* Populate the fields of the newsk from the oldsk and migrate the * asoc to the newsk. */ sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH); *sockp = sock; return err; } Commit Message: sctp: deny peeloff operation on asocs with threads sleeping on it commit 2dcab5984841 ("sctp: avoid BUG_ON on sctp_wait_for_sndbuf") attempted to avoid a BUG_ON call when the association being used for a sendmsg() is blocked waiting for more sndbuf and another thread did a peeloff operation on such asoc, moving it to another socket. As Ben Hutchings noticed, then in such case it would return without locking back the socket and would cause two unlocks in a row. Further analysis also revealed that it could allow a double free if the application managed to peeloff the asoc that is created during the sendmsg call, because then sctp_sendmsg() would try to free the asoc that was created only for that call. This patch takes another approach. It will deny the peeloff operation if there is a thread sleeping on the asoc, so this situation doesn't exist anymore. This avoids the issues described above and also honors the syscalls that are already being handled (it can be multiple sendmsg calls). Joint work with Xin Long. Fixes: 2dcab5984841 ("sctp: avoid BUG_ON on sctp_wait_for_sndbuf") Cc: Alexander Popov <[email protected]> Cc: Ben Hutchings <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: Xin Long <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-415 Target: 1 Example 2: Code: static void ehci_execute_complete(EHCIQueue *q) { EHCIPacket *p = QTAILQ_FIRST(&q->packets); uint32_t tbytes; assert(p != NULL); assert(p->qtdaddr == q->qtdaddr); assert(p->async == EHCI_ASYNC_INITIALIZED || p->async == EHCI_ASYNC_FINISHED); DPRINTF("execute_complete: qhaddr 0x%x, next 0x%x, qtdaddr 0x%x, " "status %d, actual_length %d\n", q->qhaddr, q->qh.next, q->qtdaddr, p->packet.status, p->packet.actual_length); switch (p->packet.status) { case USB_RET_SUCCESS: break; case USB_RET_IOERROR: case USB_RET_NODEV: q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_XACTERR); set_field(&q->qh.token, 0, QTD_TOKEN_CERR); ehci_raise_irq(q->ehci, USBSTS_ERRINT); break; case USB_RET_STALL: q->qh.token |= QTD_TOKEN_HALT; ehci_raise_irq(q->ehci, USBSTS_ERRINT); break; case USB_RET_NAK: set_field(&q->qh.altnext_qtd, 0, QH_ALTNEXT_NAKCNT); return; /* We're not done yet with this transaction */ case USB_RET_BABBLE: q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE); ehci_raise_irq(q->ehci, USBSTS_ERRINT); break; default: /* should not be triggerable */ fprintf(stderr, "USB invalid response %d\n", p->packet.status); g_assert_not_reached(); break; } /* TODO check 4.12 for splits */ tbytes = get_field(q->qh.token, QTD_TOKEN_TBYTES); if (tbytes && p->pid == USB_TOKEN_IN) { tbytes -= p->packet.actual_length; if (tbytes) { /* 4.15.1.2 must raise int on a short input packet */ ehci_raise_irq(q->ehci, USBSTS_INT); if (q->async) { q->ehci->int_req_by_async = true; } } } else { tbytes = 0; } DPRINTF("updating tbytes to %d\n", tbytes); set_field(&q->qh.token, tbytes, QTD_TOKEN_TBYTES); ehci_finish_transfer(q, p->packet.actual_length); usb_packet_unmap(&p->packet, &p->sgl); qemu_sglist_destroy(&p->sgl); p->async = EHCI_ASYNC_NONE; q->qh.token ^= QTD_TOKEN_DTOGGLE; q->qh.token &= ~QTD_TOKEN_ACTIVE; if (q->qh.token & QTD_TOKEN_IOC) { ehci_raise_irq(q->ehci, USBSTS_INT); if (q->async) { q->ehci->int_req_by_async = true; } } } Commit Message: CWE ID: CWE-772 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: EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionAddEventListener(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestEventTarget::s_info)) return throwVMTypeError(exec); JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info); TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); impl->addEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)), exec->argument(2).toBoolean(exec)); return JSValue::encode(jsUndefined()); } 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 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 die_codec(vpx_codec_ctx_t *ctx, const char *s) { const char *detail = vpx_codec_error_detail(ctx); printf("%s: %s\n", s, vpx_codec_error(ctx)); if(detail) printf(" %s\n",detail); exit(EXIT_FAILURE); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static int asf_read_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; ff_asf_guid g; AVIOContext *pb = s->pb; int i; int64_t gsize; ff_get_guid(pb, &g); if (ff_guidcmp(&g, &ff_asf_header)) return AVERROR_INVALIDDATA; avio_rl64(pb); avio_rl32(pb); avio_r8(pb); avio_r8(pb); memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid)); for (i = 0; i<128; i++) asf->streams[i].stream_language_index = 128; // invalid stream index means no language info for (;;) { uint64_t gpos = avio_tell(pb); int ret = 0; ff_get_guid(pb, &g); gsize = avio_rl64(pb); print_guid(&g); if (!ff_guidcmp(&g, &ff_asf_data_header)) { asf->data_object_offset = avio_tell(pb); /* If not streaming, gsize is not unlimited (how?), * and there is enough space in the file.. */ if (!(asf->hdr.flags & 0x01) && gsize >= 100) asf->data_object_size = gsize - 24; else asf->data_object_size = (uint64_t)-1; break; } if (gsize < 24) return AVERROR_INVALIDDATA; if (!ff_guidcmp(&g, &ff_asf_file_header)) { ret = asf_read_file_properties(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) { ret = asf_read_stream_properties(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) { asf_read_content_desc(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) { asf_read_language_list(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) { asf_read_ext_content_desc(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) { asf_read_metadata(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_metadata_library_header)) { asf_read_metadata(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) { asf_read_ext_stream_properties(s, gsize); continue; } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) { ff_get_guid(pb, &g); avio_skip(pb, 6); continue; } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) { asf_read_marker(s, gsize); } else if (avio_feof(pb)) { return AVERROR_EOF; } else { if (!s->keylen) { if (!ff_guidcmp(&g, &ff_asf_content_encryption)) { unsigned int len; AVPacket pkt; av_log(s, AV_LOG_WARNING, "DRM protected stream detected, decoding will likely fail!\n"); len= avio_rl32(pb); av_log(s, AV_LOG_DEBUG, "Secret data:\n"); if ((ret = av_get_packet(pb, &pkt, len)) < 0) return ret; av_hex_dump_log(s, AV_LOG_DEBUG, pkt.data, pkt.size); av_packet_unref(&pkt); len= avio_rl32(pb); get_tag(s, "ASF_Protection_Type", -1, len, 32); len= avio_rl32(pb); get_tag(s, "ASF_Key_ID", -1, len, 32); len= avio_rl32(pb); get_tag(s, "ASF_License_URL", -1, len, 32); } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) { av_log(s, AV_LOG_WARNING, "Ext DRM protected stream detected, decoding will likely fail!\n"); av_dict_set(&s->metadata, "encryption", "ASF Extended Content Encryption", 0); } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) { av_log(s, AV_LOG_INFO, "Digital signature detected!\n"); } } } if (ret < 0) return ret; if (avio_tell(pb) != gpos + gsize) av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRId64"\n", avio_tell(pb) - gpos, gsize); avio_seek(pb, gpos + gsize, SEEK_SET); } ff_get_guid(pb, &g); avio_rl64(pb); avio_r8(pb); avio_r8(pb); if (avio_feof(pb)) return AVERROR_EOF; asf->data_offset = avio_tell(pb); asf->packet_size_left = 0; for (i = 0; i < 128; i++) { int stream_num = asf->asfid2avid[i]; if (stream_num >= 0) { AVStream *st = s->streams[stream_num]; if (!st->codecpar->bit_rate) st->codecpar->bit_rate = asf->stream_bitrates[i]; if (asf->dar[i].num > 0 && asf->dar[i].den > 0) { av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, asf->dar[i].num, asf->dar[i].den, INT_MAX); } else if ((asf->dar[0].num > 0) && (asf->dar[0].den > 0) && (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, asf->dar[0].num, asf->dar[0].den, INT_MAX); av_log(s, AV_LOG_TRACE, "i=%d, st->codecpar->codec_type:%d, asf->dar %d:%d sar=%d:%d\n", i, st->codecpar->codec_type, asf->dar[i].num, asf->dar[i].den, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den); if (asf->streams[i].stream_language_index < 128) { const char *rfc1766 = asf->stream_languages[asf->streams[i].stream_language_index]; if (rfc1766 && strlen(rfc1766) > 1) { const char primary_tag[3] = { rfc1766[0], rfc1766[1], '\0' }; // ignore country code if any const char *iso6392 = ff_convert_lang_to(primary_tag, AV_LANG_ISO639_2_BIBL); if (iso6392) av_dict_set(&st->metadata, "language", iso6392, 0); } } } } ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv); return 0; } Commit Message: avformat/asfdec: Fix DoS in asf_build_simple_index() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[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 RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) { if (!is_hidden_) return; TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown"); is_hidden_ = false; if (new_content_rendering_timeout_ && new_content_rendering_timeout_->IsRunning()) { new_content_rendering_timeout_->Stop(); ClearDisplayedGraphics(); } SendScreenRects(); RestartHangMonitorTimeoutIfNecessary(); bool needs_repainting = true; needs_repainting_on_restore_ = false; Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info)); process_->WidgetRestored(); bool is_visible = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderWidgetHost>(this), Details<bool>(&is_visible)); WasResized(); } Commit Message: Force a flush of drawing to the widget when a dialog is shown. BUG=823353 TEST=as in bug Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260 Reviewed-on: https://chromium-review.googlesource.com/971661 Reviewed-by: Ken Buchanan <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#544518} 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 void add_bytes_l2_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w) { long i; for (i = 0; i <= w - sizeof(long); i += sizeof(long)) { long a = *(long *)(src1 + i); long b = *(long *)(src2 + i); *(long *)(dst + i) = ((a & pb_7f) + (b & pb_7f)) ^ ((a ^ b) & pb_80); } for (; i < w; i++) dst[i] = src1[i] + src2[i]; } Commit Message: avcodec/pngdsp: fix (un)signed type in end comparission Fixes out of array accesses Fixes Ticket2919 Found_by: ami_stuff Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: unsigned long DocumentLoader::MainResourceIdentifier() const { return GetResource() ? GetResource()->Identifier() : 0; } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <[email protected]> Commit-Queue: Nate Chapin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void stss_del(GF_Box *s) { GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s; if (ptr == NULL) return; if (ptr->sampleNumbers) gf_free(ptr->sampleNumbers); gf_free(ptr); } Commit Message: fixed 2 possible heap overflows (inc. #1088) 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: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ buflen = MIN(buflen, buf_size); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T)) { return IV_FAIL; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Fixed error concealment when no MBs are decoded in the current pic Bug: 29493002 Change-Id: I3fae547ddb0616b4e6579580985232bd3d65881e CWE ID: CWE-284 Target: 1 Example 2: Code: static apr_status_t lua_websocket_readbytes(conn_rec* c, char* buffer, apr_off_t len) { apr_bucket_brigade *brigade = apr_brigade_create(c->pool, c->bucket_alloc); apr_status_t rv; rv = ap_get_brigade(c->input_filters, brigade, AP_MODE_READBYTES, APR_BLOCK_READ, len); if (rv == APR_SUCCESS) { if (!APR_BRIGADE_EMPTY(brigade)) { apr_bucket* bucket = APR_BRIGADE_FIRST(brigade); const char* data = NULL; apr_size_t data_length = 0; rv = apr_bucket_read(bucket, &data, &data_length, APR_BLOCK_READ); if (rv == APR_SUCCESS) { memcpy(buffer, data, len); } apr_bucket_delete(bucket); } } apr_brigade_cleanup(brigade); return rv; } 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 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: tt_cmap12_char_index( TT_CMap cmap, FT_UInt32 char_code ) { return tt_cmap12_char_map_binary( cmap, &char_code, 0 ); } 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: static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer, apr_size_t len, int linelimit) { apr_size_t i = 0; while (i < len) { char c = buffer[i]; ap_xlate_proto_from_ascii(&c, 1); /* handle CRLF after the chunk */ if (ctx->state == BODY_CHUNK_END) { if (c == LF) { ctx->state = BODY_CHUNK; } i++; continue; } /* handle start of the chunk */ if (ctx->state == BODY_CHUNK) { if (!apr_isxdigit(c)) { /* * Detect invalid character at beginning. This also works for empty * chunk size lines. */ return APR_EGENERAL; } else { ctx->state = BODY_CHUNK_PART; } ctx->remaining = 0; ctx->chunkbits = sizeof(long) * 8; ctx->chunk_used = 0; } /* handle a chunk part, or a chunk extension */ /* * In theory, we are supposed to expect CRLF only, but our * test suite sends LF only. Tolerate a missing CR. */ if (c == ';' || c == CR) { ctx->state = BODY_CHUNK_EXT; } else if (c == LF) { if (ctx->remaining) { ctx->state = BODY_CHUNK_DATA; } else { ctx->state = BODY_CHUNK_TRAILER; } } else if (ctx->state != BODY_CHUNK_EXT) { int xvalue = 0; /* ignore leading zeros */ if (!ctx->remaining && c == '0') { i++; continue; } if (c >= '0' && c <= '9') { xvalue = c - '0'; } else if (c >= 'A' && c <= 'F') { xvalue = c - 'A' + 0xa; } else if (c >= 'a' && c <= 'f') { xvalue = c - 'a' + 0xa; } else { /* bogus character */ return APR_EGENERAL; } ctx->remaining = (ctx->remaining << 4) | xvalue; ctx->chunkbits -= 4; if (ctx->chunkbits <= 0 || ctx->remaining < 0) { /* overflow */ return APR_ENOSPC; } } i++; } /* sanity check */ ctx->chunk_used += len; if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) { return APR_ENOSPC; } return APR_SUCCESS; } Commit Message: Limit accepted chunk-size to 2^63-1 and be strict about chunk-ext authorized characters. Submitted by: Yann Ylavic git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684513 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-20 Target: 1 Example 2: Code: unsigned long bebytes2ulong(const u8 *buf) { if (buf == NULL) return 0UL; return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]); } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415 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 MediaControlTextTrackListElement::setVisible(bool visible) { if (visible) { setIsWanted(true); refreshTextTrackListMenu(); } else { setIsWanted(false); } } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} 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 Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1; image=AcquireImage(image_info,exception); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->resolution.x=BitmapHeader1.HorzRes/470.0; image->resolution.y=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->resolution.x=BitmapHeader2.HorzRes/470.0; image->resolution.y=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp,exception) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(image,BImgBuff,i,bpp,exception); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp,exception) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); } Commit Message: Ensure image extent does not exceed maximum CWE ID: CWE-119 Target: 1 Example 2: Code: int ssl3_accept(SSL *s) { BUF_MEM *buf; unsigned long alg_k, Time = (unsigned long)time(NULL); void (*cb) (const SSL *ssl, int type, int val) = NULL; int ret = -1; int new_state, state, skip = 0; RAND_add(&Time, sizeof(Time), 0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; /* init things to blank */ s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); if (s->cert == NULL) { SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET); return (-1); } #ifndef OPENSSL_NO_HEARTBEATS /* * If we're awaiting a HeartbeatResponse, pretend we already got and * don't await it anymore, because Heartbeats don't make sense during * handshakes anyway. */ if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state = s->state; switch (s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate = 1; /* s->state=SSL_ST_ACCEPT; */ case SSL_ST_BEFORE: case SSL_ST_ACCEPT: case SSL_ST_BEFORE | SSL_ST_ACCEPT: case SSL_ST_OK | SSL_ST_ACCEPT: s->server = 1; if (cb != NULL) cb(s, SSL_CB_HANDSHAKE_START, 1); if ((s->version >> 8) != 3) { SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); s->state = SSL_ST_ERR; return -1; } s->type = SSL_ST_ACCEPT; if (s->init_buf == NULL) { if ((buf = BUF_MEM_new()) == NULL) { ret = -1; s->state = SSL_ST_ERR; goto end; } if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) { BUF_MEM_free(buf); ret = -1; s->state = SSL_ST_ERR; goto end; } s->init_buf = buf; } if (!ssl3_setup_buffers(s)) { ret = -1; s->state = SSL_ST_ERR; goto end; } s->init_num = 0; s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE; s->s3->flags &= ~SSL3_FLAGS_CCS_OK; /* * Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; if (s->state != SSL_ST_RENEGOTIATE) { /* * Ok, we now need to push on a buffering BIO so that the * output is sent in a way that TCP likes :-) */ if (!ssl_init_wbio_buffer(s, 1)) { ret = -1; s->state = SSL_ST_ERR; goto end; } ssl3_init_finished_mac(s); s->state = SSL3_ST_SR_CLNT_HELLO_A; s->ctx->stats.sess_accept++; } else if (!s->s3->send_connection_binding && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { /* * Server attempting to renegotiate with client that doesn't * support secure renegotiation. */ SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); ret = -1; s->state = SSL_ST_ERR; goto end; } else { /* * s->state == SSL_ST_RENEGOTIATE, we will just send a * HelloRequest */ s->ctx->stats.sess_accept_renegotiate++; s->state = SSL3_ST_SW_HELLO_REQ_A; } break; case SSL3_ST_SW_HELLO_REQ_A: case SSL3_ST_SW_HELLO_REQ_B: s->shutdown = 0; ret = ssl3_send_hello_request(s); if (ret <= 0) goto end; s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C; s->state = SSL3_ST_SW_FLUSH; s->init_num = 0; ssl3_init_finished_mac(s); break; case SSL3_ST_SW_HELLO_REQ_C: s->state = SSL_ST_OK; break; case SSL3_ST_SR_CLNT_HELLO_A: case SSL3_ST_SR_CLNT_HELLO_B: case SSL3_ST_SR_CLNT_HELLO_C: s->shutdown = 0; if (s->rwstate != SSL_X509_LOOKUP) { ret = ssl3_get_client_hello(s); if (ret <= 0) goto end; } #ifndef OPENSSL_NO_SRP { int al; if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) { /* * callback indicates firther work to be done */ s->rwstate = SSL_X509_LOOKUP; goto end; } if (ret != SSL_ERROR_NONE) { ssl3_send_alert(s, SSL3_AL_FATAL, al); /* * This is not really an error but the only means to for * a client to detect whether srp is supported. */ if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT); ret = -1; s->state = SSL_ST_ERR; goto end; } } #endif s->renegotiate = 2; s->state = SSL3_ST_SW_SRVR_HELLO_A; s->init_num = 0; break; case SSL3_ST_SW_SRVR_HELLO_A: case SSL3_ST_SW_SRVR_HELLO_B: ret = ssl3_send_server_hello(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->hit) { if (s->tlsext_ticket_expected) s->state = SSL3_ST_SW_SESSION_TICKET_A; else s->state = SSL3_ST_SW_CHANGE_A; } #else if (s->hit) s->state = SSL3_ST_SW_CHANGE_A; #endif else s->state = SSL3_ST_SW_CERT_A; s->init_num = 0; break; case SSL3_ST_SW_CERT_A: case SSL3_ST_SW_CERT_B: /* Check if it is anon DH or anon ECDH, */ /* normal PSK or KRB5 or SRP */ if (! (s->s3->tmp. new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 | SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { ret = ssl3_send_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state = SSL3_ST_SW_CERT_STATUS_A; else s->state = SSL3_ST_SW_KEY_EXCH_A; } else { skip = 1; s->state = SSL3_ST_SW_KEY_EXCH_A; } #else } else skip = 1; s->state = SSL3_ST_SW_KEY_EXCH_A; #endif s->init_num = 0; break; case SSL3_ST_SW_KEY_EXCH_A: case SSL3_ST_SW_KEY_EXCH_B: alg_k = s->s3->tmp.new_cipher->algorithm_mkey; /* * clear this, it may get reset by * send_server_key_exchange */ s->s3->tmp.use_rsa_tmp = 0; /* * only send if a DH key exchange, fortezza or RSA but we have a * sign only certificate PSK: may send PSK identity hints For * ECC ciphersuites, we send a serverKeyExchange message only if * the cipher suite is either ECDH-anon or ECDHE. In other cases, * the server certificate contains the server's public key for * key exchange. */ if (0 /* * PSK: send ServerKeyExchange if PSK identity hint if * provided */ #ifndef OPENSSL_NO_PSK || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) #endif #ifndef OPENSSL_NO_SRP /* SRP: send ServerKeyExchange */ || (alg_k & SSL_kSRP) #endif || (alg_k & (SSL_kDHr | SSL_kDHd | SSL_kEDH)) || (alg_k & SSL_kEECDH) || ((alg_k & SSL_kRSA) && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && EVP_PKEY_size(s->cert->pkeys [SSL_PKEY_RSA_ENC].privatekey) * 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) ) ) ) ) { ret = ssl3_send_server_key_exchange(s); if (ret <= 0) goto end; } else skip = 1; s->state = SSL3_ST_SW_CERT_REQ_A; s->init_num = 0; break; case SSL3_ST_SW_CERT_REQ_A: case SSL3_ST_SW_CERT_REQ_B: if ( /* don't request cert unless asked for it: */ !(s->verify_mode & SSL_VERIFY_PEER) || /* * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert * during re-negotiation: */ ((s->session->peer != NULL) && (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || /* * never request cert in anonymous ciphersuites (see * section "Certificate request" in SSL 3 drafts and in * RFC 2246): */ ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && /* * ... except when the application insists on * verification (against the specs, but s3_clnt.c accepts * this for SSL 3) */ !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || /* * never request cert in Kerberos ciphersuites */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || /* don't request certificate for SRP auth */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) /* * With normal PSK Certificates and Certificate Requests * are omitted */ || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { /* no cert request */ skip = 1; s->s3->tmp.cert_request = 0; s->state = SSL3_ST_SW_SRVR_DONE_A; if (s->s3->handshake_buffer) { if (!ssl3_digest_cached_records(s)) { s->state = SSL_ST_ERR; return -1; } } } else { s->s3->tmp.cert_request = 1; ret = ssl3_send_certificate_request(s); if (ret <= 0) goto end; #ifndef NETSCAPE_HANG_BUG s->state = SSL3_ST_SW_SRVR_DONE_A; #else s->state = SSL3_ST_SW_FLUSH; s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; #endif s->init_num = 0; } break; case SSL3_ST_SW_SRVR_DONE_A: case SSL3_ST_SW_SRVR_DONE_B: ret = ssl3_send_server_done(s); if (ret <= 0) goto end; s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; s->state = SSL3_ST_SW_FLUSH; s->init_num = 0; break; case SSL3_ST_SW_FLUSH: /* * This code originally checked to see if any data was pending * using BIO_CTRL_INFO and then flushed. This caused problems as * documented in PR#1939. The proposed fix doesn't completely * resolve this issue as buggy implementations of * BIO_CTRL_PENDING still exist. So instead we just flush * unconditionally. */ s->rwstate = SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { ret = -1; goto end; } s->rwstate = SSL_NOTHING; s->state = s->s3->tmp.next_state; break; case SSL3_ST_SR_CERT_A: case SSL3_ST_SR_CERT_B: /* Check for second client hello (MS SGC) */ ret = ssl3_check_client_hello(s); if (ret <= 0) goto end; if (ret == 2) s->state = SSL3_ST_SR_CLNT_HELLO_C; else { if (s->s3->tmp.cert_request) { ret = ssl3_get_client_certificate(s); if (ret <= 0) goto end; } s->init_num = 0; s->state = SSL3_ST_SR_KEY_EXCH_A; } break; case SSL3_ST_SR_KEY_EXCH_A: case SSL3_ST_SR_KEY_EXCH_B: ret = ssl3_get_client_key_exchange(s); if (ret <= 0) goto end; if (ret == 2) { /* * For the ECDH ciphersuites when the client sends its ECDH * pub key in a certificate, the CertificateVerify message is * not sent. Also for GOST ciphersuites when the client uses * its key from the certificate for key exchange. */ #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state = SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state = SSL3_ST_SR_NEXT_PROTO_A; else s->state = SSL3_ST_SR_FINISHED_A; #endif s->init_num = 0; } else if (TLS1_get_version(s) >= TLS1_2_VERSION) { s->state = SSL3_ST_SR_CERT_VRFY_A; s->init_num = 0; if (!s->session->peer) break; /* * For TLS v1.2 freeze the handshake buffer at this point and * digest cached records. */ if (!s->s3->handshake_buffer) { SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); s->state = SSL_ST_ERR; return -1; } s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; if (!ssl3_digest_cached_records(s)) { s->state = SSL_ST_ERR; return -1; } } else { int offset = 0; int dgst_num; s->state = SSL3_ST_SR_CERT_VRFY_A; s->init_num = 0; /* * We need to get hashes here so if there is a client cert, * it can be verified FIXME - digest processing for * CertificateVerify should be generalized. But it is next * step */ if (s->s3->handshake_buffer) { if (!ssl3_digest_cached_records(s)) { s->state = SSL_ST_ERR; return -1; } } for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++) if (s->s3->handshake_dgst[dgst_num]) { int dgst_size; s->method->ssl3_enc->cert_verify_mac(s, EVP_MD_CTX_type (s-> s3->handshake_dgst [dgst_num]), &(s->s3-> tmp.cert_verify_md [offset])); dgst_size = EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); if (dgst_size < 0) { s->state = SSL_ST_ERR; ret = -1; goto end; } offset += dgst_size; } } break; case SSL3_ST_SR_CERT_VRFY_A: case SSL3_ST_SR_CERT_VRFY_B: ret = ssl3_get_cert_verify(s); if (ret <= 0) goto end; #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state = SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state = SSL3_ST_SR_NEXT_PROTO_A; else s->state = SSL3_ST_SR_FINISHED_A; #endif s->init_num = 0; break; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) case SSL3_ST_SR_NEXT_PROTO_A: case SSL3_ST_SR_NEXT_PROTO_B: /* * Enable CCS for NPN. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. This *should* be the * first time we have received one - but we check anyway to be * cautious. * s->s3->change_cipher_spec is set when a CCS is * processed in s3_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; ret = ssl3_get_next_proto(s); if (ret <= 0) goto end; s->init_num = 0; s->state = SSL3_ST_SR_FINISHED_A; break; #endif case SSL3_ST_SR_FINISHED_A: case SSL3_ST_SR_FINISHED_B: /* * Enable CCS for handshakes without NPN. In NPN the CCS flag has * already been set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in s3_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A, SSL3_ST_SR_FINISHED_B); if (ret <= 0) goto end; if (s->hit) s->state = SSL_ST_OK; #ifndef OPENSSL_NO_TLSEXT else if (s->tlsext_ticket_expected) s->state = SSL3_ST_SW_SESSION_TICKET_A; #endif else s->state = SSL3_ST_SW_CHANGE_A; s->init_num = 0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_SW_SESSION_TICKET_A: case SSL3_ST_SW_SESSION_TICKET_B: ret = ssl3_send_newsession_ticket(s); if (ret <= 0) goto end; s->state = SSL3_ST_SW_CHANGE_A; s->init_num = 0; break; case SSL3_ST_SW_CERT_STATUS_A: case SSL3_ST_SW_CERT_STATUS_B: ret = ssl3_send_cert_status(s); if (ret <= 0) goto end; s->state = SSL3_ST_SW_KEY_EXCH_A; s->init_num = 0; break; #endif case SSL3_ST_SW_CHANGE_A: case SSL3_ST_SW_CHANGE_B: s->session->cipher = s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ret = -1; s->state = SSL_ST_ERR; goto end; } ret = ssl3_send_change_cipher_spec(s, SSL3_ST_SW_CHANGE_A, SSL3_ST_SW_CHANGE_B); if (ret <= 0) goto end; s->state = SSL3_ST_SW_FINISHED_A; s->init_num = 0; if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) { ret = -1; s->state = SSL_ST_ERR; goto end; } break; case SSL3_ST_SW_FINISHED_A: case SSL3_ST_SW_FINISHED_B: ret = ssl3_send_finished(s, SSL3_ST_SW_FINISHED_A, SSL3_ST_SW_FINISHED_B, s->method-> ssl3_enc->server_finished_label, s->method-> ssl3_enc->server_finished_label_len); if (ret <= 0) goto end; s->state = SSL3_ST_SW_FLUSH; if (s->hit) { #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) { s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A; } else s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; #endif } else s->s3->tmp.next_state = SSL_ST_OK; s->init_num = 0; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); BUF_MEM_free(s->init_buf); s->init_buf = NULL; /* remove buffering on output */ ssl_free_wbio_buffer(s); s->init_num = 0; if (s->renegotiate == 2) { /* skipped if we just sent a * HelloRequest */ s->renegotiate = 0; s->new_session = 0; ssl_update_cache(s, SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; /* s->server=1; */ s->handshake_func = ssl3_accept; if (cb != NULL) cb(s, SSL_CB_HANDSHAKE_DONE, 1); } ret = 1; goto end; /* break; */ case SSL_ST_ERR: default: SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE); ret = -1; goto end; /* break; */ } if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret = BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state = s->state; s->state = state; cb(s, SSL_CB_ACCEPT_LOOP, 1); s->state = new_state; } } skip = 0; } Commit Message: CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DXVAVideoDecodeAccelerator::ClearState() { last_input_buffer_id_ = -1; output_picture_buffers_.clear(); pending_output_samples_.clear(); } 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: 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 install_thread_keyring(void) { struct cred *new; int ret; new = prepare_creds(); if (!new) return -ENOMEM; BUG_ON(new->thread_keyring); ret = install_thread_keyring_to_cred(new); if (ret < 0) { abort_creds(new); return ret; } return commit_creds(new); } Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings This fixes CVE-2017-7472. Running the following program as an unprivileged user exhausts kernel memory by leaking thread keyrings: #include <keyutils.h> int main() { for (;;) keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING); } Fix it by only creating a new thread keyring if there wasn't one before. To make things more consistent, make install_thread_keyring_to_cred() and install_process_keyring_to_cred() both return 0 if the corresponding keyring is already present. Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials") Cc: [email protected] # 2.6.29+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID: CWE-404 Target: 1 Example 2: Code: static bool ExecuteScrollLineUp(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return frame.GetEventHandler().BubblingScroll(kScrollUpIgnoringWritingMode, kScrollByLine); } Commit Message: Move Editor::Transpose() out of Editor class This patch moves |Editor::Transpose()| out of |Editor| class as preparation of expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor| class simpler for improving code health. Following patch will expand |Transpose()| into |ExecutTranspose()|. Bug: 672405 Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6 Reviewed-on: https://chromium-review.googlesource.com/583880 Reviewed-by: Xiaocheng Hu <[email protected]> Commit-Queue: Yoshifumi Inoue <[email protected]> Cr-Commit-Position: refs/heads/master@{#489518} 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: const GURL& DownloadItemImpl::GetOriginalUrl() const { return request_info_.url_chain.empty() ? GURL::EmptyGURL() : request_info_.url_chain.front(); } Commit Message: Downloads : Fixed an issue of opening incorrect download file When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download. Bug: 793620 Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8 Reviewed-on: https://chromium-review.googlesource.com/826477 Reviewed-by: David Trainor <[email protected]> Reviewed-by: Xing Liu <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Commit-Queue: Shakti Sahu <[email protected]> Cr-Commit-Position: refs/heads/master@{#525810} 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: static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx, struct iw_exif_state *e, iw_uint32 ifd) { unsigned int tag_count; unsigned int i; unsigned int tag_pos; unsigned int tag_id; unsigned int v; double v_dbl; if(ifd<8 || ifd>e->d_len-18) return; tag_count = iw_get_ui16_e(&e->d[ifd],e->endian); if(tag_count>1000) return; // Sanity check. for(i=0;i<tag_count;i++) { tag_pos = ifd+2+i*12; if(tag_pos+12 > e->d_len) return; // Avoid overruns. tag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian); switch(tag_id) { case 274: // 274 = Orientation if(get_exif_tag_int_value(e,tag_pos,&v)) { rctx->exif_orientation = v; } break; case 296: // 296 = ResolutionUnit if(get_exif_tag_int_value(e,tag_pos,&v)) { rctx->exif_density_unit = v; } break; case 282: // 282 = XResolution if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) { rctx->exif_density_x = v_dbl; } break; case 283: // 283 = YResolution if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) { rctx->exif_density_y = v_dbl; } break; } } } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125 Target: 1 Example 2: Code: bool BrowserInit::LaunchWithProfile::CheckIfAutoLaunched(Profile* profile) { #if defined(OS_WIN) if (!auto_launch_trial::IsInAutoLaunchGroup()) return false; int infobar_shown = profile->GetPrefs()->GetInteger(prefs::kShownAutoLaunchInfobar); if (infobar_shown >= kMaxInfobarShown) return false; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kAutoLaunchAtStartup) || first_run::IsChromeFirstRun()) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&CheckAutoLaunchCallback)); return true; } #endif return false; } 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 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 pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr) { int c; uchar buf[2]; if ((c = jas_stream_getc(in)) == EOF) { goto error; } buf[0] = c; if ((c = jas_stream_getc(in)) == EOF) { goto error; } buf[1] = c; hdr->magic = buf[0] << 8 | buf[1]; if (hdr->magic != PGX_MAGIC) { jas_eprintf("invalid PGX signature\n"); goto error; } if ((c = pgx_getc(in)) == EOF || !isspace(c)) { goto error; } if (pgx_getbyteorder(in, &hdr->bigendian)) { jas_eprintf("cannot get byte order\n"); goto error; } if (pgx_getsgnd(in, &hdr->sgnd)) { jas_eprintf("cannot get signedness\n"); goto error; } if (pgx_getuint32(in, &hdr->prec)) { jas_eprintf("cannot get precision\n"); goto error; } if (pgx_getuint32(in, &hdr->width)) { jas_eprintf("cannot get width\n"); goto error; } if (pgx_getuint32(in, &hdr->height)) { jas_eprintf("cannot get height\n"); goto error; } return 0; error: return -1; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FaviconSource::SendDefaultResponse(int request_id) { if (!default_favicon_.get()) { default_favicon_ = ResourceBundle::GetSharedInstance().LoadDataResourceBytes( IDR_DEFAULT_FAVICON); } SendResponse(request_id, default_favicon_); } Commit Message: ntp4: show larger favicons in most visited page extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe). BUG=none TEST=manual Review URL: http://codereview.chromium.org/7300017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb) { if (skb_cow(skb, skb_headroom(skb)) < 0) { kfree_skb(skb); return NULL; } memmove(skb->data - ETH_HLEN, skb->data - skb->mac_len - VLAN_HLEN, 2 * ETH_ALEN); skb->mac_header += VLAN_HLEN; return skb; } Commit Message: tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs __sock_recv_timestamp can be called for both normal skbs (for receive timestamps) and for skbs on the error queue (for transmit timestamps). Commit 1c885808e456 (tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING) assumes any skb passed to __sock_recv_timestamp are from the error queue, containing OPT_STATS in the content of the skb. This results in accessing invalid memory or generating junk data. To fix this, set skb->pkt_type to PACKET_OUTGOING for packets on the error queue. This is safe because on the receive path on local sockets skb->pkt_type is never set to PACKET_OUTGOING. With that, copy OPT_STATS from a packet, only if its pkt_type is PACKET_OUTGOING. 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: 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 assoc_array_rcu_cleanup(struct rcu_head *head) { struct assoc_array_edit *edit = container_of(head, struct assoc_array_edit, rcu); int i; pr_devel("-->%s()\n", __func__); if (edit->dead_leaf) edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf)); for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++) if (edit->excised_meta[i]) kfree(assoc_array_ptr_to_node(edit->excised_meta[i])); if (edit->excised_subtree) { BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree)); if (assoc_array_ptr_is_node(edit->excised_subtree)) { struct assoc_array_node *n = assoc_array_ptr_to_node(edit->excised_subtree); n->back_pointer = NULL; } else { struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(edit->excised_subtree); s->back_pointer = NULL; } assoc_array_destroy_subtree(edit->excised_subtree, edit->ops_for_excised_subtree); } kfree(edit); } Commit Message: KEYS: Fix termination condition in assoc array garbage collection This fixes CVE-2014-3631. It is possible for an associative array to end up with a shortcut node at the root of the tree if there are more than fan-out leaves in the tree, but they all crowd into the same slot in the lowest level (ie. they all have the same first nibble of their index keys). When assoc_array_gc() returns back up the tree after scanning some leaves, it can fall off of the root and crash because it assumes that the back pointer from a shortcut (after label ascend_old_tree) must point to a normal node - which isn't true of a shortcut node at the root. Should we find we're ascending rootwards over a shortcut, we should check to see if the backpointer is zero - and if it is, we have completed the scan. This particular bug cannot occur if the root node is not a shortcut - ie. if you have fewer than 17 keys in a keyring or if you have at least two keys that sit into separate slots (eg. a keyring and a non keyring). This can be reproduced by: ring=`keyctl newring bar @s` for ((i=1; i<=18; i++)); do last_key=`keyctl newring foo$i $ring`; done keyctl timeout $last_key 2 Doing this: echo 3 >/proc/sys/kernel/keys/gc_delay first will speed things up. If we do fall off of the top of the tree, we get the following oops: BUG: unable to handle kernel NULL pointer dereference at 0000000000000018 IP: [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540 PGD dae15067 PUD cfc24067 PMD 0 Oops: 0000 [#1] SMP Modules linked in: xt_nat xt_mark nf_conntrack_netbios_ns nf_conntrack_broadcast ip6t_rpfilter ip6t_REJECT xt_conntrack ebtable_nat ebtable_broute bridge stp llc ebtable_filter ebtables ip6table_ni CPU: 0 PID: 26011 Comm: kworker/0:1 Not tainted 3.14.9-200.fc20.x86_64 #1 Hardware name: Bochs Bochs, BIOS Bochs 01/01/2011 Workqueue: events key_garbage_collector task: ffff8800918bd580 ti: ffff8800aac14000 task.ti: ffff8800aac14000 RIP: 0010:[<ffffffff8136cea7>] [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540 RSP: 0018:ffff8800aac15d40 EFLAGS: 00010206 RAX: 0000000000000000 RBX: 0000000000000000 RCX: ffff8800aaecacc0 RDX: ffff8800daecf440 RSI: 0000000000000001 RDI: ffff8800aadc2bc0 RBP: ffff8800aac15da8 R08: 0000000000000001 R09: 0000000000000003 R10: ffffffff8136ccc7 R11: 0000000000000000 R12: 0000000000000000 R13: 0000000000000000 R14: 0000000000000070 R15: 0000000000000001 FS: 0000000000000000(0000) GS:ffff88011fc00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b CR2: 0000000000000018 CR3: 00000000db10d000 CR4: 00000000000006f0 Stack: ffff8800aac15d50 0000000000000011 ffff8800aac15db8 ffffffff812e2a70 ffff880091a00600 0000000000000000 ffff8800aadc2bc3 00000000cd42c987 ffff88003702df20 ffff88003702dfa0 0000000053b65c09 ffff8800aac15fd8 Call Trace: [<ffffffff812e2a70>] ? keyring_detect_cycle_iterator+0x30/0x30 [<ffffffff812e3e75>] keyring_gc+0x75/0x80 [<ffffffff812e1424>] key_garbage_collector+0x154/0x3c0 [<ffffffff810a67b6>] process_one_work+0x176/0x430 [<ffffffff810a744b>] worker_thread+0x11b/0x3a0 [<ffffffff810a7330>] ? rescuer_thread+0x3b0/0x3b0 [<ffffffff810ae1a8>] kthread+0xd8/0xf0 [<ffffffff810ae0d0>] ? insert_kthread_work+0x40/0x40 [<ffffffff816ffb7c>] ret_from_fork+0x7c/0xb0 [<ffffffff810ae0d0>] ? insert_kthread_work+0x40/0x40 Code: 08 4c 8b 22 0f 84 bf 00 00 00 41 83 c7 01 49 83 e4 fc 41 83 ff 0f 4c 89 65 c0 0f 8f 5a fe ff ff 48 8b 45 c0 4d 63 cf 49 83 c1 02 <4e> 8b 34 c8 4d 85 f6 0f 84 be 00 00 00 41 f6 c6 01 0f 84 92 RIP [<ffffffff8136cea7>] assoc_array_gc+0x2f7/0x540 RSP <ffff8800aac15d40> CR2: 0000000000000018 ---[ end trace 1129028a088c0cbd ]--- Signed-off-by: David Howells <[email protected]> Acked-by: Don Zickus <[email protected]> Signed-off-by: James Morris <[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: struct sctp_chunk *sctp_inq_pop(struct sctp_inq *queue) { struct sctp_chunk *chunk; sctp_chunkhdr_t *ch = NULL; /* The assumption is that we are safe to process the chunks * at this time. */ if ((chunk = queue->in_progress)) { /* There is a packet that we have been working on. * Any post processing work to do before we move on? */ if (chunk->singleton || chunk->end_of_packet || chunk->pdiscard) { sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; } else { /* Nothing to do. Next chunk in the packet, please. */ ch = (sctp_chunkhdr_t *) chunk->chunk_end; /* Force chunk->skb->data to chunk->chunk_end. */ skb_pull(chunk->skb, chunk->chunk_end - chunk->skb->data); /* Verify that we have at least chunk headers * worth of buffer left. */ if (skb_headlen(chunk->skb) < sizeof(sctp_chunkhdr_t)) { sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; } } } /* Do we need to take the next packet out of the queue to process? */ if (!chunk) { struct list_head *entry; /* Is the queue empty? */ if (list_empty(&queue->in_chunk_list)) return NULL; entry = queue->in_chunk_list.next; chunk = queue->in_progress = list_entry(entry, struct sctp_chunk, list); list_del_init(entry); /* This is the first chunk in the packet. */ chunk->singleton = 1; ch = (sctp_chunkhdr_t *) chunk->skb->data; chunk->data_accepted = 0; } chunk->chunk_hdr = ch; chunk->chunk_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length)); /* In the unlikely case of an IP reassembly, the skb could be * non-linear. If so, update chunk_end so that it doesn't go past * the skb->tail. */ if (unlikely(skb_is_nonlinear(chunk->skb))) { if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) chunk->chunk_end = skb_tail_pointer(chunk->skb); } skb_pull(chunk->skb, sizeof(sctp_chunkhdr_t)); chunk->subh.v = NULL; /* Subheader is no longer valid. */ if (chunk->chunk_end < skb_tail_pointer(chunk->skb)) { /* This is not a singleton */ chunk->singleton = 0; } else if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) { /* RFC 2960, Section 6.10 Bundling * * Partial chunks MUST NOT be placed in an SCTP packet. * If the receiver detects a partial chunk, it MUST drop * the chunk. * * Since the end of the chunk is past the end of our buffer * (which contains the whole packet, we can freely discard * the whole packet. */ sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; return NULL; } else { /* We are at the end of the packet, so mark the chunk * in case we need to send a SACK. */ chunk->end_of_packet = 1; } pr_debug("+++sctp_inq_pop+++ chunk:%p[%s], length:%d, skb->len:%d\n", chunk, sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)), ntohs(chunk->chunk_hdr->length), chunk->skb->len); return chunk; } Commit Message: net: sctp: fix remote memory pressure from excessive queueing This scenario is not limited to ASCONF, just taken as one example triggering the issue. When receiving ASCONF probes in the form of ... -------------- INIT[ASCONF; ASCONF_ACK] -------------> <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------ -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- ---- ASCONF_a; [ASCONF_b; ...; ASCONF_n;] JUNK ------> [...] ---- ASCONF_m; [ASCONF_o; ...; ASCONF_z;] JUNK ------> ... where ASCONF_a, ASCONF_b, ..., ASCONF_z are good-formed ASCONFs and have increasing serial numbers, we process such ASCONF chunk(s) marked with !end_of_packet and !singleton, since we have not yet reached the SCTP packet end. SCTP does only do verification on a chunk by chunk basis, as an SCTP packet is nothing more than just a container of a stream of chunks which it eats up one by one. We could run into the case that we receive a packet with a malformed tail, above marked as trailing JUNK. All previous chunks are here goodformed, so the stack will eat up all previous chunks up to this point. In case JUNK does not fit into a chunk header and there are no more other chunks in the input queue, or in case JUNK contains a garbage chunk header, but the encoded chunk length would exceed the skb tail, or we came here from an entirely different scenario and the chunk has pdiscard=1 mark (without having had a flush point), it will happen, that we will excessively queue up the association's output queue (a correct final chunk may then turn it into a response flood when flushing the queue ;)): I ran a simple script with incremental ASCONF serial numbers and could see the server side consuming excessive amount of RAM [before/after: up to 2GB and more]. The issue at heart is that the chunk train basically ends with !end_of_packet and !singleton markers and since commit 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet") therefore preventing an output queue flush point in sctp_do_sm() -> sctp_cmd_interpreter() on the input chunk (chunk = event_arg) even though local_cork is set, but its precedence has changed since then. In the normal case, the last chunk with end_of_packet=1 would trigger the queue flush to accommodate possible outgoing bundling. In the input queue, sctp_inq_pop() seems to do the right thing in terms of discarding invalid chunks. So, above JUNK will not enter the state machine and instead be released and exit the sctp_assoc_bh_rcv() chunk processing loop. It's simply the flush point being missing at loop exit. Adding a try-flush approach on the output queue might not work as the underlying infrastructure might be long gone at this point due to the side-effect interpreter run. One possibility, albeit a bit of a kludge, would be to defer invalid chunk freeing into the state machine in order to possibly trigger packet discards and thus indirectly a queue flush on error. It would surely be better to discard chunks as in the current, perhaps better controlled environment, but going back and forth, it's simply architecturally not possible. I tried various trailing JUNK attack cases and it seems to look good now. Joint work with Vlad Yasevich. Fixes: 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: bool Document::IsContextThread() const { return IsMainThread(); } Commit Message: Cleanup and remove dead code in SetFocusedElement This early-out was added in: https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc Back then, we applied fragment focus in LayoutUpdated() which could cause this issue. This got cleaned up in: https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2 so that focus is no longer applied after layout. +Cleanup: Goto considered harmful Bug: 795381 Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417 Commit-Queue: David Bokan <[email protected]> Reviewed-by: Stefan Zager <[email protected]> Cr-Commit-Position: refs/heads/master@{#641101} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GC_API void * GC_CALL GC_generic_malloc(size_t lb, int k) { void * result; DCL_LOCK_STATE; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); if (SMALL_OBJ(lb)) { LOCK(); result = GC_generic_malloc_inner((word)lb, k); UNLOCK(); } else { size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; LOCK(); result = (ptr_t)GC_alloc_large(lb_rounded, k, 0); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; UNLOCK(); if (init && !GC_debugging_started && 0 != result) { BZERO(result, n_blocks * HBLKSIZE); } } if (0 == result) { return((*GC_get_oom_fn())(lb)); } else { return(result); } } Commit Message: Fix allocation size overflows due to rounding. * malloc.c (GC_generic_malloc): Check if the allocation size is rounded to a smaller value. * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. 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 FragmentPaintPropertyTreeBuilder::UpdateOverflowClip() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsOverflowClip(object_) && !CanOmitOverflowClip(object_)) { ClipPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled() && object_.IsSVGForeignObject()) { state.clip_rect = ToClipRect(ToLayoutBox(object_).FrameRect()); } else if (object_.IsBox()) { state.clip_rect = ToClipRect(ToLayoutBox(object_).OverflowClipRect( context_.current.paint_offset)); state.clip_rect_excluding_overlay_scrollbars = ToClipRect(ToLayoutBox(object_).OverflowClipRect( context_.current.paint_offset, kExcludeOverlayScrollbarSizeForHitTesting)); } else { DCHECK(object_.IsSVGViewportContainer()); const auto& viewport_container = ToLayoutSVGViewportContainer(object_); state.clip_rect = FloatRoundedRect( viewport_container.LocalToSVGParentTransform().Inverse().MapRect( viewport_container.Viewport())); } const ClipPaintPropertyNode* existing = properties_->OverflowClip(); bool equal_ignoring_hit_test_rects = !!existing && existing->EqualIgnoringHitTestRects(context_.current.clip, state); OnUpdateClip(properties_->UpdateOverflowClip(context_.current.clip, std::move(state)), equal_ignoring_hit_test_rects); } else { OnClearClip(properties_->ClearOverflowClip()); } } if (auto* overflow_clip = properties_->OverflowClip()) context_.current.clip = overflow_clip; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID: Target: 1 Example 2: Code: void server_connect_init(SERVER_REC *server) { const char *str; g_return_if_fail(server != NULL); MODULE_DATA_INIT(server); server->type = module_get_uniq_id("SERVER", 0); server_ref(server); server->nick = g_strdup(server->connrec->nick); if (server->connrec->username == NULL || *server->connrec->username == '\0') { g_free_not_null(server->connrec->username); str = g_get_user_name(); if (*str == '\0') str = "unknown"; server->connrec->username = g_strdup(str); } if (server->connrec->realname == NULL || *server->connrec->realname == '\0') { g_free_not_null(server->connrec->realname); str = g_get_real_name(); if (*str == '\0') str = server->connrec->username; server->connrec->realname = g_strdup(str); } server->tag = server_create_tag(server->connrec); server->connect_tag = -1; } Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564 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 venc_dev::venc_set_perf_mode(OMX_U32 mode) { struct v4l2_control control; if (mode && mode <= V4L2_MPEG_VIDC_VIDEO_PERF_POWER_SAVE) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_PERF_MODE; control.value = mode; DEBUG_PRINT_LOW("Going to set V4L2_CID_MPEG_VIDC_VIDEO_PERF_MODE"); if (ioctl(m_nDriver_fd, VIDIOC_S_CTRL, &control)) { DEBUG_PRINT_ERROR("Failed to set V4L2_CID_MPEG_VIDC_VIDEO_PERF_MODE"); return false; } return true; } else { DEBUG_PRINT_ERROR("Invalid mode set for V4L2_CID_MPEG_VIDC_VIDEO_PERF_MODE: %d", mode); return false; } } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 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: void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); sqr_add_c2(a,4,0,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,5,0,c3,c1,c2); sqr_add_c2(a,4,1,c3,c1,c2); sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); sqr_add_c2(a,4,2,c1,c2,c3); sqr_add_c2(a,5,1,c1,c2,c3); sqr_add_c2(a,6,0,c1,c2,c3); r[6]=c1; c1=0; sqr_add_c2(a,7,0,c2,c3,c1); sqr_add_c2(a,6,1,c2,c3,c1); sqr_add_c2(a,5,2,c2,c3,c1); sqr_add_c2(a,4,3,c2,c3,c1); r[7]=c2; c2=0; sqr_add_c(a,4,c3,c1,c2); sqr_add_c2(a,5,3,c3,c1,c2); sqr_add_c2(a,6,2,c3,c1,c2); sqr_add_c2(a,7,1,c3,c1,c2); r[8]=c3; c3=0; sqr_add_c2(a,7,2,c1,c2,c3); sqr_add_c2(a,6,3,c1,c2,c3); sqr_add_c2(a,5,4,c1,c2,c3); r[9]=c1; c1=0; sqr_add_c(a,5,c2,c3,c1); sqr_add_c2(a,6,4,c2,c3,c1); sqr_add_c2(a,7,3,c2,c3,c1); r[10]=c2; c2=0; sqr_add_c2(a,7,4,c3,c1,c2); sqr_add_c2(a,6,5,c3,c1,c2); r[11]=c3; c3=0; sqr_add_c(a,6,c1,c2,c3); sqr_add_c2(a,7,5,c1,c2,c3); r[12]=c1; c1=0; sqr_add_c2(a,7,6,c2,c3,c1); r[13]=c2; c2=0; sqr_add_c(a,7,c3,c1,c2); r[14]=c3; r[15]=c1; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <[email protected]> CWE ID: CWE-310 Target: 1 Example 2: Code: static inline void skb_drop_fraglist(struct sk_buff *skb) { skb_drop_list(&skb_shinfo(skb)->frag_list); } 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: int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr) { if (X509at_add1_attr(&req->req_info->attributes, attr)) return 1; return 0; } 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: int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index) { struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table; int i, err = 0; int free = -1; mutex_lock(&table->mutex); for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) { if (free < 0 && (table->refs[i] == 0)) { free = i; continue; } if (table->refs[i] && (vlan == (MLX4_VLAN_MASK & be32_to_cpu(table->entries[i])))) { /* Vlan already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } if (table->total == table->max) { /* No free vlan entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID); err = mlx4_set_port_vlan_table(dev, port, table->entries); if (unlikely(err)) { mlx4_warn(dev, "Failed adding vlan: %u\n", vlan); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; } Commit Message: mlx4_en: Fix out of bounds array access When searching for a free entry in either mlx4_register_vlan() or mlx4_register_mac(), and there is no free entry, the loop terminates without updating the local variable free thus causing out of array bounds access. Fix this by adding a proper check outside the loop. Signed-off-by: Eli Cohen <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct km_event c; int err = - EINVAL; u32 mark = 0; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct nlattr *rp = attrs[XFRMA_REPLAY_VAL]; struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL]; struct nlattr *lt = attrs[XFRMA_LTIME_VAL]; if (!lt && !rp && !re) return err; /* pedantic mode - thou shalt sayeth replaceth */ if (!(nlh->nlmsg_flags&NLM_F_REPLACE)) return err; mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family); if (x == NULL) return -ESRCH; if (x->km.state != XFRM_STATE_VALID) goto out; err = xfrm_replay_verify_len(x->replay_esn, rp); if (err) goto out; spin_lock_bh(&x->lock); xfrm_update_ae_params(x, attrs); spin_unlock_bh(&x->lock); c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.data.aevent = XFRM_AE_CU; km_state_notify(x, &c); err = 0; out: xfrm_state_put(x); return err; } Commit Message: xfrm_user: return error pointer instead of NULL When dump_one_state() returns an error, e.g. because of a too small buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL instead of an error pointer. But its callers expect an error pointer and therefore continue to operate on a NULL skbuff. This could lead to a privilege escalation (execution of user code in kernel context) if the attacker has CAP_NET_ADMIN and is able to map address 0. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xfs_inode_buf_write_verify( struct xfs_buf *bp) { xfs_inode_buf_verify(bp, false); } Commit Message: xfs: More robust inode extent count validation When the inode is in extent format, it can't have more extents that fit in the inode fork. We don't currenty check this, and so this corruption goes unnoticed by the inode verifiers. This can lead to crashes operating on invalid in-memory structures. Attempts to access such a inode will now error out in the verifier rather than allowing modification operations to proceed. Reported-by: Wen Xu <[email protected]> Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Darrick J. Wong <[email protected]> [darrick: fix a typedef, add some braces and breaks to shut up compiler warnings] Signed-off-by: Darrick J. Wong <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: const unsigned char* Track::GetCodecPrivate(size_t& size) const { size = m_info.codecPrivateSize; return m_info.codecPrivate; } 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 int ipx_create(struct net *net, struct socket *sock, int protocol, int kern) { int rc = -ESOCKTNOSUPPORT; struct sock *sk; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; /* * SPX support is not anymore in the kernel sources. If you want to * ressurrect it, completing it and making it understand shared skbs, * be fully multithreaded, etc, grab the sources in an early 2.5 kernel * tree. */ if (sock->type != SOCK_DGRAM) goto out; rc = -ENOMEM; sk = sk_alloc(net, PF_IPX, GFP_KERNEL, &ipx_proto); if (!sk) goto out; sk_refcnt_debug_inc(sk); sock_init_data(sock, sk); sk->sk_no_check = 1; /* Checksum off by default */ sock->ops = &ipx_dgram_ops; rc = 0; out: return rc; } 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: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; } Commit Message: Fixed crash in elf.c with 32bit r2 when shdr->sh_size > max size_t 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 ip_options_get_from_user(struct net *net, struct ip_options **optp, unsigned char __user *data, int optlen) { struct ip_options *opt = ip_options_get_alloc(optlen); if (!opt) return -ENOMEM; if (optlen && copy_from_user(opt->__data, data, optlen)) { kfree(opt); return -EFAULT; } return ip_options_get_finish(net, optp, opt, optlen); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_user_sec_ctx *uctx; if (!rt) return 0; uctx = nla_data(rt); return security_xfrm_policy_alloc(&pol->security, uctx, GFP_KERNEL); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: v8::Local<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> getter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "get")).ToLocal(&getter) || !getter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(getter), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::GetterContext, attributeName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79 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: image_transform_png_set_@_add(image_transform *this, PNG_CONST image_transform **that, char *name, size_t sizeof_name, size_t *pos, png_byte colour_type, png_byte bit_depth) { this->next = *that; *that = this; *pos = safecat(name, sizeof_name, *pos, " +@"); return 1; } 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 sctp_disposition_t sctp_sf_do_unexpected_init( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_disposition_t retval; struct sctp_chunk *chunk = arg; struct sctp_chunk *repl; struct sctp_association *new_asoc; struct sctp_chunk *err_chunk; struct sctp_packet *packet; sctp_unrecognized_param_t *unk_param; int len; /* 6.10 Bundling * An endpoint MUST NOT bundle INIT, INIT ACK or * SHUTDOWN COMPLETE with any other chunks. * * IG Section 2.11.2 * Furthermore, we require that the receiver of an INIT chunk MUST * enforce these rules by silently discarding an arriving packet * with an INIT chunk that is bundled with other chunks. */ if (!chunk->singleton) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* 3.1 A packet containing an INIT chunk MUST have a zero Verification * Tag. */ if (chunk->sctp_hdr->vtag != 0) return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); /* Make sure that the INIT chunk has a valid length. * In this case, we generate a protocol violation since we have * an association established. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Grab the INIT header. */ chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data; /* Tag the variable length parameters. */ chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t)); /* Verify the INIT chunk before processing it. */ err_chunk = NULL; if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type, (sctp_init_chunk_t *)chunk->chunk_hdr, chunk, &err_chunk)) { /* This chunk contains fatal error. It is to be discarded. * Send an ABORT, with causes if there is any. */ if (err_chunk) { packet = sctp_abort_pkt_new(net, ep, asoc, arg, (__u8 *)(err_chunk->chunk_hdr) + sizeof(sctp_chunkhdr_t), ntohs(err_chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t)); if (packet) { sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); retval = SCTP_DISPOSITION_CONSUME; } else { retval = SCTP_DISPOSITION_NOMEM; } goto cleanup; } else { return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); } } /* * Other parameters for the endpoint SHOULD be copied from the * existing parameters of the association (e.g. number of * outbound streams) into the INIT ACK and cookie. * FIXME: We are copying parameters from the endpoint not the * association. */ new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC); if (!new_asoc) goto nomem; if (sctp_assoc_set_bind_addr_from_ep(new_asoc, sctp_scope(sctp_source(chunk)), GFP_ATOMIC) < 0) goto nomem; /* In the outbound INIT ACK the endpoint MUST copy its current * Verification Tag and Peers Verification tag into a reserved * place (local tie-tag and per tie-tag) within the state cookie. */ if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), (sctp_init_chunk_t *)chunk->chunk_hdr, GFP_ATOMIC)) goto nomem; /* Make sure no new addresses are being added during the * restart. Do not do this check for COOKIE-WAIT state, * since there are no peer addresses to check against. * Upon return an ABORT will have been sent if needed. */ if (!sctp_state(asoc, COOKIE_WAIT)) { if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) { retval = SCTP_DISPOSITION_CONSUME; goto nomem_retval; } } sctp_tietags_populate(new_asoc, asoc); /* B) "Z" shall respond immediately with an INIT ACK chunk. */ /* If there are errors need to be reported for unknown parameters, * make sure to reserve enough room in the INIT ACK for them. */ len = 0; if (err_chunk) { len = ntohs(err_chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t); } repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len); if (!repl) goto nomem; /* If there are errors need to be reported for unknown parameters, * include them in the outgoing INIT ACK as "Unrecognized parameter" * parameter. */ if (err_chunk) { /* Get the "Unrecognized parameter" parameter(s) out of the * ERROR chunk generated by sctp_verify_init(). Since the * error cause code for "unknown parameter" and the * "Unrecognized parameter" type is the same, we can * construct the parameters in INIT ACK by copying the * ERROR causes over. */ unk_param = (sctp_unrecognized_param_t *) ((__u8 *)(err_chunk->chunk_hdr) + sizeof(sctp_chunkhdr_t)); /* Replace the cause code with the "Unrecognized parameter" * parameter type. */ sctp_addto_chunk(repl, len, unk_param); } sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); /* * Note: After sending out INIT ACK with the State Cookie parameter, * "Z" MUST NOT allocate any resources for this new association. * Otherwise, "Z" will be vulnerable to resource attacks. */ sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); retval = SCTP_DISPOSITION_CONSUME; return retval; nomem: retval = SCTP_DISPOSITION_NOMEM; nomem_retval: if (new_asoc) sctp_association_free(new_asoc); cleanup: if (err_chunk) sctp_chunk_free(err_chunk); return retval; } Commit Message: net: sctp: fix remote memory pressure from excessive queueing This scenario is not limited to ASCONF, just taken as one example triggering the issue. When receiving ASCONF probes in the form of ... -------------- INIT[ASCONF; ASCONF_ACK] -------------> <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------ -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- ---- ASCONF_a; [ASCONF_b; ...; ASCONF_n;] JUNK ------> [...] ---- ASCONF_m; [ASCONF_o; ...; ASCONF_z;] JUNK ------> ... where ASCONF_a, ASCONF_b, ..., ASCONF_z are good-formed ASCONFs and have increasing serial numbers, we process such ASCONF chunk(s) marked with !end_of_packet and !singleton, since we have not yet reached the SCTP packet end. SCTP does only do verification on a chunk by chunk basis, as an SCTP packet is nothing more than just a container of a stream of chunks which it eats up one by one. We could run into the case that we receive a packet with a malformed tail, above marked as trailing JUNK. All previous chunks are here goodformed, so the stack will eat up all previous chunks up to this point. In case JUNK does not fit into a chunk header and there are no more other chunks in the input queue, or in case JUNK contains a garbage chunk header, but the encoded chunk length would exceed the skb tail, or we came here from an entirely different scenario and the chunk has pdiscard=1 mark (without having had a flush point), it will happen, that we will excessively queue up the association's output queue (a correct final chunk may then turn it into a response flood when flushing the queue ;)): I ran a simple script with incremental ASCONF serial numbers and could see the server side consuming excessive amount of RAM [before/after: up to 2GB and more]. The issue at heart is that the chunk train basically ends with !end_of_packet and !singleton markers and since commit 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet") therefore preventing an output queue flush point in sctp_do_sm() -> sctp_cmd_interpreter() on the input chunk (chunk = event_arg) even though local_cork is set, but its precedence has changed since then. In the normal case, the last chunk with end_of_packet=1 would trigger the queue flush to accommodate possible outgoing bundling. In the input queue, sctp_inq_pop() seems to do the right thing in terms of discarding invalid chunks. So, above JUNK will not enter the state machine and instead be released and exit the sctp_assoc_bh_rcv() chunk processing loop. It's simply the flush point being missing at loop exit. Adding a try-flush approach on the output queue might not work as the underlying infrastructure might be long gone at this point due to the side-effect interpreter run. One possibility, albeit a bit of a kludge, would be to defer invalid chunk freeing into the state machine in order to possibly trigger packet discards and thus indirectly a queue flush on error. It would surely be better to discard chunks as in the current, perhaps better controlled environment, but going back and forth, it's simply architecturally not possible. I tried various trailing JUNK attack cases and it seems to look good now. Joint work with Vlad Yasevich. Fixes: 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Vlad Yasevich <[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: spawn_sh(WebKitWebView *web_view, GArray *argv, GString *result) { (void)web_view; (void)result; if (!uzbl.behave.shell_cmd) { g_printerr ("spawn_sh: shell_cmd is not set!\n"); return; } guint i; gchar *spacer = g_strdup(""); g_array_insert_val(argv, 1, spacer); gchar **cmd = split_quoted(uzbl.behave.shell_cmd, TRUE); for (i = 1; i < g_strv_length(cmd); i++) g_array_prepend_val(argv, cmd[i]); if (cmd) run_command(cmd[0], g_strv_length(cmd) + 1, (const gchar **) argv->data, FALSE, NULL); g_free (spacer); g_strfreev (cmd); } Commit Message: disable Uzbl javascript object because of security problem. 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 ixheaacd_shiftrountine_with_rnd_hq(WORD32 *qmf_real, WORD32 *qmf_imag, WORD32 *filter_states, WORD32 len, WORD32 shift) { WORD32 *filter_states_rev = filter_states + len; WORD32 treal, timag; WORD32 j; for (j = (len - 1); j >= 0; j -= 2) { WORD32 r1, r2, i1, i2; i2 = qmf_imag[j]; r2 = qmf_real[j]; r1 = *qmf_real++; i1 = *qmf_imag++; timag = ixheaacd_add32(i1, r1); timag = (ixheaacd_shl32_sat(timag, shift)); filter_states_rev[j] = timag; treal = ixheaacd_sub32(i2, r2); treal = (ixheaacd_shl32_sat(treal, shift)); filter_states[j] = treal; treal = ixheaacd_sub32(i1, r1); treal = (ixheaacd_shl32_sat(treal, shift)); *filter_states++ = treal; timag = ixheaacd_add32(i2, r2); timag = (ixheaacd_shl32_sat(timag, shift)); *filter_states_rev++ = timag; } } Commit Message: Fix for stack corruption in esbr Bug: 110769924 Test: poc from bug before/after Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e (cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a) (cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50) CWE ID: CWE-787 Target: 1 Example 2: Code: GF_Err stss_dump(GF_Box *a, FILE * trace) { GF_SyncSampleBox *p; u32 i; p = (GF_SyncSampleBox *)a; gf_isom_box_dump_start(a, "SyncSampleBox", trace); fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries); if (!p->sampleNumbers && p->size) { fprintf(trace, "<!--Warning: No Key Frames indications-->\n"); } else { for (i=0; i<p->nb_entries; i++) { fprintf(trace, "<SyncSampleEntry sampleNumber=\"%u\"/>\n", p->sampleNumbers[i]); } } if (!p->size) { fprintf(trace, "<SyncSampleEntry sampleNumber=\"\"/>\n"); } gf_isom_box_dump_done("SyncSampleBox", a, trace); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int caif_stream_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int copied = 0; int target; int err = 0; long timeo; err = -EOPNOTSUPP; if (flags&MSG_OOB) goto out; msg->msg_namelen = 0; /* * Lock the socket to prevent queue disordering * while sleeps in memcpy_tomsg */ err = -EAGAIN; if (sk->sk_state == CAIF_CONNECTING) goto out; caif_read_lock(sk); target = sock_rcvlowat(sk, flags&MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT); do { int chunk; struct sk_buff *skb; lock_sock(sk); skb = skb_dequeue(&sk->sk_receive_queue); caif_check_flow_release(sk); if (skb == NULL) { if (copied >= target) goto unlock; /* * POSIX 1003.1g mandates this order. */ err = sock_error(sk); if (err) goto unlock; err = -ECONNRESET; if (sk->sk_shutdown & RCV_SHUTDOWN) goto unlock; err = -EPIPE; if (sk->sk_state != CAIF_CONNECTED) goto unlock; if (sock_flag(sk, SOCK_DEAD)) goto unlock; release_sock(sk); err = -EAGAIN; if (!timeo) break; caif_read_unlock(sk); timeo = caif_stream_data_wait(sk, timeo); if (signal_pending(current)) { err = sock_intr_errno(timeo); goto out; } caif_read_lock(sk); continue; unlock: release_sock(sk); break; } release_sock(sk); chunk = min_t(unsigned int, skb->len, size); if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (copied == 0) copied = -EFAULT; break; } copied += chunk; size -= chunk; /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { skb_pull(skb, chunk); /* put the skb back if we didn't use it up. */ if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { /* * It is questionable, see note in unix_dgram_recvmsg. */ /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); caif_read_unlock(sk); out: return copied ? : err; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 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: memory_handle(const media::BitstreamBuffer& input) { base::SharedMemoryHandle input_handle = base::SharedMemory::DuplicateHandle(input.handle()); if (!base::SharedMemory::IsHandleValid(input_handle)) { DLOG(ERROR) << "Failed to duplicate handle of BitstreamBuffer"; return mojo::ScopedSharedBufferHandle(); } return mojo::WrapSharedMemoryHandle(input_handle, input.size(), true /* read_only */); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 1 Example 2: Code: cmd_http_rxbody(CMD_ARGS) { struct http *hp; (void)cmd; (void)vl; CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC); ONLY_SERVER(hp, av); assert(!strcmp(av[0], "rxbody")); av++; for(; *av != NULL; av++) vtc_log(hp->vl, 0, "Unknown http rxreq spec: %s\n", *av); http_swallow_body(hp, hp->req, 0); vtc_log(hp->vl, 4, "bodylen = %s", hp->bodylen); } Commit Message: Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] [email protected] CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool CheckClientDownloadRequest::ShouldUploadBinary( DownloadCheckResultReason reason) { bool upload_for_dlp = ShouldUploadForDlpScan(); bool upload_for_malware = ShouldUploadForMalwareScan(reason); if (!upload_for_dlp && !upload_for_malware) return false; return !!Profile::FromBrowserContext(GetBrowserContext()); } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20 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: iakerb_gss_init_sec_context(OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { OM_uint32 major_status = GSS_S_FAILURE; krb5_error_code code; iakerb_ctx_id_t ctx; krb5_gss_cred_id_t kcred; krb5_gss_name_t kname; krb5_boolean cred_locked = FALSE; int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); if (initialContextToken) { code = iakerb_alloc_context(&ctx); if (code != 0) { *minor_status = code; goto cleanup; } if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) { major_status = iakerb_gss_acquire_cred(minor_status, NULL, GSS_C_INDEFINITE, GSS_C_NULL_OID_SET, GSS_C_INITIATE, &ctx->defcred, NULL, NULL); if (GSS_ERROR(major_status)) goto cleanup; claimant_cred_handle = ctx->defcred; } } else { ctx = (iakerb_ctx_id_t)*context_handle; if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) claimant_cred_handle = ctx->defcred; } kname = (krb5_gss_name_t)target_name; major_status = kg_cred_resolve(minor_status, ctx->k5c, claimant_cred_handle, target_name); if (GSS_ERROR(major_status)) goto cleanup; cred_locked = TRUE; kcred = (krb5_gss_cred_id_t)claimant_cred_handle; major_status = GSS_S_FAILURE; if (initialContextToken) { code = iakerb_get_initial_state(ctx, kcred, kname, time_req, &ctx->state); if (code != 0) { *minor_status = code; goto cleanup; } *context_handle = (gss_ctx_id_t)ctx; } if (ctx->state != IAKERB_AP_REQ) { /* We need to do IAKERB. */ code = iakerb_initiator_step(ctx, kcred, kname, time_req, input_token, output_token); if (code == KRB5_BAD_MSIZE) major_status = GSS_S_DEFECTIVE_TOKEN; if (code != 0) { *minor_status = code; goto cleanup; } } if (ctx->state == IAKERB_AP_REQ) { krb5_gss_ctx_ext_rec exts; if (cred_locked) { k5_mutex_unlock(&kcred->lock); cred_locked = FALSE; } iakerb_make_exts(ctx, &exts); if (ctx->gssc == GSS_C_NO_CONTEXT) input_token = GSS_C_NO_BUFFER; /* IAKERB is finished, or we skipped to Kerberos directly. */ major_status = krb5_gss_init_sec_context_ext(minor_status, (gss_cred_id_t) kcred, &ctx->gssc, target_name, (gss_OID)gss_mech_iakerb, req_flags, time_req, input_chan_bindings, input_token, NULL, output_token, ret_flags, time_rec, &exts); if (major_status == GSS_S_COMPLETE) { *context_handle = ctx->gssc; ctx->gssc = GSS_C_NO_CONTEXT; iakerb_release_context(ctx); } if (actual_mech_type != NULL) *actual_mech_type = (gss_OID)gss_mech_krb5; } else { if (actual_mech_type != NULL) *actual_mech_type = (gss_OID)gss_mech_iakerb; if (ret_flags != NULL) *ret_flags = 0; if (time_rec != NULL) *time_rec = 0; major_status = GSS_S_CONTINUE_NEEDED; } cleanup: if (cred_locked) k5_mutex_unlock(&kcred->lock); if (initialContextToken && GSS_ERROR(major_status)) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return major_status; } Commit Message: Fix IAKERB context aliasing bugs [CVE-2015-2696] The IAKERB mechanism currently replaces its context handle with the krb5 mechanism handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the IAKERB context structure after context establishment and add new IAKERB entry points to refer to it with that type. Add initiate and established flags to the IAKERB context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2696: In MIT krb5 1.9 and later, applications which call gss_inquire_context() on a partially-established IAKERB context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted IAKERB packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18 Target: 1 Example 2: Code: void show_state_filter(unsigned long state_filter) { struct task_struct *g, *p; #if BITS_PER_LONG == 32 printk(KERN_INFO " task PC stack pid father\n"); #else printk(KERN_INFO " task PC stack pid father\n"); #endif rcu_read_lock(); do_each_thread(g, p) { /* * reset the NMI-timeout, listing all files on a slow * console might take a lot of time: */ touch_nmi_watchdog(); if (!state_filter || (p->state & state_filter)) sched_show_task(p); } while_each_thread(g, p); touch_all_softlockup_watchdogs(); #ifdef CONFIG_SCHED_DEBUG sysrq_sched_debug_show(); #endif rcu_read_unlock(); /* * Only show locks if all tasks are dumped: */ if (!state_filter) debug_show_all_locks(); } Commit Message: sched: Fix information leak in sys_sched_getattr() We're copying the on-stack structure to userspace, but forgot to give the right number of bytes to copy. This allows the calling process to obtain up to PAGE_SIZE bytes from the stack (and possibly adjacent kernel memory). This fix copies only as much as we actually have on the stack (attr->size defaults to the size of the struct) and leaves the rest of the userspace-provided buffer untouched. Found using kmemcheck + trinity. Fixes: d50dde5a10f30 ("sched: Add new scheduler syscalls to support an extended scheduling parameters ABI") Cc: Dario Faggioli <[email protected]> Cc: Juri Lelli <[email protected]> Cc: Ingo Molnar <[email protected]> Signed-off-by: Vegard Nossum <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Thomas Gleixner <[email protected]> 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: tt_cmap14_char_variants( TT_CMap cmap, FT_Memory memory, FT_UInt32 charCode ) { TT_CMap14 cmap14 = (TT_CMap14) cmap; FT_UInt32 count = cmap14->num_selectors; FT_Byte* p = cmap->data + 10; FT_UInt32* q; if ( tt_cmap14_ensure( cmap14, ( count + 1 ), memory ) ) return NULL; for ( q = cmap14->results; count > 0; --count ) { FT_UInt32 varSel = TT_NEXT_UINT24( p ); FT_ULong defOff = TT_NEXT_ULONG( p ); FT_ULong nondefOff = TT_NEXT_ULONG( p ); if ( ( defOff != 0 && tt_cmap14_char_map_def_binary( cmap->data + defOff, charCode ) ) || ( nondefOff != 0 && tt_cmap14_char_map_nondef_binary( cmap->data + nondefOff, charCode ) != 0 ) ) { q[0] = varSel; q++; } } q[0] = 0; return cmap14->results; } 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: long long Segment::ParseHeaders() { long long total, available; const int status = m_pReader->Length(&total, &available); if (status < 0) // error return status; assert((total < 0) || (available <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; assert((segment_stop < 0) || (total < 0) || (segment_stop <= total)); assert((segment_stop < 0) || (m_pos <= segment_stop)); for (;;) { if ((total >= 0) && (m_pos >= total)) break; if ((segment_stop >= 0) && (m_pos >= segment_stop)) break; long long pos = m_pos; const long long element_start = pos; if ((pos + 1) > available) return (pos + 1); long len; long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return result; if (result > 0) // underflow (weird) return (pos + 1); if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) // error return id; if (id == 0x0F43B675) // Cluster ID break; pos += len; // consume ID if ((pos + 1) > available) return (pos + 1); result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return result; if (result > 0) // underflow (weird) return (pos + 1); if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return size; pos += len; // consume length of size of element const long long element_size = size + pos - element_start; if ((segment_stop >= 0) && ((pos + size) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; if (id == 0x0549A966) { // Segment Info ID if (m_pInfo) return E_FILE_FORMAT_INVALID; m_pInfo = new (std::nothrow) SegmentInfo(this, pos, size, element_start, element_size); if (m_pInfo == NULL) return -1; const long status = m_pInfo->Parse(); if (status) return status; } else if (id == 0x0654AE6B) { // Tracks ID if (m_pTracks) return E_FILE_FORMAT_INVALID; m_pTracks = new (std::nothrow) Tracks(this, pos, size, element_start, element_size); if (m_pTracks == NULL) return -1; const long status = m_pTracks->Parse(); if (status) return status; } else if (id == 0x0C53BB6B) { // Cues ID if (m_pCues == NULL) { m_pCues = new (std::nothrow) Cues(this, pos, size, element_start, element_size); if (m_pCues == NULL) return -1; } } else if (id == 0x014D9B74) { // SeekHead ID if (m_pSeekHead == NULL) { m_pSeekHead = new (std::nothrow) SeekHead(this, pos, size, element_start, element_size); if (m_pSeekHead == NULL) return -1; const long status = m_pSeekHead->Parse(); if (status) return status; } } else if (id == 0x0043A770) { // Chapters ID if (m_pChapters == NULL) { m_pChapters = new (std::nothrow) Chapters(this, pos, size, element_start, element_size); if (m_pChapters == NULL) return -1; const long status = m_pChapters->Parse(); if (status) return status; } } m_pos = pos + size; // consume payload } assert((segment_stop < 0) || (m_pos <= segment_stop)); if (m_pInfo == NULL) // TODO: liberalize this behavior return E_FILE_FORMAT_INVALID; if (m_pTracks == NULL) return E_FILE_FORMAT_INVALID; return 0; // success } 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 Target: 1 Example 2: Code: void Browser::ToggleFullscreenMode() { #if !defined(OS_MACOSX) if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) && window_->IsFullscreen()) return; #endif UserMetrics::RecordAction(UserMetricsAction("ToggleFullscreen"), profile_); window_->SetFullscreen(!window_->IsFullscreen()); #if !defined(OS_LINUX) UpdateCommandsForFullscreenMode(window_->IsFullscreen()); #endif } 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 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: tr (char const *trans, char c) { return trans ? trans[U(c)] : c; } 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: static int handle_vmread(struct kvm_vcpu *vcpu) { unsigned long field; u64 field_value; unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); gva_t gva = 0; if (!nested_vmx_check_permission(vcpu)) return 1; if (!nested_vmx_check_vmcs12(vcpu)) return kvm_skip_emulated_instruction(vcpu); /* Decode instruction info and find the field to read */ field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf)); /* Read the field, zero-extended to a u64 field_value */ if (vmcs12_read_any(vcpu, field, &field_value) < 0) { nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT); return kvm_skip_emulated_instruction(vcpu); } /* * Now copy part of this value to register or memory, as requested. * Note that the number of bits actually copied is 32 or 64 depending * on the guest's mode (32 or 64 bit), not on the given field's length. */ if (vmx_instruction_info & (1u << 10)) { kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf), field_value); } else { if (get_vmx_mem_address(vcpu, exit_qualification, vmx_instruction_info, true, &gva)) return 1; /* _system ok, as hardware has verified cpl=0 */ kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva, &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL); } nested_vmx_succeed(vcpu); return kvm_skip_emulated_instruction(vcpu); } Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions VMX instructions executed inside a L1 VM will always trigger a VM exit even when executed with cpl 3. This means we must perform the privilege check in software. Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks") Cc: [email protected] Signed-off-by: Felix Wilhelm <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: Target: 1 Example 2: Code: png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) { png_color palette[PNG_MAX_PALETTE_LENGTH]; int num, i; #ifdef PNG_POINTER_INDEXING_SUPPORTED png_colorp pal_ptr; #endif png_debug(1, "in png_handle_PLTE"); if (!(png_ptr->mode & PNG_HAVE_IHDR)) png_error(png_ptr, "Missing IHDR before PLTE"); else if (png_ptr->mode & PNG_HAVE_IDAT) { png_warning(png_ptr, "Invalid PLTE after IDAT"); png_crc_finish(png_ptr, length); return; } else if (png_ptr->mode & PNG_HAVE_PLTE) png_error(png_ptr, "Duplicate PLTE chunk"); png_ptr->mode |= PNG_HAVE_PLTE; if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR)) { png_warning(png_ptr, "Ignoring PLTE chunk in grayscale PNG"); png_crc_finish(png_ptr, length); return; } #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { png_crc_finish(png_ptr, length); return; } #endif if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3) { if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { png_warning(png_ptr, "Invalid palette chunk"); png_crc_finish(png_ptr, length); return; } else { png_error(png_ptr, "Invalid palette chunk"); } } num = (int)length / 3; #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); pal_ptr->red = buf[0]; pal_ptr->green = buf[1]; pal_ptr->blue = buf[2]; } #else for (i = 0; i < num; i++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); /* Don't depend upon png_color being any order */ palette[i].red = buf[0]; palette[i].green = buf[1]; palette[i].blue = buf[2]; } #endif /* If we actually NEED the PLTE chunk (ie for a paletted image), we do * whatever the normal CRC configuration tells us. However, if we * have an RGB image, the PLTE can be considered ancillary, so * we will act as though it is. */ #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) #endif { png_crc_finish(png_ptr, 0); } #ifndef PNG_READ_OPT_PLTE_SUPPORTED else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */ { /* If we don't want to use the data from an ancillary chunk, we have two options: an error abort, or a warning and we ignore the data in this chunk (which should be OK, since it's considered ancillary for a RGB or RGBA image). */ if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE)) { if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) { png_chunk_error(png_ptr, "CRC error"); } else { png_chunk_warning(png_ptr, "CRC error"); return; } } /* Otherwise, we (optionally) emit a warning and use the chunk. */ else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) { png_chunk_warning(png_ptr, "CRC error"); } } #endif png_set_PLTE(png_ptr, info_ptr, palette, num); #ifdef PNG_READ_tRNS_SUPPORTED if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS)) { if (png_ptr->num_trans > (png_uint_16)num) { png_warning(png_ptr, "Truncating incorrect tRNS chunk length"); png_ptr->num_trans = (png_uint_16)num; } if (info_ptr->num_trans > (png_uint_16)num) { png_warning(png_ptr, "Truncating incorrect info tRNS chunk length"); info_ptr->num_trans = (png_uint_16)num; } } } #endif } Commit Message: Pull follow-up tweak from upstream. BUG=116162 Review URL: http://codereview.chromium.org/9546033 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125311 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: error::Error GLES2DecoderPassthroughImpl::DoScheduleDCLayerCHROMIUM( GLuint y_texture_id, GLuint uv_texture_id, GLint z_order, GLint content_x, GLint content_y, GLint content_width, GLint content_height, GLint quad_x, GLint quad_y, GLint quad_width, GLint quad_height, GLfloat transform_c1r1, GLfloat transform_c2r1, GLfloat transform_c1r2, GLfloat transform_c2r2, GLfloat transform_tx, GLfloat transform_ty, GLboolean is_clipped, GLint clip_x, GLint clip_y, GLint clip_width, GLint clip_height, GLuint protected_video_type) { if (protected_video_type > static_cast<GLuint>(ui::ProtectedVideoType::kMaxValue)) { InsertError(GL_INVALID_VALUE, "invalid protected video type"); return error::kNoError; } GLuint texture_ids[] = {y_texture_id, uv_texture_id}; scoped_refptr<gl::GLImage> images[2]; size_t i = 0; for (GLuint texture_id : texture_ids) { if (!texture_id) { InsertError(GL_INVALID_VALUE, "invalid texture"); return error::kNoError; } scoped_refptr<TexturePassthrough> passthrough_texture; if (!resources_->texture_object_map.GetServiceID(texture_id, &passthrough_texture)) { InsertError(GL_INVALID_VALUE, "unknown texture"); return error::kNoError; } DCHECK(passthrough_texture); gl::GLImage* image = passthrough_texture->GetLevelImage(passthrough_texture->target(), 0); if (!image) { InsertError(GL_INVALID_VALUE, "unsupported texture format"); return error::kNoError; } images[i++] = scoped_refptr<gl::GLImage>(image); } ui::DCRendererLayerParams params; params.y_image = std::move(images[0]); params.uv_image = std::move(images[1]); params.z_order = z_order; params.content_rect = gfx::Rect(content_x, content_y, content_width, content_height); params.quad_rect = gfx::Rect(quad_x, quad_y, quad_width, quad_height); params.transform = gfx::Transform(transform_c1r1, transform_c2r1, transform_c1r2, transform_c2r2, transform_tx, transform_ty); params.is_clipped = is_clipped; params.clip_rect = gfx::Rect(clip_x, clip_y, clip_width, clip_height); params.protected_video_type = static_cast<ui::ProtectedVideoType>(protected_video_type); if (!surface_->ScheduleDCLayer(params)) InsertError(GL_INVALID_OPERATION, "failed to schedule DCLayer"); 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 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 zrle_send_framebuffer_update(VncState *vs, int x, int y, int w, int h) { bool be = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG); size_t bytes; int zywrle_level; if (vs->zrle.type == VNC_ENCODING_ZYWRLE) { if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1 || vs->tight.quality == 9) { zywrle_level = 0; vs->zrle.type = VNC_ENCODING_ZRLE; } else if (vs->tight.quality < 3) { zywrle_level = 3; } else if (vs->tight.quality < 6) { zywrle_level = 2; } else { zywrle_level = 1; } } else { zywrle_level = 0; } vnc_zrle_start(vs); switch(vs->clientds.pf.bytes_per_pixel) { case 1: zrle_encode_8ne(vs, x, y, w, h, zywrle_level); break; case 2: if (vs->clientds.pf.gmax > 0x1F) { if (be) { zrle_encode_16be(vs, x, y, w, h, zywrle_level); } else { zrle_encode_16le(vs, x, y, w, h, zywrle_level); } } else { if (be) { zrle_encode_15be(vs, x, y, w, h, zywrle_level); } else { zrle_encode_15le(vs, x, y, w, h, zywrle_level); } } break; case 4: { bool fits_in_ls3bytes; bool fits_in_ms3bytes; fits_in_ls3bytes = ((vs->clientds.pf.rmax << vs->clientds.pf.rshift) < (1 << 24) && (vs->clientds.pf.gmax << vs->clientds.pf.gshift) < (1 << 24) && (vs->clientds.pf.bmax << vs->clientds.pf.bshift) < (1 << 24)); fits_in_ms3bytes = (vs->clientds.pf.rshift > 7 && vs->clientds.pf.gshift > 7 && vs->clientds.pf.bshift > 7); if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) { if (be) { zrle_encode_24abe(vs, x, y, w, h, zywrle_level); } else { zrle_encode_24ale(vs, x, y, w, h, zywrle_level); } } else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) { if (be) { zrle_encode_24bbe(vs, x, y, w, h, zywrle_level); } else { zrle_encode_24ble(vs, x, y, w, h, zywrle_level); } } else { if (be) { zrle_encode_32be(vs, x, y, w, h, zywrle_level); } else { zrle_encode_32le(vs, x, y, w, h, zywrle_level); } } } break; } vnc_zrle_stop(vs); bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION); vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type); vnc_write_u32(vs, bytes); vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset); return 1; } Commit Message: CWE ID: CWE-125 Target: 1 Example 2: Code: static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) { if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) return 0; if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) return 0; if (w < 0 || w >= env->prog->len) { verbose_linfo(env, t, "%d: ", t); verbose(env, "jump out of range from insn %d to %d\n", t, w); return -EINVAL; } if (e == BRANCH) /* mark branch target for state pruning */ env->explored_states[w] = STATE_LIST_MARK; if (insn_state[w] == 0) { /* tree-edge */ insn_state[t] = DISCOVERED | e; insn_state[w] = DISCOVERED; if (cur_stack >= env->prog->len) return -E2BIG; insn_stack[cur_stack++] = w; return 1; } else if ((insn_state[w] & 0xF0) == DISCOVERED) { verbose_linfo(env, t, "%d: ", t); verbose_linfo(env, w, "%d: ", w); verbose(env, "back-edge from insn %d to %d\n", t, w); return -EINVAL; } else if (insn_state[w] == EXPLORED) { /* forward- or cross-edge */ insn_state[t] = DISCOVERED | e; } else { verbose(env, "insn state internal bug\n"); return -EFAULT; } return 0; } Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") took care of rejecting alu op on pointer when e.g. pointer came from two different map values with different map properties such as value size, Jann reported that a case was not covered yet when a given alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from different branches where we would incorrectly try to sanitize based on the pointer's limit. Catch this corner case and reject the program instead. Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> CWE ID: CWE-189 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 RenderWidgetHostViewAura::ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection direction) { if (!GetTextInputManager() && !GetTextInputManager()->GetActiveWidget()) return false; GetTextInputManager()->GetActiveWidget()->UpdateTextDirection( direction == base::i18n::RIGHT_TO_LEFT ? blink::kWebTextDirectionRightToLeft : blink::kWebTextDirectionLeftToRight); GetTextInputManager()->GetActiveWidget()->NotifyTextDirection(); return true; } Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash RenderWidgetHostViewChildFrame expects its parent to have a valid FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even if DelegatedFrameHost is not used (in mus+ash). BUG=706553 [email protected] Review-Url: https://codereview.chromium.org/2847253003 Cr-Commit-Position: refs/heads/master@{#468179} 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 cJSON *cJSON_New_Item( void ) { cJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) ); if ( node ) memset( node, 0, sizeof(cJSON) ); return node; } 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 HTMLInputElement::setSelectionDirectionForBinding(const String& direction, ExceptionState& exceptionState) { if (!m_inputType->supportsSelectionAPI()) { exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."); return; } HTMLTextFormControlElement::setSelectionDirection(direction); } Commit Message: Add HTMLFormControlElement::supportsAutofocus to fix a FIXME comment. This virtual function should return true if the form control can hanlde 'autofocucs' attribute if it is specified. Note: HTMLInputElement::supportsAutofocus reuses InputType::isInteractiveContent because interactiveness is required for autofocus capability. BUG=none TEST=none; no behavior changes. Review URL: https://codereview.chromium.org/143343003 git-svn-id: svn://svn.chromium.org/blink/trunk@165432 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: void yr_re_node_destroy( RE_NODE* node) { if (node->left != NULL) yr_re_node_destroy(node->left); if (node->right != NULL) yr_re_node_destroy(node->right); if (node->type == RE_NODE_CLASS) yr_free(node->class_vector); yr_free(node); } Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier. CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadVICARImage(const ImageInfo *image_info, ExceptionInfo *exception) { char keyword[MaxTextExtent], value[MaxTextExtent]; Image *image; int c; MagickBooleanType status, value_expected; QuantumInfo *quantum_info; QuantumType quantum_type; register PixelPacket *q; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ c=ReadBlobByte(image); count=1; if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } length=0; image->columns=0; image->rows=0; while (isgraph(c) && ((image->columns == 0) || (image->rows == 0))) { if (isalnum(c) == MagickFalse) { c=ReadBlobByte(image); count++; } else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); count++; } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); count++; } if (value_expected == MagickFalse) continue; p=value; while (isalnum(c)) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); count++; } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"Label_RECORDS") == 0) length=(ssize_t) StringToLong(value); if (LocaleCompare(keyword,"LBLSIZE") == 0) length=(ssize_t) StringToLong(value); if (LocaleCompare(keyword,"RECORD_BYTES") == 0) image->columns=StringToUnsignedLong(value); if (LocaleCompare(keyword,"NS") == 0) image->columns=StringToUnsignedLong(value); if (LocaleCompare(keyword,"LINES") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"NL") == 0) image->rows=StringToUnsignedLong(value); } while (isspace((int) ((unsigned char) c)) != 0) { c=ReadBlobByte(image); count++; } } while (count < (ssize_t) length) { c=ReadBlobByte(image); count++; } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); image->depth=8; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read VICAR pixels. */ (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; count=ReadBlob(image,length,pixels); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: bshift (u64 * b0, u64 * b1) { u64 t[2], mask; t[0] = *b0; t[1] = *b1; mask = -(t[1] & 1) & 0xe1; mask <<= 56; *b1 = (t[1] >> 1) ^ (t[0] << 63); *b0 = (t[0] >> 1) ^ mask; } Commit Message: GCM: move look-up table to .data section and unshare between processes * cipher/cipher-gcm.c (ATTR_ALIGNED_64): New. (gcmR): Move to 'gcm_table' structure. (gcm_table): New structure for look-up table with counters before and after. (gcmR): New macro. (prefetch_table): Handle input with length not multiple of 256. (do_prefetch_tables): Modify pre- and post-table counters to unshare look-up table pages between processes. -- GnuPG-bug-id: 4541 Signed-off-by: Jussi Kivilinna <[email protected]> CWE ID: CWE-310 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: AuthenticatorTouchIdIncognitoBumpSheetModel::GetAcceptButtonLabel() const { #if defined(OS_MACOSX) return l10n_util::GetStringUTF16( IDS_WEBAUTHN_TOUCH_ID_INCOGNITO_BUMP_CONTINUE); #else return base::string16(); #endif // defined(OS_MACOSX) } Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break. As requested by UX in [1], allow long host names to split a title into two lines. This allows us to show more of the name before eliding, although sufficiently long names will still trigger elision. Screenshot at https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r. [1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12 Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34 Bug: 870892 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812 Auto-Submit: Adam Langley <[email protected]> Commit-Queue: Nina Satragno <[email protected]> Reviewed-by: Nina Satragno <[email protected]> Cr-Commit-Position: refs/heads/master@{#658114} 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 llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug("%p %zu\n", sk, len); lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err("Recv datagram failed state %d %d %d", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } sock_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; } Commit Message: NFC: llcp: fix info leaks via msg_name in llcp_sock_recvmsg() The code in llcp_sock_recvmsg() does not initialize all the members of struct sockaddr_nfc_llcp when filling the sockaddr info. Nor does it initialize the padding bytes of the structure inserted by the compiler for alignment. Also, if the socket is in state LLCP_CLOSED or is shutting down during receive the msg_namelen member is not updated to 0 while otherwise returning with 0, i.e. "success". The msg_namelen update is also missing for stream and seqpacket sockets which don't fill the sockaddr info. Both issues lead to the fact that the code will leak uninitialized kernel stack bytes in net/socket.c. Fix the first issue by initializing the memory used for sockaddr info with memset(0). Fix the second one by setting msg_namelen to 0 early. It will be updated later if we're going to fill the msg_name member. Cc: Lauro Ramos Venancio <[email protected]> Cc: Aloisio Almeida Jr <[email protected]> Cc: Samuel Ortiz <[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: static void EnableDisable(GLenum pname, bool enable) { if (enable) { glEnable(pname); } else { glDisable(pname); } } 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: static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MaxTextExtent], id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; StringInfo *profile; unsigned int signature; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MaxTextExtent; options=AcquireString((char *) NULL); signature=GetMagickSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MaxTextExtent; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse, options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (signature != GetMagickSignature((const StringInfo *) NULL)) ThrowReaderException(CacheError,"IncompatibleAPI"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); (void) ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=colormap; switch (depth) { default: ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: ... CWE ID: CWE-772 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: on_handler_appeared(GDBusConnection *connection, const gchar *name, const gchar *name_owner, gpointer user_data) { struct tcmur_handler *handler = user_data; struct dbus_info *info = handler->opaque; if (info->register_invocation) { info->connection = connection; tcmur_register_handler(handler); dbus_export_handler(handler, G_CALLBACK(on_dbus_check_config)); g_dbus_method_invocation_return_value(info->register_invocation, g_variant_new("(bs)", TRUE, "succeeded")); info->register_invocation = NULL; } } Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS Trying to unregister an internal handler ended up in a SEGFAULT, because the tcmur_handler->opaque was NULL. Way to reproduce: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow we use a newly introduced boolean in struct tcmur_handler for keeping track of external handlers. As suggested by mikechristie adjusting the public data structure is acceptable. CWE ID: CWE-476 Target: 1 Example 2: Code: void AudioHandler::UpdateChannelInterpretation() { channel_interpretation_ = new_channel_interpretation_; } Commit Message: Revert "Keep AudioHandlers alive until they can be safely deleted." This reverts commit 071df33edf2c8b4375fa432a83953359f93ea9e4. Reason for revert: This CL seems to cause an AudioNode leak on the Linux leak bot. The log is: https://ci.chromium.org/buildbot/chromium.webkit/WebKit%20Linux%20Trusty%20Leak/14252 * webaudio/AudioNode/audionode-connect-method-chaining.html * webaudio/Panner/pannernode-basic.html * webaudio/dom-exceptions.html Original change's description: > Keep AudioHandlers alive until they can be safely deleted. > > When an AudioNode is disposed, the handler is also disposed. But add > the handler to the orphan list so that the handler stays alive until > the context can safely delete it. If we don't do this, the handler > may get deleted while the audio thread is processing the handler (due > to, say, channel count changes and such). > > For an realtime context, always save the handler just in case the > audio thread is running after the context is marked as closed (because > the audio thread doesn't instantly stop when requested). > > For an offline context, only need to do this when the context is > running because the context is guaranteed to be stopped if we're not > in the running state. Hence, there's no possibility of deleting the > handler while the graph is running. > > This is a revert of > https://chromium-review.googlesource.com/c/chromium/src/+/860779, with > a fix for the leak. > > Bug: 780919 > Change-Id: Ifb6b5fcf3fbc373f5779256688731245771da33c > Reviewed-on: https://chromium-review.googlesource.com/862723 > Reviewed-by: Hongchan Choi <[email protected]> > Commit-Queue: Raymond Toy <[email protected]> > Cr-Commit-Position: refs/heads/master@{#528829} [email protected],[email protected] Change-Id: Ibf406bf6ed34ea1f03e86a64a1e5ba6de0970c6f No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 780919 Reviewed-on: https://chromium-review.googlesource.com/863402 Reviewed-by: Taiju Tsuiki <[email protected]> Commit-Queue: Taiju Tsuiki <[email protected]> Cr-Commit-Position: refs/heads/master@{#528888} 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 bt_status_t get_play_status_rsp(btrc_play_status_t play_status, uint32_t song_len, uint32_t song_pos) { tAVRC_RESPONSE avrc_rsp; CHECK_RC_CONNECTED memset(&(avrc_rsp.get_play_status), 0, sizeof(tAVRC_GET_PLAY_STATUS_RSP)); avrc_rsp.get_play_status.song_len = song_len; avrc_rsp.get_play_status.song_pos = song_pos; avrc_rsp.get_play_status.play_status = play_status; avrc_rsp.get_play_status.pdu = AVRC_PDU_GET_PLAY_STATUS; avrc_rsp.get_play_status.opcode = opcode_from_pdu(AVRC_PDU_GET_PLAY_STATUS); avrc_rsp.get_play_status.status = AVRC_STS_NO_ERROR; /* Send the response */ SEND_METAMSG_RSP(IDX_GET_PLAY_STATUS_RSP, &avrc_rsp); return BT_STATUS_SUCCESS; } 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 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: LocalSiteCharacteristicsWebContentsObserverTest() { scoped_feature_list_.InitAndEnableFeature( features::kSiteCharacteristicsDatabase); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Target: 1 Example 2: Code: void ZeroSuggestProvider::DeleteMatch(const AutocompleteMatch& match) { if (OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial()) { client()->GetPrefs()->SetString(omnibox::kZeroSuggestCachedResults, std::string()); } BaseSearchProvider::DeleteMatch(match); } 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: 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 GLES2DecoderImpl::ClearFramebufferForWorkaround(GLbitfield mask) { ScopedGLErrorSuppressor suppressor("GLES2DecoderImpl::ClearWorkaround", GetErrorState()); clear_framebuffer_blit_->ClearFramebuffer( this, gfx::Size(viewport_max_width_, viewport_max_height_), mask, state_.color_clear_red, state_.color_clear_green, state_.color_clear_blue, state_.color_clear_alpha, state_.depth_clear, state_.stencil_clear); } Commit Message: Implement immutable texture base/max level clamping It seems some drivers fail to handle that gracefully, so let's always clamp to be on the safe side. BUG=877874 TEST=test case in the bug, gpu_unittests [email protected] Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: I6d93cb9389ea70525df4604112223604577582a2 Reviewed-on: https://chromium-review.googlesource.com/1194994 Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#587264} 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: Track::Track( Segment* pSegment, long long element_start, long long element_size) : m_pSegment(pSegment), m_element_start(element_start), m_element_size(element_size), content_encoding_entries_(NULL), content_encoding_entries_end_(NULL) { } 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 struct inet_peer_base *family_to_base(int family) { return family == AF_INET ? &v4_peers : &v6_peers; } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct net *net = sock_net(cb->skb->sk); xfrm_policy_walk_done(walk, net); return 0; } 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: static void f2fs_put_super(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int i; f2fs_quota_off_umount(sb); /* prevent remaining shrinker jobs */ mutex_lock(&sbi->umount_mutex); /* * We don't need to do checkpoint when superblock is clean. * But, the previous checkpoint was not done by umount, it needs to do * clean checkpoint again. */ if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) || !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { struct cp_control cpc = { .reason = CP_UMOUNT, }; write_checkpoint(sbi, &cpc); } /* be sure to wait for any on-going discard commands */ f2fs_wait_discard_bios(sbi); if (f2fs_discard_en(sbi) && !sbi->discard_blks) { struct cp_control cpc = { .reason = CP_UMOUNT | CP_TRIMMED, }; write_checkpoint(sbi, &cpc); } /* write_checkpoint can update stat informaion */ f2fs_destroy_stats(sbi); /* * normally superblock is clean, so we need to release this. * In addition, EIO will skip do checkpoint, we need this as well. */ release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); mutex_unlock(&sbi->umount_mutex); /* our cp_error case, we can wait for any writeback page */ f2fs_flush_merged_writes(sbi); iput(sbi->node_inode); iput(sbi->meta_inode); /* destroy f2fs internal modules */ destroy_node_manager(sbi); destroy_segment_manager(sbi); kfree(sbi->ckpt); f2fs_unregister_sysfs(sbi); sb->s_fs_info = NULL; if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->raw_super); destroy_device_list(sbi); mempool_destroy(sbi->write_io_dummy); #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif destroy_percpu_info(sbi); for (i = 0; i < NR_PAGE_TYPE; i++) kfree(sbi->write_io[i]); kfree(sbi); } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static int do_send_NPUTF8(rpc_message_t *message, void *p_value) { NPUTF8 *string = (NPUTF8 *)p_value; if (string == NULL) return RPC_ERROR_MESSAGE_ARGUMENT_INVALID; int len = strlen(string) + 1; int error = rpc_message_send_uint32(message, len); if (error < 0) return error; if (len > 0) return rpc_message_send_bytes(message, (unsigned char *)string, len); return RPC_ERROR_NO_ERROR; } Commit Message: Support all the new variables added 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: UWORD16 impeg2d_get_mb_addr_incr(stream_t *ps_stream) { UWORD16 u2_mb_addr_incr = 0; while (impeg2d_bit_stream_nxt(ps_stream,MB_ESCAPE_CODE_LEN) == MB_ESCAPE_CODE) { impeg2d_bit_stream_flush(ps_stream,MB_ESCAPE_CODE_LEN); u2_mb_addr_incr += 33; } u2_mb_addr_incr += impeg2d_dec_vld_symbol(ps_stream,gai2_impeg2d_mb_addr_incr,MB_ADDR_INCR_LEN) + MB_ADDR_INCR_OFFSET; return(u2_mb_addr_incr); } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 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: PHP_FUNCTION(readlink) { char *link; int link_len; char buff[MAXPATHLEN]; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &link, &link_len) == FAILURE) { return; } if (php_check_open_basedir(link TSRMLS_CC)) { RETURN_FALSE; } ret = php_sys_readlink(link, buff, MAXPATHLEN-1); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } /* Append NULL to the end of the string */ buff[ret] = '\0'; RETURN_STRING(buff, 1); } Commit Message: CWE ID: CWE-254 Target: 1 Example 2: Code: void RenderViewHostImpl::OnClose() { ClosePageIgnoringUnloadEvents(); } Commit Message: Filter more incoming URLs in the CreateWindow path. BUG=170532 Review URL: https://chromiumcodereview.appspot.com/12036002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 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: void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } Commit Message: re_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int yr_re_fast_exec( uint8_t* code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args, int* matches) { RE_REPEAT_ANY_ARGS* repeat_any_args; uint8_t* code_stack[MAX_FAST_RE_STACK]; uint8_t* input_stack[MAX_FAST_RE_STACK]; int matches_stack[MAX_FAST_RE_STACK]; uint8_t* ip = code; uint8_t* input = input_data; uint8_t* next_input; uint8_t* next_opcode; uint8_t mask; uint8_t value; int i; int stop; int input_incr; int sp = 0; int bytes_matched; int max_bytes_matched; max_bytes_matched = flags & RE_FLAGS_BACKWARDS ? (int) input_backwards_size : (int) input_forwards_size; input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1; if (flags & RE_FLAGS_BACKWARDS) input--; code_stack[sp] = code; input_stack[sp] = input; matches_stack[sp] = 0; sp++; while (sp > 0) { sp--; ip = code_stack[sp]; input = input_stack[sp]; bytes_matched = matches_stack[sp]; stop = FALSE; while(!stop) { if (*ip == RE_OPCODE_MATCH) { if (flags & RE_FLAGS_EXHAUSTIVE) { FAIL_ON_ERROR(callback( flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data, bytes_matched, flags, callback_args)); break; } else { if (matches != NULL) *matches = bytes_matched; return ERROR_SUCCESS; } } if (bytes_matched >= max_bytes_matched) break; switch(*ip) { case RE_OPCODE_LITERAL: if (*input == *(ip + 1)) { bytes_matched++; input += input_incr; ip += 2; } else { stop = TRUE; } break; case RE_OPCODE_MASKED_LITERAL: value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; if ((*input & mask) == value) { bytes_matched++; input += input_incr; ip += 3; } else { stop = TRUE; } break; case RE_OPCODE_ANY: bytes_matched++; input += input_incr; ip += 1; break; case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1); next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS); for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++) { next_input = input + i * input_incr; if (bytes_matched + i >= max_bytes_matched) break; if ( *(next_opcode) != RE_OPCODE_LITERAL || (*(next_opcode) == RE_OPCODE_LITERAL && *(next_opcode + 1) == *next_input)) { if (sp >= MAX_FAST_RE_STACK) return -4; code_stack[sp] = next_opcode; input_stack[sp] = next_input; matches_stack[sp] = bytes_matched + i; sp++; } } input += input_incr * repeat_any_args->min; bytes_matched += repeat_any_args->min; ip = next_opcode; break; default: assert(FALSE); } } } if (matches != NULL) *matches = -1; return ERROR_SUCCESS; } Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier. CWE ID: CWE-125 Target: 1 Example 2: Code: ofputil_decode_hello_bitmap(const struct ofp_hello_elem_header *oheh, uint32_t *allowed_versionsp) { uint16_t bitmap_len = ntohs(oheh->length) - sizeof *oheh; const ovs_be32 *bitmap = ALIGNED_CAST(const ovs_be32 *, oheh + 1); uint32_t allowed_versions; if (!bitmap_len || bitmap_len % sizeof *bitmap) { return false; } /* Only use the first 32-bit element of the bitmap as that is all the * current implementation supports. Subsequent elements are ignored which * should have no effect on session negotiation until Open vSwitch supports * wire-protocol versions greater than 31. */ allowed_versions = ntohl(bitmap[0]); if (allowed_versions & 1) { /* There's no OpenFlow version 0. */ VLOG_WARN_RL(&bad_ofmsg_rl, "peer claims to support invalid OpenFlow " "version 0x00"); allowed_versions &= ~1u; } if (!allowed_versions) { VLOG_WARN_RL(&bad_ofmsg_rl, "peer does not support any OpenFlow " "version (between 0x01 and 0x1f)"); return false; } *allowed_versionsp = allowed_versions; return true; } Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command. When decoding a group mod, the current code validates the group type and command after the whole group mod has been decoded. The OF1.5 decoder, however, tries to use the type and command earlier, when it might still be invalid. This caused an assertion failure (via OVS_NOT_REACHED). This commit fixes the problem. ovs-vswitchd does not enable support for OpenFlow 1.5 by default. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249 Signed-off-by: Ben Pfaff <[email protected]> Reviewed-by: Yifeng Sun <[email protected]> CWE ID: CWE-617 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ip6t_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); /* Initializing verdict to NF_DROP keeps gcc happy. */ unsigned int verdict = NF_DROP; const char *indev, *outdev; const void *table_base; struct ip6t_entry *e, **jumpstack; unsigned int stackidx, cpu; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; /* Initialization */ stackidx = 0; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; /* We handle fragments by dealing with the first fragment as * if it was a normal packet. All other fragments are treated * normally, except that they will NEVER match rules that ask * things we don't know, ie. tcp syn flag or ports). If the * rule is also a fragment-specific rule, non-fragments won't * match it. */ acpar.hotdrop = false; acpar.state = state; WARN_ON(!(table->valid_hooks & (1 << hook))); local_bh_disable(); addend = xt_write_recseq_begin(); private = READ_ONCE(table->private); /* Address dependency. */ cpu = smp_processor_id(); table_base = private->entries; jumpstack = (struct ip6t_entry **)private->jumpstack[cpu]; /* Switch to alternate jumpstack if we're being invoked via TEE. * TEE issues XT_CONTINUE verdict on original skb so we must not * clobber the jumpstack. * * For recursion via REJECT or SYNPROXY the stack will be clobbered * but it is no problem since absolute verdict is issued by these. */ if (static_key_false(&xt_tee_enabled)) jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated); e = get_entry(table_base, private->hook_entry[hook]); do { const struct xt_entry_target *t; const struct xt_entry_match *ematch; struct xt_counters *counter; WARN_ON(!e); acpar.thoff = 0; if (!ip6_packet_match(skb, indev, outdev, &e->ipv6, &acpar.thoff, &acpar.fragoff, &acpar.hotdrop)) { no_match: e = ip6t_next_entry(e); continue; } xt_ematch_foreach(ematch, e) { acpar.match = ematch->u.kernel.match; acpar.matchinfo = ematch->data; if (!acpar.match->match(skb, &acpar)) goto no_match; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, skb->len, 1); t = ip6t_get_target_c(e); WARN_ON(!t->u.kernel.target); #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) /* The packet is traced: log it */ if (unlikely(skb->nf_trace)) trace_packet(state->net, skb, hook, state->in, state->out, table->name, private, e); #endif /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) e = get_entry(table_base, private->underflow[hook]); else e = ip6t_next_entry(jumpstack[--stackidx]); continue; } if (table_base + v != ip6t_next_entry(e) && !(e->ipv6.flags & IP6T_F_GOTO)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); if (verdict == XT_CONTINUE) e = ip6t_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } Commit Message: netfilter: add back stackpointer size checks The rationale for removing the check is only correct for rulesets generated by ip(6)tables. In iptables, a jump can only occur to a user-defined chain, i.e. because we size the stack based on number of user-defined chains we cannot exceed stack size. However, the underlying binary format has no such restriction, and the validation step only ensures that the jump target is a valid rule start point. IOW, its possible to build a rule blob that has no user-defined chains but does contain a jump. If this happens, no jump stack gets allocated and crash occurs because no jumpstack was allocated. Fixes: 7814b6ec6d0d6 ("netfilter: xtables: don't save/restore jumpstack offset") Reported-by: [email protected] Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-476 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 nft_flush_table(struct nft_ctx *ctx) { int err; struct nft_chain *chain, *nc; struct nft_set *set, *ns; list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) { ctx->chain = chain; err = nft_delrule_by_chain(ctx); if (err < 0) goto out; err = nft_delchain(ctx); if (err < 0) goto out; } list_for_each_entry_safe(set, ns, &ctx->table->sets, list) { if (set->flags & NFT_SET_ANONYMOUS && !list_empty(&set->bindings)) continue; err = nft_delset(ctx, set); if (err < 0) goto out; } err = nft_deltable(ctx); out: return err; } Commit Message: netfilter: nf_tables: fix flush ruleset chain dependencies Jumping between chains doesn't mix well with flush ruleset. Rules from a different chain and set elements may still refer to us. [ 353.373791] ------------[ cut here ]------------ [ 353.373845] kernel BUG at net/netfilter/nf_tables_api.c:1159! [ 353.373896] invalid opcode: 0000 [#1] SMP [ 353.373942] Modules linked in: intel_powerclamp uas iwldvm iwlwifi [ 353.374017] CPU: 0 PID: 6445 Comm: 31c3.nft Not tainted 3.18.0 #98 [ 353.374069] Hardware name: LENOVO 5129CTO/5129CTO, BIOS 6QET47WW (1.17 ) 07/14/2010 [...] [ 353.375018] Call Trace: [ 353.375046] [<ffffffff81964c31>] ? nf_tables_commit+0x381/0x540 [ 353.375101] [<ffffffff81949118>] nfnetlink_rcv+0x3d8/0x4b0 [ 353.375150] [<ffffffff81943fc5>] netlink_unicast+0x105/0x1a0 [ 353.375200] [<ffffffff8194438e>] netlink_sendmsg+0x32e/0x790 [ 353.375253] [<ffffffff818f398e>] sock_sendmsg+0x8e/0xc0 [ 353.375300] [<ffffffff818f36b9>] ? move_addr_to_kernel.part.20+0x19/0x70 [ 353.375357] [<ffffffff818f44f9>] ? move_addr_to_kernel+0x19/0x30 [ 353.375410] [<ffffffff819016d2>] ? verify_iovec+0x42/0xd0 [ 353.375459] [<ffffffff818f3e10>] ___sys_sendmsg+0x3f0/0x400 [ 353.375510] [<ffffffff810615fa>] ? native_sched_clock+0x2a/0x90 [ 353.375563] [<ffffffff81176697>] ? acct_account_cputime+0x17/0x20 [ 353.375616] [<ffffffff8110dc78>] ? account_user_time+0x88/0xa0 [ 353.375667] [<ffffffff818f4bbd>] __sys_sendmsg+0x3d/0x80 [ 353.375719] [<ffffffff81b184f4>] ? int_check_syscall_exit_work+0x34/0x3d [ 353.375776] [<ffffffff818f4c0d>] SyS_sendmsg+0xd/0x20 [ 353.375823] [<ffffffff81b1826d>] system_call_fastpath+0x16/0x1b Release objects in this order: rules -> sets -> chains -> tables, to make sure no references to chains are held anymore. Reported-by: Asbjoern Sloth Toennesen <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-19 Target: 1 Example 2: Code: selftest_encr_2048 (gcry_sexp_t pkey, gcry_sexp_t skey) { const char *errtxt = NULL; gcry_error_t err; static const char plaintext[] = "Jim quickly realized that the beautiful gowns are expensive."; gcry_sexp_t plain = NULL; gcry_sexp_t encr = NULL; gcry_mpi_t ciphertext = NULL; gcry_sexp_t decr = NULL; char *decr_plaintext = NULL; gcry_sexp_t tmplist = NULL; /* expected result of encrypting the plaintext with sample_secret_key */ static const char ref_data[] = "18022e2593a402a737caaa93b4c7e750e20ca265452980e1d6b7710fbd3e" "7dce72be5c2110fb47691cb38f42170ee3b4a37f2498d4a51567d762585e" "4cb81d04fbc7df4144f8e5eac2d4b8688521b64011f11d7ad53f4c874004" "819856f2e2a6f83d1c9c4e73ac26089789c14482b0b8d44139133c88c4a5" "2dba9dd6d6ffc622666b7d129168333d999706af30a2d7d272db7734e5ed" "fb8c64ea3018af3ad20f4a013a5060cb0f5e72753967bebe294280a6ed0d" "dbd3c4f11d0a8696e9d32a0dc03deb0b5e49b2cbd1503392642d4e1211f3" "e8e2ee38abaa3671ccd57fcde8ca76e85fd2cb77c35706a970a213a27352" "cec92a9604d543ddb5fc478ff50e0622"; gcry_mpi_t ref_mpi = NULL; /* Put the plaintext into an S-expression. */ err = sexp_build (&plain, NULL, "(data (flags raw) (value %s))", plaintext); if (err) { errtxt = "converting data failed"; goto leave; } /* Encrypt. */ err = _gcry_pk_encrypt (&encr, plain, pkey); if (err) { errtxt = "encrypt failed"; goto leave; } err = _gcry_mpi_scan(&ref_mpi, GCRYMPI_FMT_HEX, ref_data, 0, NULL); if (err) { errtxt = "converting encrydata to mpi failed"; goto leave; } /* Extraxt the ciphertext from the returned S-expression. */ /*sexp_dump (encr);*/ ciphertext = extract_a_from_sexp (encr); if (!ciphertext) { errtxt = "gcry_pk_decrypt returned garbage"; goto leave; } /* Check that the ciphertext does no match the plaintext. */ /* _gcry_log_printmpi ("plaintext", plaintext); */ /* _gcry_log_printmpi ("ciphertxt", ciphertext); */ if (mpi_cmp (ref_mpi, ciphertext)) { errtxt = "ciphertext doesn't match reference data"; goto leave; } /* Decrypt. */ err = _gcry_pk_decrypt (&decr, encr, skey); if (err) { errtxt = "decrypt failed"; goto leave; } /* Extract the decrypted data from the S-expression. Note that the output of gcry_pk_decrypt depends on whether a flags lists occurs in its input data. Because we passed the output of gcry_pk_encrypt directly to gcry_pk_decrypt, such a flag value won't be there as of today. To be prepared for future changes we take care of it anyway. */ tmplist = sexp_find_token (decr, "value", 0); if (tmplist) decr_plaintext = sexp_nth_string (tmplist, 1); else decr_plaintext = sexp_nth_string (decr, 0); if (!decr_plaintext) { errtxt = "decrypt returned no plaintext"; goto leave; } /* Check that the decrypted plaintext matches the original plaintext. */ if (strcmp (plaintext, decr_plaintext)) { errtxt = "mismatch"; goto leave; } leave: sexp_release (tmplist); xfree (decr_plaintext); sexp_release (decr); _gcry_mpi_release (ciphertext); _gcry_mpi_release (ref_mpi); sexp_release (encr); sexp_release (plain); return errtxt; } Commit Message: CWE ID: CWE-310 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 LoadingStatsCollector::CleanupAbandonedStats() { base::TimeTicks time_now = base::TimeTicks::Now(); for (auto it = preconnect_stats_.begin(); it != preconnect_stats_.end();) { if (time_now - it->second->start_time > max_stats_age_) { ReportPreconnectAccuracy(*it->second, std::map<GURL, OriginRequestSummary>()); it = preconnect_stats_.erase(it); } else { ++it; } } } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops) { while (elements-- > 0) { zval *key, *data, **old_data; ALLOC_INIT_ZVAL(key); if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); return 0; } if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) { zval_dtor(key); FREE_ZVAL(key); return 0; } ALLOC_INIT_ZVAL(data); if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); zval_dtor(data); FREE_ZVAL(data); return 0; } if (!objprops) { switch (Z_TYPE_P(key)) { case IS_LONG: if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL); break; case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL); break; } } else { /* object properties should include no integers */ convert_to_string(key); zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof data, NULL); } if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } } Commit Message: CWE ID: Target: 1 Example 2: Code: void Document::open(Document* entered_document, ExceptionState& exception_state) { if (ImportLoader()) { exception_state.ThrowDOMException( kInvalidStateError, "Imported document doesn't support open()."); return; } if (!IsHTMLDocument()) { exception_state.ThrowDOMException(kInvalidStateError, "Only HTML documents support open()."); return; } if (throw_on_dynamic_markup_insertion_count_) { exception_state.ThrowDOMException( kInvalidStateError, "Custom Element constructor should not use open()."); return; } if (entered_document) { if (!GetSecurityOrigin()->IsSameSchemeHostPortAndSuborigin( entered_document->GetSecurityOrigin())) { exception_state.ThrowSecurityError( "Can only call open() on same-origin documents."); return; } SetSecurityOrigin(entered_document->GetSecurityOrigin()); if (this != entered_document) { KURL new_url = entered_document->Url(); new_url.SetFragmentIdentifier(String()); SetURL(new_url); } cookie_url_ = entered_document->CookieURL(); } open(); } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud, unsigned long addr, unsigned long end, struct zap_details *details) { pmd_t *pmd; unsigned long next; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) continue; next = zap_pte_range(tlb, vma, pmd, addr, next, details); cond_resched(); } while (pmd++, addr = next, addr != end); return addr; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool BaseSettingChange::Init(Profile* profile) { DCHECK(profile); profile_ = profile; return true; } Commit Message: [protector] Refactoring of --no-protector code. *) On DSE change, new provider is not pushed to Sync. *) Simplified code in BrowserInit. BUG=None TEST=protector.py Review URL: http://codereview.chromium.org/10065016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132398 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: SYSCALL_DEFINE1(uname, struct old_utsname __user *, name) { int error = 0; if (!name) return -EFAULT; down_read(&uts_sem); if (copy_to_user(name, utsname(), sizeof(*name))) error = -EFAULT; up_read(&uts_sem); if (!error && override_release(name->release, sizeof(name->release))) error = -EFAULT; if (!error && override_architecture(name)) error = -EFAULT; return error; } Commit Message: mm: fix prctl_set_vma_anon_name prctl_set_vma_anon_name could attempt to set the name across two vmas at the same time due to a typo, which might corrupt the vma list. Fix it to use tmp instead of end to limit the name setting to a single vma at a time. Change-Id: Ie32d8ddb0fd547efbeedd6528acdab5ca5b308b4 Reported-by: Jed Davis <[email protected]> Signed-off-by: Colin Cross <[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: juniper_atm2_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM2; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */ (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) { ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */ return l2info.header_len; if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125 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: asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct compat_timespec __user *timeout) { int datagrams; struct timespec ktspec; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (COMPAT_USE_64BIT_TIME) return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, (struct timespec *) timeout); if (timeout == NULL) return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, NULL); if (get_compat_timespec(&ktspec, timeout)) return -EFAULT; datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, &ktspec); if (datagrams > 0 && put_compat_timespec(&ktspec, timeout)) datagrams = -EFAULT; return datagrams; } Commit Message: x86, x32: Correct invalid use of user timespec in the kernel The x32 case for the recvmsg() timout handling is broken: asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct compat_timespec __user *timeout) { int datagrams; struct timespec ktspec; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (COMPAT_USE_64BIT_TIME) return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, (struct timespec *) timeout); ... The timeout pointer parameter is provided by userland (hence the __user annotation) but for x32 syscalls it's simply cast to a kernel pointer and is passed to __sys_recvmmsg which will eventually directly dereference it for both reading and writing. Other callers to __sys_recvmmsg properly copy from userland to the kernel first. The bug was introduced by commit ee4fa23c4bfc ("compat: Use COMPAT_USE_64BIT_TIME in net/compat.c") and should affect all kernels since 3.4 (and perhaps vendor kernels if they backported x32 support along with this code). Note that CONFIG_X86_X32_ABI gets enabled at build time and only if CONFIG_X86_X32 is enabled and ld can build x32 executables. Other uses of COMPAT_USE_64BIT_TIME seem fine. This addresses CVE-2014-0038. Signed-off-by: PaX Team <[email protected]> Signed-off-by: H. Peter Anvin <[email protected]> Cc: <[email protected]> # v3.4+ Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: bool kvm_arch_has_assigned_device(struct kvm *kvm) { return atomic_read(&kvm->arch.assigned_device_count); } Commit Message: KVM: x86: Reload pit counters for all channels when restoring state Currently if userspace restores the pit counters with a count of 0 on channels 1 or 2 and the guest attempts to read the count on those channels, then KVM will perform a mod of 0 and crash. This will ensure that 0 values are converted to 65536 as per the spec. This is CVE-2015-7513. Signed-off-by: Andy Honig <[email protected]> Signed-off-by: Paolo Bonzini <[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: std::vector<ExtensionSyncData> ExtensionService::GetSyncDataList( ExtensionFilter filter) const { std::vector<ExtensionSyncData> sync_data_list; GetSyncDataListHelper(extensions_, filter, &sync_data_list); GetSyncDataListHelper(disabled_extensions_, filter, &sync_data_list); GetSyncDataListHelper(terminated_extensions_, filter, &sync_data_list); return sync_data_list; } Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension with plugins. First landing broke some browser tests. BUG=83273 TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog. TBR=mihaip git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 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: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = (uint64_t)mTimeToSampleCount * 2 * sizeof(uint32_t); if (allocSize > UINT32_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new (std::nothrow) uint32_t[mTimeToSampleCount * 2]; if (!mTimeToSample) return ERROR_OUT_OF_RANGE; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20 Target: 1 Example 2: Code: void CommandBufferProxyImpl::OnConsoleMessage( const GPUCommandBufferConsoleMessage& message) { if (gpu_control_client_) gpu_control_client_->OnGpuControlErrorMessage(message.message.c_str(), message.id); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 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 MediaInterfaceProxy::CreateCdm( media::mojom::ContentDecryptionModuleRequest request) { DCHECK(thread_checker_.CalledOnValidThread()); GetMediaInterfaceFactory()->CreateCdm(std::move(request)); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} 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: RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "OnDocumentElementCreated", base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated, base::Unretained(this))); } Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated BUG=585268,568130 Review URL: https://codereview.chromium.org/1684953002 Cr-Commit-Position: refs/heads/master@{#374758} CWE ID: Target: 1 Example 2: Code: static void nfnl_err_reset(struct list_head *err_list) { struct nfnl_err *nfnl_err, *next; list_for_each_entry_safe(nfnl_err, next, err_list, head) nfnl_err_del(nfnl_err); } Commit Message: netfilter: nfnetlink: correctly validate length of batch messages If nlh->nlmsg_len is zero then an infinite loop is triggered because 'skb_pull(skb, msglen);' pulls zero bytes. The calculation in nlmsg_len() underflows if 'nlh->nlmsg_len < NLMSG_HDRLEN' which bypasses the length validation and will later trigger an out-of-bound read. If the length validation does fail then the malformed batch message is copied back to userspace. However, we cannot do this because the nlh->nlmsg_len can be invalid. This leads to an out-of-bounds read in netlink_ack: [ 41.455421] ================================================================== [ 41.456431] BUG: KASAN: slab-out-of-bounds in memcpy+0x1d/0x40 at addr ffff880119e79340 [ 41.456431] Read of size 4294967280 by task a.out/987 [ 41.456431] ============================================================================= [ 41.456431] BUG kmalloc-512 (Not tainted): kasan: bad access detected [ 41.456431] ----------------------------------------------------------------------------- ... [ 41.456431] Bytes b4 ffff880119e79310: 00 00 00 00 d5 03 00 00 b0 fb fe ff 00 00 00 00 ................ [ 41.456431] Object ffff880119e79320: 20 00 00 00 10 00 05 00 00 00 00 00 00 00 00 00 ............... [ 41.456431] Object ffff880119e79330: 14 00 0a 00 01 03 fc 40 45 56 11 22 33 10 00 05 .......@EV."3... [ 41.456431] Object ffff880119e79340: f0 ff ff ff 88 99 aa bb 00 14 00 0a 00 06 fe fb ................ ^^ start of batch nlmsg with nlmsg_len=4294967280 ... [ 41.456431] Memory state around the buggy address: [ 41.456431] ffff880119e79400: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 41.456431] ffff880119e79480: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 41.456431] >ffff880119e79500: 00 00 00 00 fc fc fc fc fc fc fc fc fc fc fc fc [ 41.456431] ^ [ 41.456431] ffff880119e79580: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 41.456431] ffff880119e79600: fc fc fc fc fc fc fc fc fc fc fb fb fb fb fb fb [ 41.456431] ================================================================== Fix this with better validation of nlh->nlmsg_len and by setting NFNL_BATCH_FAILURE if any batch message fails length validation. CAP_NET_ADMIN is required to trigger the bugs. Fixes: 9ea2aa8b7dba ("netfilter: nfnetlink: validate nfnetlink header from batch") Signed-off-by: Phil Turnbull <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> 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: IMPEG2D_ERROR_CODES_T impeg2d_init_video_state(dec_state_t *ps_dec, e_video_type_t e_video_type) { /*-----------------------------------------------------------------------*/ /* Bit Stream that conforms to MPEG-1 <ISO/IEC 11172-2> standard */ /*-----------------------------------------------------------------------*/ if(e_video_type == MPEG_1_VIDEO) { ps_dec->u2_is_mpeg2 = 0; /*-------------------------------------------------------------------*/ /* force MPEG-1 parameters for proper decoder behavior */ /* see ISO/IEC 13818-2 section D.9.14 */ /*-------------------------------------------------------------------*/ ps_dec->u2_progressive_sequence = 1; ps_dec->u2_intra_dc_precision = 0; ps_dec->u2_picture_structure = FRAME_PICTURE; ps_dec->u2_frame_pred_frame_dct = 1; ps_dec->u2_concealment_motion_vectors = 0; ps_dec->u2_q_scale_type = 0; ps_dec->u2_intra_vlc_format = 0; ps_dec->u2_alternate_scan = 0; ps_dec->u2_repeat_first_field = 0; ps_dec->u2_progressive_frame = 1; ps_dec->u2_frame_rate_extension_n = 0; ps_dec->u2_frame_rate_extension_d = 0; ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg1; /*-------------------------------------------------------------------*/ /* Setting of parameters other than those mentioned in MPEG2 standard*/ /* but used in decoding process. */ /*-------------------------------------------------------------------*/ } /*-----------------------------------------------------------------------*/ /* Bit Stream that conforms to MPEG-2 */ /*-----------------------------------------------------------------------*/ else { ps_dec->u2_is_mpeg2 = 1; ps_dec->u2_full_pel_forw_vector = 0; ps_dec->u2_forw_f_code = 7; ps_dec->u2_full_pel_back_vector = 0; ps_dec->u2_back_f_code = 7; ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg2; } impeg2d_init_function_ptr(ps_dec); /* Set the frame Width and frame Height */ ps_dec->u2_frame_height = ALIGN16(ps_dec->u2_vertical_size); ps_dec->u2_frame_width = ALIGN16(ps_dec->u2_horizontal_size); ps_dec->u2_num_horiz_mb = (ps_dec->u2_horizontal_size + 15) >> 4; if (ps_dec->u2_frame_height > ps_dec->u2_create_max_height || ps_dec->u2_frame_width > ps_dec->u2_create_max_width) { return IMPEG2D_PIC_SIZE_NOT_SUPPORTED; } ps_dec->u2_num_flds_decoded = 0; /* Calculate the frame period */ { UWORD32 numer; UWORD32 denom; numer = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][1] * (UWORD32)(ps_dec->u2_frame_rate_extension_d + 1); denom = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][0] * (UWORD32)(ps_dec->u2_frame_rate_extension_n + 1); ps_dec->u2_framePeriod = (numer * 1000 * 100) / denom; } if(VERTICAL_SCAN == ps_dec->u2_alternate_scan) { ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_vertical; } else { ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_zig_zag; } return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Adding Error Check for f_code Parameters In MPEG1, the valid range for the forward and backward f_code parameters is [1, 7]. Adding a check to enforce this. Without the check, the value could be 0. We read (f_code - 1) bits from the stream and reading a negative number of bits from the stream is undefined. Bug: 64550583 Test: monitored temp ALOGD() output Change-Id: Ia452cd43a28e9d566401f515947164635361782f (cherry picked from commit 71d734b83d72e8a59f73f1230982da97615d2689) CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Browser::SetWebContentsBlocked(content::WebContents* web_contents, bool blocked) { int index = tab_strip_model_->GetIndexOfWebContents(web_contents); if (index == TabStripModel::kNoTab) { return; } tab_strip_model_->SetTabBlocked(index, blocked); bool browser_active = BrowserList::GetInstance()->GetLastActive() == this; bool contents_is_active = tab_strip_model_->GetActiveWebContents() == web_contents; if (!blocked && contents_is_active && browser_active) web_contents->Focus(); } Commit Message: If a dialog is shown, drop fullscreen. BUG=875066, 817809, 792876, 812769, 813815 TEST=included Change-Id: Ic3d697fa3c4b01f5d7fea77391857177ada660db Reviewed-on: https://chromium-review.googlesource.com/1185208 Reviewed-by: Sidney San Martín <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#586418} CWE ID: CWE-20 Target: 1 Example 2: Code: static int perf_event_comm_match(struct perf_event *event) { if (event->state < PERF_EVENT_STATE_INACTIVE) return 0; if (!event_filter_match(event)) return 0; if (event->attr.comm) return 1; return 0; } 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: unsigned omx_video::omx_cmd_queue::get_q_msg_type() { return m_q[m_read].id; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 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: CuePoint::~CuePoint() { delete[] m_track_positions; } 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 InputHandler::ClearInputState() { for (auto& callback : pending_key_callbacks_) callback->sendSuccess(); pending_key_callbacks_.clear(); for (auto& callback : pending_mouse_callbacks_) callback->sendSuccess(); pending_mouse_callbacks_.clear(); touch_points_.clear(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 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: ZEND_API zval* ZEND_FASTCALL _zend_hash_index_update(HashTable *ht, zend_ulong h, zval *pData ZEND_FILE_LINE_DC) { return _zend_hash_index_add_or_update_i(ht, h, pData, HASH_UPDATE ZEND_FILE_LINE_RELAY_CC); } Commit Message: Fix #73832 - leave the table in a safe state if the size is too big. CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool Browser::CanCloseContentsAt(int index) { if (!CanCloseTab()) return false; if (tab_handler_->GetTabStripModel()->count() > 1) return true; return CanCloseWithInProgressDownloads(); } 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 Target: 1 Example 2: Code: static int do_last(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, int *opened, struct filename *name) { struct dentry *dir = nd->path.dentry; int open_flag = op->open_flag; bool will_truncate = (open_flag & O_TRUNC) != 0; bool got_write = false; int acc_mode = op->acc_mode; struct inode *inode; bool symlink_ok = false; struct path save_parent = { .dentry = NULL, .mnt = NULL }; bool retried = false; int error; nd->flags &= ~LOOKUP_PARENT; nd->flags |= op->intent; if (nd->last_type != LAST_NORM) { error = handle_dots(nd, nd->last_type); if (error) return error; goto finish_open; } if (!(open_flag & O_CREAT)) { if (nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW)) symlink_ok = true; /* we _can_ be in RCU mode here */ error = lookup_fast(nd, path, &inode); if (likely(!error)) goto finish_lookup; if (error < 0) goto out; BUG_ON(nd->inode != dir->d_inode); } else { /* create side of things */ /* * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED * has been cleared when we got to the last component we are * about to look up */ error = complete_walk(nd); if (error) return error; audit_inode(name, dir, LOOKUP_PARENT); error = -EISDIR; /* trailing slashes? */ if (nd->last.name[nd->last.len]) goto out; } retry_lookup: if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) { error = mnt_want_write(nd->path.mnt); if (!error) got_write = true; /* * do _not_ fail yet - we might not need that or fail with * a different error; let lookup_open() decide; we'll be * dropping this one anyway. */ } mutex_lock(&dir->d_inode->i_mutex); error = lookup_open(nd, path, file, op, got_write, opened); mutex_unlock(&dir->d_inode->i_mutex); if (error <= 0) { if (error) goto out; if ((*opened & FILE_CREATED) || !S_ISREG(file_inode(file)->i_mode)) will_truncate = false; audit_inode(name, file->f_path.dentry, 0); goto opened; } if (*opened & FILE_CREATED) { /* Don't check for write permission, don't truncate */ open_flag &= ~O_TRUNC; will_truncate = false; acc_mode = MAY_OPEN; path_to_nameidata(path, nd); goto finish_open_created; } /* * create/update audit record if it already exists. */ if (d_is_positive(path->dentry)) audit_inode(name, path->dentry, 0); /* * If atomic_open() acquired write access it is dropped now due to * possible mount and symlink following (this might be optimized away if * necessary...) */ if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } error = -EEXIST; if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT)) goto exit_dput; error = follow_managed(path, nd->flags); if (error < 0) goto exit_dput; if (error) nd->flags |= LOOKUP_JUMPED; BUG_ON(nd->flags & LOOKUP_RCU); inode = path->dentry->d_inode; finish_lookup: /* we _can_ be in RCU mode here */ error = -ENOENT; if (!inode || d_is_negative(path->dentry)) { path_to_nameidata(path, nd); goto out; } if (should_follow_link(path->dentry, !symlink_ok)) { if (nd->flags & LOOKUP_RCU) { if (unlikely(unlazy_walk(nd, path->dentry))) { error = -ECHILD; goto out; } } BUG_ON(inode != path->dentry->d_inode); return 1; } if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path->mnt) { path_to_nameidata(path, nd); } else { save_parent.dentry = nd->path.dentry; save_parent.mnt = mntget(path->mnt); nd->path.dentry = path->dentry; } nd->inode = inode; /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ finish_open: error = complete_walk(nd); if (error) { path_put(&save_parent); return error; } audit_inode(name, nd->path.dentry, 0); error = -EISDIR; if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry)) goto out; error = -ENOTDIR; if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry)) goto out; if (!S_ISREG(nd->inode->i_mode)) will_truncate = false; if (will_truncate) { error = mnt_want_write(nd->path.mnt); if (error) goto out; got_write = true; } finish_open_created: error = may_open(&nd->path, acc_mode, open_flag); if (error) goto out; file->f_path.mnt = nd->path.mnt; error = finish_open(file, nd->path.dentry, NULL, opened); if (error) { if (error == -EOPENSTALE) goto stale_open; goto out; } opened: error = open_check_o_direct(file); if (error) goto exit_fput; error = ima_file_check(file, op->acc_mode); if (error) goto exit_fput; if (will_truncate) { error = handle_truncate(file); if (error) goto exit_fput; } out: if (got_write) mnt_drop_write(nd->path.mnt); path_put(&save_parent); terminate_walk(nd); return error; exit_dput: path_put_conditional(path, nd); goto out; exit_fput: fput(file); goto out; stale_open: /* If no saved parent or already retried then can't retry */ if (!save_parent.dentry || retried) goto out; BUG_ON(save_parent.dentry != dir); path_put(&nd->path); nd->path = save_parent; nd->inode = dir->d_inode; save_parent.mnt = NULL; save_parent.dentry = NULL; if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } retried = true; goto retry_lookup; } 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: int CIFSFindNext(const int xid, struct cifs_tcon *tcon, __u16 searchHandle, struct cifs_search_info *psrch_inf) { TRANSACTION2_FNEXT_REQ *pSMB = NULL; TRANSACTION2_FNEXT_RSP *pSMBr = NULL; T2_FNEXT_RSP_PARMS *parms; char *response_data; int rc = 0; int bytes_returned, name_len; __u16 params, byte_count; cFYI(1, "In FindNext"); if (psrch_inf->endOfSearch) return -ENOENT; rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB, (void **) &pSMBr); if (rc) return rc; params = 14; /* includes 2 bytes of null string, converted to LE below*/ byte_count = 0; pSMB->TotalDataCount = 0; /* no EAs */ pSMB->MaxParameterCount = cpu_to_le16(8); pSMB->MaxDataCount = cpu_to_le16((tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE) & 0xFFFFFF00); pSMB->MaxSetupCount = 0; pSMB->Reserved = 0; pSMB->Flags = 0; pSMB->Timeout = 0; pSMB->Reserved2 = 0; pSMB->ParameterOffset = cpu_to_le16( offsetof(struct smb_com_transaction2_fnext_req,SearchHandle) - 4); pSMB->DataCount = 0; pSMB->DataOffset = 0; pSMB->SetupCount = 1; pSMB->Reserved3 = 0; pSMB->SubCommand = cpu_to_le16(TRANS2_FIND_NEXT); pSMB->SearchHandle = searchHandle; /* always kept as le */ pSMB->SearchCount = cpu_to_le16(CIFSMaxBufSize / sizeof(FILE_UNIX_INFO)); pSMB->InformationLevel = cpu_to_le16(psrch_inf->info_level); pSMB->ResumeKey = psrch_inf->resume_key; pSMB->SearchFlags = cpu_to_le16(CIFS_SEARCH_CLOSE_AT_END | CIFS_SEARCH_RETURN_RESUME); name_len = psrch_inf->resume_name_len; params += name_len; if (name_len < PATH_MAX) { memcpy(pSMB->ResumeFileName, psrch_inf->presume_name, name_len); byte_count += name_len; /* 14 byte parm len above enough for 2 byte null terminator */ pSMB->ResumeFileName[name_len] = 0; pSMB->ResumeFileName[name_len+1] = 0; } else { rc = -EINVAL; goto FNext2_err_exit; } byte_count = params + 1 /* pad */ ; pSMB->TotalParameterCount = cpu_to_le16(params); pSMB->ParameterCount = pSMB->TotalParameterCount; inc_rfc1001_len(pSMB, byte_count); pSMB->ByteCount = cpu_to_le16(byte_count); rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB, (struct smb_hdr *) pSMBr, &bytes_returned, 0); cifs_stats_inc(&tcon->num_fnext); if (rc) { if (rc == -EBADF) { psrch_inf->endOfSearch = true; cifs_buf_release(pSMB); rc = 0; /* search probably was closed at end of search*/ } else cFYI(1, "FindNext returned = %d", rc); } else { /* decode response */ rc = validate_t2((struct smb_t2_rsp *)pSMBr); if (rc == 0) { unsigned int lnoff; /* BB fixme add lock for file (srch_info) struct here */ if (pSMBr->hdr.Flags2 & SMBFLG2_UNICODE) psrch_inf->unicode = true; else psrch_inf->unicode = false; response_data = (char *) &pSMBr->hdr.Protocol + le16_to_cpu(pSMBr->t2.ParameterOffset); parms = (T2_FNEXT_RSP_PARMS *)response_data; response_data = (char *)&pSMBr->hdr.Protocol + le16_to_cpu(pSMBr->t2.DataOffset); if (psrch_inf->smallBuf) cifs_small_buf_release( psrch_inf->ntwrk_buf_start); else cifs_buf_release(psrch_inf->ntwrk_buf_start); psrch_inf->srch_entries_start = response_data; psrch_inf->ntwrk_buf_start = (char *)pSMB; psrch_inf->smallBuf = 0; if (parms->EndofSearch) psrch_inf->endOfSearch = true; else psrch_inf->endOfSearch = false; psrch_inf->entries_in_buffer = le16_to_cpu(parms->SearchCount); psrch_inf->index_of_last_entry += psrch_inf->entries_in_buffer; lnoff = le16_to_cpu(parms->LastNameOffset); if (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE < lnoff) { cERROR(1, "ignoring corrupt resume name"); psrch_inf->last_entry = NULL; return rc; } else psrch_inf->last_entry = psrch_inf->srch_entries_start + lnoff; /* cFYI(1, "fnxt2 entries in buf %d index_of_last %d", psrch_inf->entries_in_buffer, psrch_inf->index_of_last_entry); */ /* BB fixme add unlock here */ } } /* BB On error, should we leave previous search buf (and count and last entry fields) intact or free the previous one? */ /* Note: On -EAGAIN error only caller can retry on handle based calls since file handle passed in no longer valid */ FNext2_err_exit: if (rc != 0) cifs_buf_release(pSMB); return rc; } Commit Message: cifs: fix possible memory corruption in CIFSFindNext The name_len variable in CIFSFindNext is a signed int that gets set to the resume_name_len in the cifs_search_info. The resume_name_len however is unsigned and for some infolevels is populated directly from a 32 bit value sent by the server. If the server sends a very large value for this, then that value could look negative when converted to a signed int. That would make that value pass the PATH_MAX check later in CIFSFindNext. The name_len would then be used as a length value for a memcpy. It would then be treated as unsigned again, and the memcpy scribbles over a ton of memory. Fix this by making the name_len an unsigned value in CIFSFindNext. Cc: <[email protected]> Reported-by: Darren Lavender <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> 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: static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray) { u_short type, class, dlen; u_long ttl; long n, i; u_short s; u_char *tp, *p; char name[MAXHOSTNAMELEN]; int have_v6_break = 0, in_v6_break = 0; *subarray = NULL; n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, sizeof(name) - 2); if (n < 0) { return NULL; } cp += n; GETSHORT(type, cp); GETSHORT(class, cp); GETLONG(ttl, cp); GETSHORT(dlen, cp); if (type_to_fetch != T_ANY && type != type_to_fetch) { cp += dlen; return cp; } if (!store) { cp += dlen; return cp; } ALLOC_INIT_ZVAL(*subarray); array_init(*subarray); add_assoc_string(*subarray, "host", name, 1); add_assoc_string(*subarray, "class", "IN", 1); add_assoc_long(*subarray, "ttl", ttl); if (raw) { add_assoc_long(*subarray, "type", type); add_assoc_stringl(*subarray, "data", (char*) cp, (uint) dlen, 1); cp += dlen; return cp; } switch (type) { case DNS_T_A: add_assoc_string(*subarray, "type", "A", 1); snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]); add_assoc_string(*subarray, "ip", name, 1); cp += dlen; break; case DNS_T_MX: add_assoc_string(*subarray, "type", "MX", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "pri", n); /* no break; */ case DNS_T_CNAME: if (type == DNS_T_CNAME) { add_assoc_string(*subarray, "type", "CNAME", 1); } /* no break; */ case DNS_T_NS: if (type == DNS_T_NS) { add_assoc_string(*subarray, "type", "NS", 1); } /* no break; */ case DNS_T_PTR: if (type == DNS_T_PTR) { add_assoc_string(*subarray, "type", "PTR", 1); } n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "target", name, 1); break; case DNS_T_HINFO: /* See RFC 1010 for values */ add_assoc_string(*subarray, "type", "HINFO", 1); n = *cp & 0xFF; cp++; add_assoc_stringl(*subarray, "cpu", (char*)cp, n, 1); cp += n; n = *cp & 0xFF; cp++; add_assoc_stringl(*subarray, "os", (char*)cp, n, 1); cp += n; break; case DNS_T_TXT: { int ll = 0; zval *entries = NULL; add_assoc_string(*subarray, "type", "TXT", 1); tp = emalloc(dlen + 1); MAKE_STD_ZVAL(entries); array_init(entries); while (ll < dlen) { n = cp[ll]; memcpy(tp + ll , cp + ll + 1, n); add_next_index_stringl(entries, cp + ll + 1, n, 1); ll = ll + n + 1; } tp[dlen] = '\0'; cp += dlen; add_assoc_stringl(*subarray, "txt", tp, (dlen>0)?dlen - 1:0, 0); add_assoc_zval(*subarray, "entries", entries); } break; case DNS_T_SOA: add_assoc_string(*subarray, "type", "SOA", 1); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "mname", name, 1); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "rname", name, 1); GETLONG(n, cp); add_assoc_long(*subarray, "serial", n); GETLONG(n, cp); add_assoc_long(*subarray, "refresh", n); GETLONG(n, cp); add_assoc_long(*subarray, "retry", n); GETLONG(n, cp); add_assoc_long(*subarray, "expire", n); GETLONG(n, cp); add_assoc_long(*subarray, "minimum-ttl", n); break; case DNS_T_AAAA: tp = (u_char*)name; for(i=0; i < 8; i++) { GETSHORT(s, cp); if (s != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } tp += sprintf((char*)tp,"%x",s); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } } if (have_v6_break && in_v6_break) { tp[0] = ':'; tp++; } tp[0] = '\0'; add_assoc_string(*subarray, "type", "AAAA", 1); add_assoc_string(*subarray, "ipv6", name, 1); break; case DNS_T_A6: p = cp; add_assoc_string(*subarray, "type", "A6", 1); n = ((int)cp[0]) & 0xFF; cp++; add_assoc_long(*subarray, "masklen", n); tp = (u_char*)name; if (n > 15) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } if (n % 16 > 8) { /* Partial short */ if (cp[0] != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } sprintf((char*)tp, "%x", cp[0] & 0xFF); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } cp++; } for (i = (n + 8) / 16; i < 8; i++) { GETSHORT(s, cp); if (s != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } tp += sprintf((char*)tp,"%x",s); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } } if (have_v6_break && in_v6_break) { tp[0] = ':'; tp++; } tp[0] = '\0'; add_assoc_string(*subarray, "ipv6", name, 1); if (cp < p + dlen) { n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "chain", name, 1); } break; case DNS_T_SRV: add_assoc_string(*subarray, "type", "SRV", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "pri", n); GETSHORT(n, cp); add_assoc_long(*subarray, "weight", n); GETSHORT(n, cp); add_assoc_long(*subarray, "port", n); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "target", name, 1); break; case DNS_T_NAPTR: add_assoc_string(*subarray, "type", "NAPTR", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "order", n); GETSHORT(n, cp); add_assoc_long(*subarray, "pref", n); n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "flags", (char*)++cp, n, 1); cp += n; n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "services", (char*)++cp, n, 1); cp += n; n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "regex", (char*)++cp, n, 1); cp += n; n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "replacement", name, 1); break; default: zval_ptr_dtor(subarray); *subarray = NULL; cp += dlen; break; } return cp; } Commit Message: Merge branch 'PHP-5.6' * PHP-5.6: Fix potential segfault in dns_get_record() CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderMessageFilter::SendLoadFontReply(IPC::Message* reply, FontLoader::Result* result) { base::SharedMemoryHandle handle; if (result->font_data_size == 0 || result->font_id == 0) { result->font_data_size = 0; result->font_id = 0; handle = base::SharedMemory::NULLHandle(); } else { result->font_data.GiveToProcess(base::GetCurrentProcessHandle(), &handle); } ViewHostMsg_LoadFont::WriteReplyParams( reply, result->font_data_size, handle, result->font_id); Send(reply); } 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 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: gst_qtdemux_do_seek (GstQTDemux * qtdemux, GstPad * pad, GstEvent * event) { gdouble rate; GstFormat format; GstSeekFlags flags; GstSeekType cur_type, stop_type; gint64 cur, stop; gboolean flush; gboolean res; gboolean update; GstSegment seeksegment; int i; if (event) { GST_DEBUG_OBJECT (qtdemux, "doing seek with event"); gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur, &stop_type, &stop); /* we have to have a format as the segment format. Try to convert * if not. */ if (format != GST_FORMAT_TIME) { GstFormat fmt; fmt = GST_FORMAT_TIME; res = TRUE; if (cur_type != GST_SEEK_TYPE_NONE) res = gst_pad_query_convert (pad, format, cur, &fmt, &cur); if (res && stop_type != GST_SEEK_TYPE_NONE) res = gst_pad_query_convert (pad, format, stop, &fmt, &stop); if (!res) goto no_format; format = fmt; } } else { GST_DEBUG_OBJECT (qtdemux, "doing seek without event"); flags = 0; } flush = flags & GST_SEEK_FLAG_FLUSH; GST_DEBUG_OBJECT (qtdemux, "seek format %d", format); /* stop streaming, either by flushing or by pausing the task */ if (flush) { /* unlock upstream pull_range */ gst_pad_push_event (qtdemux->sinkpad, gst_event_new_flush_start ()); /* make sure out loop function exits */ gst_qtdemux_push_event (qtdemux, gst_event_new_flush_start ()); } else { /* non flushing seek, pause the task */ gst_pad_pause_task (qtdemux->sinkpad); } /* wait for streaming to finish */ GST_PAD_STREAM_LOCK (qtdemux->sinkpad); /* copy segment, we need this because we still need the old * segment when we close the current segment. */ memcpy (&seeksegment, &qtdemux->segment, sizeof (GstSegment)); if (event) { /* configure the segment with the seek variables */ GST_DEBUG_OBJECT (qtdemux, "configuring seek"); gst_segment_set_seek (&seeksegment, rate, format, flags, cur_type, cur, stop_type, stop, &update); } /* now do the seek, this actually never returns FALSE */ res = gst_qtdemux_perform_seek (qtdemux, &seeksegment); /* prepare for streaming again */ if (flush) { gst_pad_push_event (qtdemux->sinkpad, gst_event_new_flush_stop ()); gst_qtdemux_push_event (qtdemux, gst_event_new_flush_stop ()); } else if (qtdemux->segment_running) { /* we are running the current segment and doing a non-flushing seek, * close the segment first based on the last_stop. */ GST_DEBUG_OBJECT (qtdemux, "closing running segment %" G_GINT64_FORMAT " to %" G_GINT64_FORMAT, qtdemux->segment.start, qtdemux->segment.last_stop); if (qtdemux->segment.rate >= 0) { /* FIXME, rate is the product of the global rate and the (quicktime) * segment rate. */ qtdemux->pending_newsegment = gst_event_new_new_segment (TRUE, qtdemux->segment.rate, qtdemux->segment.format, qtdemux->segment.start, qtdemux->segment.last_stop, qtdemux->segment.time); } else { /* For Reverse Playback */ guint64 stop; if ((stop = qtdemux->segment.stop) == -1) stop = qtdemux->segment.duration; /* for reverse playback, we played from stop to last_stop. */ qtdemux->pending_newsegment = gst_event_new_new_segment (TRUE, qtdemux->segment.rate, qtdemux->segment.format, qtdemux->segment.last_stop, stop, qtdemux->segment.last_stop); } } /* commit the new segment */ memcpy (&qtdemux->segment, &seeksegment, sizeof (GstSegment)); if (qtdemux->segment.flags & GST_SEEK_FLAG_SEGMENT) { gst_element_post_message (GST_ELEMENT_CAST (qtdemux), gst_message_new_segment_start (GST_OBJECT_CAST (qtdemux), qtdemux->segment.format, qtdemux->segment.last_stop)); } /* restart streaming, NEWSEGMENT will be sent from the streaming * thread. */ qtdemux->segment_running = TRUE; for (i = 0; i < qtdemux->n_streams; i++) qtdemux->streams[i]->last_ret = GST_FLOW_OK; gst_pad_start_task (qtdemux->sinkpad, (GstTaskFunction) gst_qtdemux_loop, qtdemux->sinkpad); GST_PAD_STREAM_UNLOCK (qtdemux->sinkpad); return TRUE; /* ERRORS */ no_format: { GST_DEBUG_OBJECT (qtdemux, "unsupported format given, seek aborted."); return FALSE; } } 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 GKI_delay(UINT32 timeout_ms) { struct timespec delay; delay.tv_sec = timeout_ms / 1000; delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000); int err; do { err = nanosleep(&delay, &delay); } while (err == -1 && errno == EINTR); } 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: Response InspectorPageAgent::stopScreencast() { state_->setBoolean(PageAgentState::kScreencastEnabled, false); return Response::OK(); } 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: int ndo_dflt_fdb_del(struct ndmsg *ndm, struct nlattr *tb[], struct net_device *dev, const unsigned char *addr, u16 vid) { int err = -EINVAL; /* If aging addresses are supported device will need to * implement its own handler for this. */ if (!(ndm->ndm_state & NUD_PERMANENT)) { pr_info("%s: FDB only supports static addresses\n", dev->name); return err; } if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr)) err = dev_uc_del(dev, addr); else if (is_multicast_ether_addr(addr)) err = dev_mc_del(dev, addr); return err; } Commit Message: net: fix infoleak in rtnetlink The stack object “map” has a total size of 32 bytes. Its last 4 bytes are padding generated by compiler. These padding bytes are not initialized and sent out via “nla_put”. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: David S. Miller <[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: GpuChannelHost* BrowserGpuChannelHostFactory::EstablishGpuChannelSync( CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kLost) gpu_channel_ = NULL; else return gpu_channel_.get(); } GpuDataManagerImpl::GetInstance(); EstablishRequest request; GetIOLoopProxy()->PostTask( FROM_HERE, base::Bind( &BrowserGpuChannelHostFactory::EstablishGpuChannelOnIO, base::Unretained(this), &request, cause_for_gpu_launch)); request.event.Wait(); if (request.channel_handle.name.empty() || request.gpu_process_handle == base::kNullProcessHandle) return NULL; base::ProcessHandle browser_process_for_gpu; #if defined(OS_WIN) DuplicateHandle(base::GetCurrentProcessHandle(), base::GetCurrentProcessHandle(), request.gpu_process_handle, &browser_process_for_gpu, PROCESS_DUP_HANDLE, FALSE, 0); #else browser_process_for_gpu = base::GetCurrentProcessHandle(); #endif gpu_channel_ = new GpuChannelHost(this, gpu_host_id_, gpu_client_id_); gpu_channel_->set_gpu_info(request.gpu_info); content::GetContentClient()->SetGpuInfo(request.gpu_info); gpu_channel_->Connect(request.channel_handle, browser_process_for_gpu); return gpu_channel_.get(); } 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: 1 Example 2: Code: mojom::WindowStateType GetLastOldStateAndReset() { mojom::WindowStateType r = last_old_state_; last_old_state_ = mojom::WindowStateType::DEFAULT; return r; } Commit Message: cros: Enable some tests in //ash/wm in ash_unittests --mash For the ones that fail, disable them via filter file instead of in the code, per our disablement policy. Bug: 698085, 695556, 698878, 698888, 698093, 698894 Test: ash_unittests --mash Change-Id: Ic145ab6a95508968d6884d14fac2a3ca08888d26 Reviewed-on: https://chromium-review.googlesource.com/752423 Commit-Queue: James Cook <[email protected]> Reviewed-by: Steven Bennetts <[email protected]> Cr-Commit-Position: refs/heads/master@{#513836} 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 srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag) { struct srpt_device *sdev; struct srpt_rdma_ch *ch; struct srpt_send_ioctx *target; int ret, i; ret = -EINVAL; ch = ioctx->ch; BUG_ON(!ch); BUG_ON(!ch->sport); sdev = ch->sport->sdev; BUG_ON(!sdev); spin_lock_irq(&sdev->spinlock); for (i = 0; i < ch->rq_size; ++i) { target = ch->ioctx_ring[i]; if (target->cmd.se_lun == ioctx->cmd.se_lun && target->cmd.tag == tag && srpt_get_cmd_state(target) != SRPT_STATE_DONE) { ret = 0; /* now let the target core abort &target->cmd; */ break; } } spin_unlock_irq(&sdev->spinlock); return ret; } 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 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: _pango_emoji_iter_next (PangoEmojiIter *iter) { PangoEmojiType current_emoji_type = PANGO_EMOJI_TYPE_INVALID; if (iter->end == iter->text_end) return FALSE; iter->start = iter->end; for (; iter->end < iter->text_end; iter->end = g_utf8_next_char (iter->end)) { gunichar ch = g_utf8_get_char (iter->end); /* Except at the beginning, ZWJ just carries over the emoji or neutral * text type, VS15 & VS16 we just carry over as well, since we already * resolved those through lookahead. Also, don't downgrade to text * presentation for emoji that are part of a ZWJ sequence, example * U+1F441 U+200D U+1F5E8, eye (text presentation) + ZWJ + left speech * bubble, see below. */ if ((!(ch == kZeroWidthJoinerCharacter && !iter->is_emoji) && ch != kVariationSelector15Character && ch != kVariationSelector16Character && ch != kCombiningEnclosingCircleBackslashCharacter && !_pango_Is_Regional_Indicator(ch) && !((ch == kLeftSpeechBubbleCharacter || ch == kRainbowCharacter || ch == kMaleSignCharacter || ch == kFemaleSignCharacter || ch == kStaffOfAesculapiusCharacter) && !iter->is_emoji)) || current_emoji_type == PANGO_EMOJI_TYPE_INVALID) { current_emoji_type = _pango_get_emoji_type (ch); } if (g_utf8_next_char (iter->end) < iter->text_end) /* Optimize. */ { gunichar peek_char = g_utf8_get_char (g_utf8_next_char (iter->end)); /* Variation Selectors */ if (current_emoji_type == PANGO_EMOJI_TYPE_EMOJI_EMOJI && peek_char == kVariationSelector15Character) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_TEXT; } if ((current_emoji_type == PANGO_EMOJI_TYPE_EMOJI_TEXT || _pango_Is_Emoji_Keycap_Base(ch)) && peek_char == kVariationSelector16Character) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } /* Combining characters Keycap... */ if (_pango_Is_Emoji_Keycap_Base(ch) && peek_char == kCombiningEnclosingKeycapCharacter) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; }; /* Regional indicators */ if (_pango_Is_Regional_Indicator(ch) && _pango_Is_Regional_Indicator(peek_char)) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } /* Upgrade text presentation emoji to emoji presentation when followed by * ZWJ, Example U+1F441 U+200D U+1F5E8, eye + ZWJ + left speech bubble. */ if ((ch == kEyeCharacter || ch == kWavingWhiteFlagCharacter) && peek_char == kZeroWidthJoinerCharacter) { current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI; } } if (iter->is_emoji == (gboolean) 2) iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); if (iter->is_emoji == PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type)) { iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); return TRUE; } } iter->is_emoji = PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type); return TRUE; } Commit Message: Prevent an assertion with invalid Unicode sequences Invalid Unicode sequences, such as 0x2665 0xfe0e 0xfe0f, can trick the Emoji iter code into returning an empty segment, which then triggers an assertion in the itemizer. Prevent this by ensuring that we make progress. This issue was reported by Jeffrey M. CWE ID: CWE-119 Target: 1 Example 2: Code: void xmp_terminate() { RESET_ERROR; SXMPFiles::Terminate(); } Commit Message: 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 jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_qcd_t *qcd = &ms->parms.qcd; int i; fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n", (int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes); for (i = 0; i < qcd->compparms.numstepsizes; ++i) { fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n", i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]), i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])); } return 0; } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). 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: dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags); if (offset == 0) break; } } return 0; } Commit Message: Bail out on partial reads, from Alexander Cherepanov CWE ID: CWE-20 Target: 1 Example 2: Code: int deny_write_access(struct file * file) { struct inode *inode = file->f_path.dentry->d_inode; spin_lock(&inode->i_lock); if (atomic_read(&inode->i_writecount) > 0) { spin_unlock(&inode->i_lock); return -ETXTBSY; } atomic_dec(&inode->i_writecount); spin_unlock(&inode->i_lock); return 0; } Commit Message: fix autofs/afs/etc. magic mountpoint breakage We end up trying to kfree() nd.last.name on open("/mnt/tmp", O_CREAT) if /mnt/tmp is an autofs direct mount. The reason is that nd.last_type is bogus here; we want LAST_BIND for everything of that kind and we get LAST_NORM left over from finding parent directory. So make sure that it *is* set properly; set to LAST_BIND before doing ->follow_link() - for normal symlinks it will be changed by __vfs_follow_link() and everything else needs it set that way. Signed-off-by: Al Viro <[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: static void LongMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObject* impl = V8TestObject::ToImpl(info.Holder()); V8SetReturnValueInt(info, impl->longMethod()); } 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: char *suhosin_encrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key TSRMLS_DC) { char buffer[4096]; char buffer2[4096]; char *buf = buffer, *buf2 = buffer2, *d, *d_url; int l; if (name_len > sizeof(buffer)-2) { buf = estrndup(name, name_len); } else { memcpy(buf, name, name_len); buf[name_len] = 0; } name_len = php_url_decode(buf, name_len); normalize_varname(buf); name_len = strlen(buf); if (SUHOSIN_G(cookie_plainlist)) { if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) { encrypt_return_plain: if (buf != buffer) { efree(buf); } return estrndup(value, value_len); } } else if (SUHOSIN_G(cookie_cryptlist)) { if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) { goto encrypt_return_plain; } } if (strlen(value) <= sizeof(buffer2)-2) { memcpy(buf2, value, value_len); buf2[value_len] = 0; } else { buf2 = estrndup(value, value_len); } value_len = php_url_decode(buf2, value_len); d = suhosin_encrypt_string(buf2, value_len, buf, name_len, key TSRMLS_CC); d_url = php_url_encode(d, strlen(d), &l); efree(d); if (buf != buffer) { efree(buf); } if (buf2 != buffer2) { efree(buf2); } return d_url; } Commit Message: Fixed stack based buffer overflow in transparent cookie encryption (see separate advisory) CWE ID: CWE-119 Target: 1 Example 2: Code: static int fsmCommit(char **path, rpmfi fi, rpmFileAction action, const char *suffix) { int rc = 0; /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!(S_ISSOCK(rpmfiFMode(fi)) && IS_DEV_LOG(*path))) { const char *nsuffix = (action == FA_ALTNAME) ? SUFFIX_RPMNEW : NULL; char *dest = *path; /* Construct final destination path (nsuffix is usually NULL) */ if (suffix) dest = fsmFsPath(fi, nsuffix); /* Rename temporary to final file name if needed. */ if (dest != *path) { rc = fsmRename(*path, dest); if (!rc && nsuffix) { char * opath = fsmFsPath(fi, NULL); rpmlog(RPMLOG_WARNING, _("%s created as %s\n"), opath, dest); free(opath); } free(*path); *path = dest; } } return rc; } Commit Message: Don't follow symlinks on file creation (CVE-2017-7501) Open newly created files with O_EXCL to prevent symlink tricks. When reopening hardlinks for writing the actual content, use append mode instead. This is compatible with the write-only permissions but is not destructive in case we got redirected to somebody elses file, verify the target before actually writing anything. As these are files with the temporary suffix, errors mean a local user with sufficient privileges to break the installation of the package anyway is trying to goof us on purpose, don't bother trying to mend it (we couldn't fix the hardlink case anyhow) but just bail out. Based on a patch by Florian Festi. 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: MagickPrivate void AnnotateComponentTerminus(void) { if (annotate_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&annotate_semaphore); RelinquishSemaphoreInfo(&annotate_semaphore); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1589 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: COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len, compat_ulong_t, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, flags) { long err = 0; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; nodemask_t bm; nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { err = compat_get_bitmap(nodes_addr(bm), nmask, nr_bits); nm = compat_alloc_user_space(alloc_size); err |= copy_to_user(nm, nodes_addr(bm), alloc_size); } if (err) return -EFAULT; return sys_mbind(start, len, mode, nm, nr_bits+1, flags); } Commit Message: mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-388 Target: 1 Example 2: Code: perf_cgroup_mark_enabled(struct perf_event *event, struct perf_event_context *ctx) { } 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: static void *__dma_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flags, struct dma_attrs *attrs) { if (dev == NULL) { WARN_ONCE(1, "Use an actual device structure for DMA allocation\n"); return NULL; } if (IS_ENABLED(CONFIG_ZONE_DMA) && dev->coherent_dma_mask <= DMA_BIT_MASK(32)) flags |= GFP_DMA; if (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) { struct page *page; void *addr; size = PAGE_ALIGN(size); page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT, get_order(size)); if (!page) return NULL; *dma_handle = phys_to_dma(dev, page_to_phys(page)); addr = page_address(page); if (flags & __GFP_ZERO) memset(addr, 0, size); return addr; } else { return swiotlb_alloc_coherent(dev, size, dma_handle, flags); } } Commit Message: arm64: dma-mapping: always clear allocated buffers Buffers allocated by dma_alloc_coherent() are always zeroed on Alpha, ARM (32bit), MIPS, PowerPC, x86/x86_64 and probably other architectures. It turned out that some drivers rely on this 'feature'. Allocated buffer might be also exposed to userspace with dma_mmap() call, so clearing it is desired from security point of view to avoid exposing random memory to userspace. This patch unifies dma_alloc_coherent() behavior on ARM64 architecture with other implementations by unconditionally zeroing allocated buffer. Cc: <[email protected]> # v3.14+ Signed-off-by: Marek Szyprowski <[email protected]> Signed-off-by: Will Deacon <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ImageCapture::SetMediaTrackConstraints( ScriptPromiseResolver* resolver, const HeapVector<MediaTrackConstraintSet>& constraints_vector) { DCHECK_GT(constraints_vector.size(), 0u); if (!service_) { resolver->Reject(DOMException::Create(kNotFoundError, kNoServiceError)); return; } auto constraints = constraints_vector[0]; if ((constraints.hasWhiteBalanceMode() && !capabilities_.hasWhiteBalanceMode()) || (constraints.hasExposureMode() && !capabilities_.hasExposureMode()) || (constraints.hasFocusMode() && !capabilities_.hasFocusMode()) || (constraints.hasExposureCompensation() && !capabilities_.hasExposureCompensation()) || (constraints.hasColorTemperature() && !capabilities_.hasColorTemperature()) || (constraints.hasIso() && !capabilities_.hasIso()) || (constraints.hasBrightness() && !capabilities_.hasBrightness()) || (constraints.hasContrast() && !capabilities_.hasContrast()) || (constraints.hasSaturation() && !capabilities_.hasSaturation()) || (constraints.hasSharpness() && !capabilities_.hasSharpness()) || (constraints.hasZoom() && !capabilities_.hasZoom()) || (constraints.hasTorch() && !capabilities_.hasTorch())) { resolver->Reject( DOMException::Create(kNotSupportedError, "Unsupported constraint(s)")); return; } auto settings = media::mojom::blink::PhotoSettings::New(); MediaTrackConstraintSet temp_constraints = current_constraints_; settings->has_white_balance_mode = constraints.hasWhiteBalanceMode() && constraints.whiteBalanceMode().IsString(); if (settings->has_white_balance_mode) { const auto white_balance_mode = constraints.whiteBalanceMode().GetAsString(); if (capabilities_.whiteBalanceMode().Find(white_balance_mode) == kNotFound) { resolver->Reject(DOMException::Create(kNotSupportedError, "Unsupported whiteBalanceMode.")); return; } temp_constraints.setWhiteBalanceMode(constraints.whiteBalanceMode()); settings->white_balance_mode = ParseMeteringMode(white_balance_mode); } settings->has_exposure_mode = constraints.hasExposureMode() && constraints.exposureMode().IsString(); if (settings->has_exposure_mode) { const auto exposure_mode = constraints.exposureMode().GetAsString(); if (capabilities_.exposureMode().Find(exposure_mode) == kNotFound) { resolver->Reject(DOMException::Create(kNotSupportedError, "Unsupported exposureMode.")); return; } temp_constraints.setExposureMode(constraints.exposureMode()); settings->exposure_mode = ParseMeteringMode(exposure_mode); } settings->has_focus_mode = constraints.hasFocusMode() && constraints.focusMode().IsString(); if (settings->has_focus_mode) { const auto focus_mode = constraints.focusMode().GetAsString(); if (capabilities_.focusMode().Find(focus_mode) == kNotFound) { resolver->Reject( DOMException::Create(kNotSupportedError, "Unsupported focusMode.")); return; } temp_constraints.setFocusMode(constraints.focusMode()); settings->focus_mode = ParseMeteringMode(focus_mode); } if (constraints.hasPointsOfInterest() && constraints.pointsOfInterest().IsPoint2DSequence()) { for (const auto& point : constraints.pointsOfInterest().GetAsPoint2DSequence()) { auto mojo_point = media::mojom::blink::Point2D::New(); mojo_point->x = point.x(); mojo_point->y = point.y(); settings->points_of_interest.push_back(std::move(mojo_point)); } temp_constraints.setPointsOfInterest(constraints.pointsOfInterest()); } settings->has_exposure_compensation = constraints.hasExposureCompensation() && constraints.exposureCompensation().IsDouble(); if (settings->has_exposure_compensation) { const auto exposure_compensation = constraints.exposureCompensation().GetAsDouble(); if (exposure_compensation < capabilities_.exposureCompensation()->min() || exposure_compensation > capabilities_.exposureCompensation()->max()) { resolver->Reject(DOMException::Create( kNotSupportedError, "exposureCompensation setting out of range")); return; } temp_constraints.setExposureCompensation( constraints.exposureCompensation()); settings->exposure_compensation = exposure_compensation; } settings->has_color_temperature = constraints.hasColorTemperature() && constraints.colorTemperature().IsDouble(); if (settings->has_color_temperature) { const auto color_temperature = constraints.colorTemperature().GetAsDouble(); if (color_temperature < capabilities_.colorTemperature()->min() || color_temperature > capabilities_.colorTemperature()->max()) { resolver->Reject(DOMException::Create( kNotSupportedError, "colorTemperature setting out of range")); return; } temp_constraints.setColorTemperature(constraints.colorTemperature()); settings->color_temperature = color_temperature; } settings->has_iso = constraints.hasIso() && constraints.iso().IsDouble(); if (settings->has_iso) { const auto iso = constraints.iso().GetAsDouble(); if (iso < capabilities_.iso()->min() || iso > capabilities_.iso()->max()) { resolver->Reject( DOMException::Create(kNotSupportedError, "iso setting out of range")); return; } temp_constraints.setIso(constraints.iso()); settings->iso = iso; } settings->has_brightness = constraints.hasBrightness() && constraints.brightness().IsDouble(); if (settings->has_brightness) { const auto brightness = constraints.brightness().GetAsDouble(); if (brightness < capabilities_.brightness()->min() || brightness > capabilities_.brightness()->max()) { resolver->Reject(DOMException::Create(kNotSupportedError, "brightness setting out of range")); return; } temp_constraints.setBrightness(constraints.brightness()); settings->brightness = brightness; } settings->has_contrast = constraints.hasContrast() && constraints.contrast().IsDouble(); if (settings->has_contrast) { const auto contrast = constraints.contrast().GetAsDouble(); if (contrast < capabilities_.contrast()->min() || contrast > capabilities_.contrast()->max()) { resolver->Reject(DOMException::Create(kNotSupportedError, "contrast setting out of range")); return; } temp_constraints.setContrast(constraints.contrast()); settings->contrast = contrast; } settings->has_saturation = constraints.hasSaturation() && constraints.saturation().IsDouble(); if (settings->has_saturation) { const auto saturation = constraints.saturation().GetAsDouble(); if (saturation < capabilities_.saturation()->min() || saturation > capabilities_.saturation()->max()) { resolver->Reject(DOMException::Create(kNotSupportedError, "saturation setting out of range")); return; } temp_constraints.setSaturation(constraints.saturation()); settings->saturation = saturation; } settings->has_sharpness = constraints.hasSharpness() && constraints.sharpness().IsDouble(); if (settings->has_sharpness) { const auto sharpness = constraints.sharpness().GetAsDouble(); if (sharpness < capabilities_.sharpness()->min() || sharpness > capabilities_.sharpness()->max()) { resolver->Reject(DOMException::Create(kNotSupportedError, "sharpness setting out of range")); return; } temp_constraints.setSharpness(constraints.sharpness()); settings->sharpness = sharpness; } settings->has_zoom = constraints.hasZoom() && constraints.zoom().IsDouble(); if (settings->has_zoom) { const auto zoom = constraints.zoom().GetAsDouble(); if (zoom < capabilities_.zoom()->min() || zoom > capabilities_.zoom()->max()) { resolver->Reject(DOMException::Create(kNotSupportedError, "zoom setting out of range")); return; } temp_constraints.setZoom(constraints.zoom()); settings->zoom = zoom; } settings->has_torch = constraints.hasTorch() && constraints.torch().IsBoolean(); if (settings->has_torch) { const auto torch = constraints.torch().GetAsBoolean(); if (torch && !capabilities_.torch()) { resolver->Reject( DOMException::Create(kNotSupportedError, "torch not supported")); return; } temp_constraints.setTorch(constraints.torch()); settings->torch = torch; } current_constraints_ = temp_constraints; service_requests_.insert(resolver); MediaTrackConstraints resolver_constraints; resolver_constraints.setAdvanced(constraints_vector); auto resolver_cb = WTF::Bind(&ImageCapture::ResolveWithMediaTrackConstraints, WrapPersistent(this), resolver_constraints); service_->SetOptions( stream_track_->Component()->Source()->Id(), std::move(settings), ConvertToBaseCallback(WTF::Bind( &ImageCapture::OnMojoSetOptions, WrapPersistent(this), WrapPersistent(resolver), WTF::Passed(std::move(resolver_cb)), false /* trigger_take_photo */))); } Commit Message: Convert MediaTrackConstraints to a ScriptValue IDLDictionaries such as MediaTrackConstraints should not be stored on the heap which would happen when binding one as a parameter to a callback. This change converts the object to a ScriptValue ahead of time. This is fine because the value will be passed to a ScriptPromiseResolver that will converted it to a V8 value if it isn't already. Bug: 759457 Change-Id: I3009a0f7711cc264aeaae07a36c18a6db8c915c8 Reviewed-on: https://chromium-review.googlesource.com/701358 Reviewed-by: Kentaro Hara <[email protected]> Commit-Queue: Reilly Grant <[email protected]> Cr-Commit-Position: refs/heads/master@{#507177} CWE ID: CWE-416 Target: 1 Example 2: Code: static int csnmp_shutdown(void) { data_definition_t *data_this; data_definition_t *data_next; /* When we get here, the read threads have been stopped and all the * `host_definition_t' will be freed. */ DEBUG("snmp plugin: Destroying all data definitions."); data_this = data_head; data_head = NULL; while (data_this != NULL) { data_next = data_this->next; sfree(data_this->name); sfree(data_this->type); sfree(data_this->values); sfree(data_this->ignores); sfree(data_this); data_this = data_next; } return (0); } /* int csnmp_shutdown */ Commit Message: snmp plugin: Fix double free of request PDU snmp_sess_synch_response() always frees request PDU, in both case of request error and success. If error condition occurs inside of `while (status == 0)` loop, double free of `req` happens. Issue: #2291 Signed-off-by: Florian Forster <[email protected]> CWE ID: CWE-415 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 ExtensionTtsSpeakFunction::SpeechFinished() { error_ = utterance_->error(); bool success = error_.empty(); SendResponse(success); Release(); // Balanced in RunImpl(). } 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: void fslib_copy_libs(const char *full_path) { assert(full_path); if (arg_debug || arg_debug_private_lib) printf(" fslib_copy_libs %s\n", full_path); if (access(full_path, R_OK)) { if (arg_debug || arg_debug_private_lib) printf("cannot find %s for private-lib, skipping...\n", full_path); return; } unlink(RUN_LIB_FILE); // in case is there create_empty_file_as_root(RUN_LIB_FILE, 0644); if (chown(RUN_LIB_FILE, getuid(), getgid())) errExit("chown"); if (arg_debug || arg_debug_private_lib) printf(" running fldd %s\n", full_path); sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE); FILE *fp = fopen(RUN_LIB_FILE, "r"); if (!fp) errExit("fopen"); char buf[MAXBUF]; while (fgets(buf, MAXBUF, fp)) { char *ptr = strchr(buf, '\n'); if (ptr) *ptr = '\0'; fslib_duplicate(buf); } fclose(fp); } Commit Message: mount runtime seccomp files read-only (#2602) avoid creating locations in the file system that are both writable and executable (in this case for processes with euid of the user). for the same reason also remove user owned libfiles when it is not needed any more CWE ID: CWE-284 Target: 1 Example 2: Code: static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg) { struct megasas_instance *instance; struct megasas_aen aen; int error; if (file->private_data != file) { printk(KERN_DEBUG "megasas: fasync_helper was not " "called first\n"); return -EINVAL; } if (copy_from_user(&aen, (void __user *)arg, sizeof(aen))) return -EFAULT; instance = megasas_lookup_instance(aen.host_no); if (!instance) return -ENODEV; if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { return -ENODEV; } if (instance->unload == 1) { return -ENODEV; } if (megasas_wait_for_adapter_operational(instance)) return -ENODEV; mutex_lock(&instance->reset_mutex); error = megasas_register_aen(instance, aen.seq_num, aen.class_locale_word); mutex_unlock(&instance->reset_mutex); return error; } 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: int genl_register_family(struct genl_family *family) { int err, i; int start = GENL_START_ALLOC, end = GENL_MAX_ID; err = genl_validate_ops(family); if (err) return err; genl_lock_all(); if (genl_family_find_byname(family->name)) { err = -EEXIST; goto errout_locked; } /* * Sadly, a few cases need to be special-cased * due to them having previously abused the API * and having used their family ID also as their * multicast group ID, so we use reserved IDs * for both to be sure we can do that mapping. */ if (family == &genl_ctrl) { /* and this needs to be special for initial family lookups */ start = end = GENL_ID_CTRL; } else if (strcmp(family->name, "pmcraid") == 0) { start = end = GENL_ID_PMCRAID; } else if (strcmp(family->name, "VFS_DQUOT") == 0) { start = end = GENL_ID_VFS_DQUOT; } if (family->maxattr && !family->parallel_ops) { family->attrbuf = kmalloc_array(family->maxattr + 1, sizeof(struct nlattr *), GFP_KERNEL); if (family->attrbuf == NULL) { err = -ENOMEM; goto errout_locked; } } else family->attrbuf = NULL; family->id = idr_alloc(&genl_fam_idr, family, start, end + 1, GFP_KERNEL); if (family->id < 0) { err = family->id; goto errout_locked; } err = genl_validate_assign_mc_groups(family); if (err) goto errout_remove; genl_unlock_all(); /* send all events */ genl_ctrl_event(CTRL_CMD_NEWFAMILY, family, NULL, 0); for (i = 0; i < family->n_mcgrps; i++) genl_ctrl_event(CTRL_CMD_NEWMCAST_GRP, family, &family->mcgrps[i], family->mcgrp_offset + i); return 0; errout_remove: idr_remove(&genl_fam_idr, family->id); kfree(family->attrbuf); errout_locked: genl_unlock_all(); return err; } Commit Message: genetlink: Fix a memory leak on error path In genl_register_family(), when idr_alloc() fails, we forget to free the memory we possibly allocate for family->attrbuf. Reported-by: Hulk Robot <[email protected]> Fixes: 2ae0f17df1cd ("genetlink: use idr to track families") Signed-off-by: YueHaibing <[email protected]> Reviewed-by: Kirill Tkhai <[email protected]> Signed-off-by: David S. Miller <[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: void WebGL2RenderingContextBase::texImage3D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, MaybeShared<DOMArrayBufferView> pixels) { TexImageHelperDOMArrayBufferView(kTexImage3D, target, level, internalformat, width, height, depth, border, format, type, 0, 0, 0, pixels.View(), kNullAllowed, 0); } Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA. BUG=774174 TEST=https://github.com/KhronosGroup/WebGL/pull/2555 [email protected] Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;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: I4f4e7636314502451104730501a5048a5d7b9f3f Reviewed-on: https://chromium-review.googlesource.com/808665 Commit-Queue: Zhenyao Mo <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#522003} CWE ID: CWE-125 Target: 1 Example 2: Code: static int sctp_setsockopt_adaptation_layer(struct sock *sk, char __user *optval, int optlen) { struct sctp_setadaptation adaptation; if (optlen != sizeof(struct sctp_setadaptation)) return -EINVAL; if (copy_from_user(&adaptation, optval, optlen)) return -EFAULT; sctp_sk(sk)->adaptation_ind = adaptation.ssb_adaptation_ind; return 0; } Commit Message: [SCTP]: Fix assertion (!atomic_read(&sk->sk_rmem_alloc)) failed message In current implementation, LKSCTP does receive buffer accounting for data in sctp_receive_queue and pd_lobby. However, LKSCTP don't do accounting for data in frag_list when data is fragmented. In addition, LKSCTP doesn't do accounting for data in reasm and lobby queue in structure sctp_ulpq. When there are date in these queue, assertion failed message is printed in inet_sock_destruct because sk_rmem_alloc of oldsk does not become 0 when socket is destroyed. Signed-off-by: Tsutomu Fujii <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: mux_exit_message(Channel *c, int exitval) { Buffer m; Channel *mux_chan; debug3("%s: channel %d: exit message, exitval %d", __func__, c->self, exitval); if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL) fatal("%s: channel %d missing mux channel %d", __func__, c->self, c->ctl_chan); /* Append exit message packet to control socket output queue */ buffer_init(&m); buffer_put_int(&m, MUX_S_EXIT_MESSAGE); buffer_put_int(&m, c->self); buffer_put_int(&m, exitval); buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m)); buffer_free(&m); } Commit Message: 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: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if((ps_dec->ps_out_buffer->u4_num_bufs == 0) || (ps_dec->ps_out_buffer->u4_num_bufs > IVD_VIDDEC_MAX_IO_BUFFERS)) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm) { if(ps_dec->u1_init_dec_flag == 0) { /*Come out of flush mode and return*/ ps_dec->u1_flushfrm = 0; return (IV_FAIL); } ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { /* check output buffer size given by the application */ if(check_app_out_buf_size(ps_dec) != IV_SUCCESS) { ps_dec_op->u4_error_code= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return (IV_FAIL); } ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; ps_dec->u4_sps_cnt_in_process = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, buf_size - 8); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T) || (ret == IVD_DISP_FRM_ZERO_OP_BUF_SIZE)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_pic_buf_got == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_pic_buf_got == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } else { ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Increased allocation and added checks in sei parsing. This prevents heap overflow while parsing sei_message. Bug: 63122634 Test: ran PoC on unpatched/patched Change-Id: I61c1ff4ac053a060be8c24da4671db985cac628c (cherry picked from commit f2b70d353768af8d4ead7f32497be05f197925ef) CWE ID: CWE-200 Target: 1 Example 2: Code: void RenderViewImpl::OnSetInitialFocus(bool reverse) { if (!webview()) return; webview()->SetInitialFocus(reverse); } 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: key_ref_t find_key_to_update(key_ref_t keyring_ref, const struct keyring_index_key *index_key) { struct key *keyring, *key; const void *object; keyring = key_ref_to_ptr(keyring_ref); kenter("{%d},{%s,%s}", keyring->serial, index_key->type->name, index_key->description); object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops, index_key); if (object) goto found; kleave(" = NULL"); return NULL; found: key = keyring_ptr_to_key(object); if (key->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED))) { kleave(" = NULL [x]"); return NULL; } __key_get(key); kleave(" = {%d}", key->serial); return make_key_ref(key, is_key_possessed(keyring_ref)); } Commit Message: KEYS: ensure we free the assoc array edit if edit is valid __key_link_end is not freeing the associated array edit structure and this leads to a 512 byte memory leak each time an identical existing key is added with add_key(). The reason the add_key() system call returns okay is that key_create_or_update() calls __key_link_begin() before checking to see whether it can update a key directly rather than adding/replacing - which it turns out it can. Thus __key_link() is not called through __key_instantiate_and_link() and __key_link_end() must cancel the edit. CVE-2015-1333 Signed-off-by: Colin Ian King <[email protected]> Signed-off-by: David Howells <[email protected]> Signed-off-by: James Morris <[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: void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); Stream_Write_UINT32(s, header->MessageType); } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125 Target: 1 Example 2: Code: int ib_send_cm_rep(struct ib_cm_id *cm_id, struct ib_cm_rep_param *param) { struct cm_id_private *cm_id_priv; struct ib_mad_send_buf *msg; struct cm_rep_msg *rep_msg; unsigned long flags; int ret; if (param->private_data && param->private_data_len > IB_CM_REP_PRIVATE_DATA_SIZE) return -EINVAL; cm_id_priv = container_of(cm_id, struct cm_id_private, id); spin_lock_irqsave(&cm_id_priv->lock, flags); if (cm_id->state != IB_CM_REQ_RCVD && cm_id->state != IB_CM_MRA_REQ_SENT) { ret = -EINVAL; goto out; } ret = cm_alloc_msg(cm_id_priv, &msg); if (ret) goto out; rep_msg = (struct cm_rep_msg *) msg->mad; cm_format_rep(rep_msg, cm_id_priv, param); msg->timeout_ms = cm_id_priv->timeout_ms; msg->context[1] = (void *) (unsigned long) IB_CM_REP_SENT; ret = ib_post_send_mad(msg, NULL); if (ret) { spin_unlock_irqrestore(&cm_id_priv->lock, flags); cm_free_msg(msg); return ret; } cm_id->state = IB_CM_REP_SENT; cm_id_priv->msg = msg; cm_id_priv->initiator_depth = param->initiator_depth; cm_id_priv->responder_resources = param->responder_resources; cm_id_priv->rq_psn = cm_rep_get_starting_psn(rep_msg); cm_id_priv->local_qpn = cpu_to_be32(param->qp_num & 0xFFFFFF); out: spin_unlock_irqrestore(&cm_id_priv->lock, flags); return ret; } Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler The code that resolves the passive side source MAC within the rdma_cm connection request handler was both redundant and buggy, so remove it. It was redundant since later, when an RC QP is modified to RTR state, the resolution will take place in the ib_core module. It was buggy because this callback also deals with UD SIDR exchange, for which we incorrectly looked at the REQ member of the CM event and dereferenced a random value. Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures") Signed-off-by: Moni Shoua <[email protected]> Signed-off-by: Or Gerlitz <[email protected]> Signed-off-by: Roland Dreier <[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: status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) { status_t res = OK; size_t startIndex = 0; if (mStatusWaiters == 0) { mRecentStatusUpdates.clear(); } else { startIndex = mRecentStatusUpdates.size(); } mStatusWaiters++; bool stateSeen = false; do { if (active == (mStatus == STATUS_ACTIVE)) { break; } res = mStatusChanged.waitRelative(mLock, timeout); if (res != OK) break; LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(), "%s: Skipping status updates in Camera3Device, may result in deadlock.", __FUNCTION__); for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) { if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) { stateSeen = true; break; } } } while (!stateSeen); mStatusWaiters--; return res; } 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 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 fht4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fht4x4_c(in, out, stride, tx_type); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: externalParEntProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { const char *next = s; int tok; tok = XmlPrologTok(parser->m_encoding, s, end, &next); if (tok <= 0) { if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { *nextPtr = s; return XML_ERROR_NONE; } switch (tok) { case XML_TOK_INVALID: return XML_ERROR_INVALID_TOKEN; case XML_TOK_PARTIAL: return XML_ERROR_UNCLOSED_TOKEN; case XML_TOK_PARTIAL_CHAR: return XML_ERROR_PARTIAL_CHAR; case XML_TOK_NONE: /* start == end */ default: break; } } /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM. However, when parsing an external subset, doProlog will not accept a BOM as valid, and report a syntax error, so we have to skip the BOM */ else if (tok == XML_TOK_BOM) { s = next; tok = XmlPrologTok(parser->m_encoding, s, end, &next); } parser->m_processor = prologProcessor; return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); } Commit Message: xmlparse.c: Fix extraction of namespace prefix from XML name (#186) CWE ID: CWE-611 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 xmlNodePtr check_and_resolve_href(xmlNodePtr data) { if (data && data->properties) { xmlAttrPtr href; href = data->properties; while (1) { href = get_attribute(href, "href"); if (href == NULL || href->ns == NULL) {break;} href = href->next; } if (href) { /* Internal href try and find node */ if (href->children->content[0] == '#') { xmlNodePtr ret = get_node_with_attribute_recursive(data->doc->children, NULL, "id", (char*)&href->children->content[1]); if (!ret) { soap_error1(E_ERROR, "Encoding: Unresolved reference '%s'", href->children->content); } return ret; } else { /* TODO: External href....? */ soap_error1(E_ERROR, "Encoding: External reference '%s'", href->children->content); } } /* SOAP 1.2 enc:id enc:ref */ href = get_attribute_ex(data->properties, "ref", SOAP_1_2_ENC_NAMESPACE); if (href) { xmlChar* id; xmlNodePtr ret; if (href->children->content[0] == '#') { id = href->children->content+1; } else { id = href->children->content; } ret = get_node_with_attribute_recursive_ex(data->doc->children, NULL, NULL, "id", (char*)id, SOAP_1_2_ENC_NAMESPACE); if (!ret) { soap_error1(E_ERROR, "Encoding: Unresolved reference '%s'", href->children->content); } else if (ret == data) { soap_error1(E_ERROR, "Encoding: Violation of id and ref information items '%s'", href->children->content); } return ret; } } return data; } 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: ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct sock *sk = sock->sk; struct tcp_splice_state tss = { .pipe = pipe, .len = len, .flags = flags, }; long timeo; ssize_t spliced; int ret; sock_rps_record_flow(sk); /* * We can't seek on a socket input */ if (unlikely(*ppos)) return -ESPIPE; ret = spliced = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK); while (tss.len) { ret = __tcp_splice_read(sk, &tss); if (ret < 0) break; else if (!ret) { if (spliced) break; if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { ret = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { /* * This occurs when user tries to read * from never connected socket. */ if (!sock_flag(sk, SOCK_DONE)) ret = -ENOTCONN; break; } if (!timeo) { ret = -EAGAIN; break; } sk_wait_data(sk, &timeo, NULL); if (signal_pending(current)) { ret = sock_intr_errno(timeo); break; } continue; } tss.len -= ret; spliced += ret; if (!timeo) break; release_sock(sk); lock_sock(sk); if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || signal_pending(current)) break; } release_sock(sk); if (spliced) return spliced; return ret; } Commit Message: tcp: avoid infinite loop in tcp_splice_read() Splicing from TCP socket is vulnerable when a packet with URG flag is received and stored into receive queue. __tcp_splice_read() returns 0, and sk_wait_data() immediately returns since there is the problematic skb in queue. This is a nice way to burn cpu (aka infinite loop) and trigger soft lockups. Again, this gem was found by syzkaller tool. Fixes: 9c55e01c0cc8 ("[TCP]: Splice receive support.") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Dmitry Vyukov <[email protected]> Cc: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-835 Target: 1 Example 2: Code: static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf, size_t count, loff_t *ppos) { struct inode * inode = file->f_path.dentry->d_inode; char *page; ssize_t length; struct task_struct *task = get_proc_task(inode); length = -ESRCH; if (!task) goto out_no_task; if (count > PAGE_SIZE) count = PAGE_SIZE; /* No partial writes. */ length = -EINVAL; if (*ppos != 0) goto out; length = -ENOMEM; page = (char*)__get_free_page(GFP_TEMPORARY); if (!page) goto out; length = -EFAULT; if (copy_from_user(page, buf, count)) goto out_free; /* Guard against adverse ptrace interaction */ length = mutex_lock_interruptible(&task->cred_guard_mutex); if (length < 0) goto out_free; length = security_setprocattr(task, (char*)file->f_path.dentry->d_name.name, (void*)page, count); mutex_unlock(&task->cred_guard_mutex); out_free: free_page((unsigned long) page); out: put_task_struct(task); out_no_task: return length; } Commit Message: fix autofs/afs/etc. magic mountpoint breakage We end up trying to kfree() nd.last.name on open("/mnt/tmp", O_CREAT) if /mnt/tmp is an autofs direct mount. The reason is that nd.last_type is bogus here; we want LAST_BIND for everything of that kind and we get LAST_NORM left over from finding parent directory. So make sure that it *is* set properly; set to LAST_BIND before doing ->follow_link() - for normal symlinks it will be changed by __vfs_follow_link() and everything else needs it set that way. Signed-off-by: Al Viro <[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: static Image *ReadTGAImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; PixelPacket pixel; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; size_t base, flag, offset, real, skip; ssize_t count, y; TGAInfo tga_info; unsigned char j, k, pixels[4], runlength; unsigned int alpha_bits; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read TGA header information. */ count=ReadBlob(image,1,&tga_info.id_length); tga_info.colormap_type=(unsigned char) ReadBlobByte(image); tga_info.image_type=(TGAImageType) ReadBlobByte(image); if ((count != 1) || ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARGB) && (tga_info.image_type != TGAMonochrome) && (tga_info.image_type != TGARLEColormap) && (tga_info.image_type != TGARLERGB) && (tga_info.image_type != TGARLEMonochrome)) || (((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGARLEColormap)) && (tga_info.colormap_type == 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); tga_info.colormap_index=ReadBlobLSBShort(image); tga_info.colormap_length=ReadBlobLSBShort(image); tga_info.colormap_size=(unsigned char) ReadBlobByte(image); tga_info.x_origin=ReadBlobLSBShort(image); tga_info.y_origin=ReadBlobLSBShort(image); tga_info.width=(unsigned short) ReadBlobLSBShort(image); tga_info.height=(unsigned short) ReadBlobLSBShort(image); tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image); tga_info.attributes=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) && (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image structure. */ image->columns=tga_info.width; image->rows=tga_info.height; alpha_bits=(tga_info.attributes & 0x0FU); image->matte=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) || (tga_info.colormap_size == 32) ? MagickTrue : MagickFalse; if ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARLEColormap)) image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 : (tga_info.bits_per_pixel <= 16) ? 5 : (tga_info.bits_per_pixel == 24) ? 8 : (tga_info.bits_per_pixel == 32) ? 8 : 8); else image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 : (tga_info.colormap_size <= 16) ? 5 : (tga_info.colormap_size == 24) ? 8 : (tga_info.colormap_size == 32) ? 8 : 8); if ((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGAMonochrome) || (tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome)) image->storage_class=PseudoClass; image->compression=NoCompression; if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome)) image->compression=RLECompression; if (image->storage_class == PseudoClass) { if (tga_info.colormap_type != 0) image->colors=tga_info.colormap_length; else { size_t one; one=1; image->colors=one << tga_info.bits_per_pixel; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (tga_info.id_length != 0) { char *comment; size_t length; /* TGA image comment. */ length=(size_t) tga_info.id_length; comment=(char *) NULL; if (~length >= (MaxTextExtent-1)) comment=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment); comment[tga_info.id_length]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); } if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); pixel.opacity=(Quantum) OpaqueOpacity; if (tga_info.colormap_type != 0) { /* Read TGA raster colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) { switch (tga_info.colormap_size) { case 8: default: { /* Gray scale. */ pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=pixel.red; pixel.blue=pixel.red; break; } case 15: case 16: { QuantumAny range; /* 5 bits each of red green and blue. */ j=(unsigned char) ReadBlobByte(image); k=(unsigned char) ReadBlobByte(image); range=GetQuantumRange(5UL); pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range); pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+ (1UL*(j & 0xe0) >> 5),range); pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range); break; } case 24: { /* 8 bits each of blue, green and red. */ pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); break; } case 32: { /* 8 bits each of blue, green, red, and alpha. */ pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum( (unsigned char) ReadBlobByte(image))); break; } } image->colormap[i]=pixel; } } /* Convert TGA pixels to pixel packets. */ base=0; flag=0; skip=MagickFalse; real=0; index=(IndexPacket) 0; runlength=0; offset=0; for (y=0; y < (ssize_t) image->rows; y++) { real=offset; if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0) real=image->rows-real-1; q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLERGB) || (tga_info.image_type == TGARLEMonochrome)) { if (runlength != 0) { runlength--; skip=flag != 0; } else { count=ReadBlob(image,1,&runlength); if (count == 0) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); flag=runlength & 0x80; if (flag != 0) runlength-=128; skip=MagickFalse; } } if (skip == MagickFalse) switch (tga_info.bits_per_pixel) { case 8: default: { /* Gray scale. */ index=(IndexPacket) ReadBlobByte(image); if (tga_info.colormap_type != 0) pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image, 1UL*index)]; else { pixel.red=ScaleCharToQuantum((unsigned char) index); pixel.green=ScaleCharToQuantum((unsigned char) index); pixel.blue=ScaleCharToQuantum((unsigned char) index); } break; } case 15: case 16: { QuantumAny range; /* 5 bits each of RGB; */ if (ReadBlob(image,2,pixels) != 2) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); j=pixels[0]; k=pixels[1]; range=GetQuantumRange(5UL); pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range); pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+ (1UL*(j & 0xe0) >> 5),range); pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range); if (image->matte != MagickFalse) pixel.opacity=(k & 0x80) == 0 ? (Quantum) OpaqueOpacity : (Quantum) TransparentOpacity; if (image->storage_class == PseudoClass) index=ConstrainColormapIndex(image,((size_t) k << 8)+j); break; } case 24: { /* BGR pixels. */ if (ReadBlob(image,3,pixels) != 3) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=ScaleCharToQuantum(pixels[0]); pixel.green=ScaleCharToQuantum(pixels[1]); pixel.red=ScaleCharToQuantum(pixels[2]); break; } case 32: { /* BGRA pixels. */ if (ReadBlob(image,4,pixels) != 4) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=ScaleCharToQuantum(pixels[0]); pixel.green=ScaleCharToQuantum(pixels[1]); pixel.red=ScaleCharToQuantum(pixels[2]); pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum( pixels[3])); break; } } if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,index); SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); if (image->matte != MagickFalse) SetPixelOpacity(q,pixel.opacity); q++; } if (((tga_info.attributes & 0xc0) >> 6) == 4) offset+=4; else if (((tga_info.attributes & 0xc0) >> 6) == 2) offset+=2; else offset++; if (offset >= image->rows) { base++; offset=base; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION( locale_get_script ) { get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125 Target: 1 Example 2: Code: void TheMethod() {} Commit Message: Convert Uses of base::RepeatingCallback<>::Equals to Use == or != in //base Staging this change because some conversions will have semantic changes. BUG=937566 Change-Id: I2d4950624c0fab00e107814421a161e43da965cc Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1507245 Reviewed-by: Gabriel Charette <[email protected]> Commit-Queue: Gabriel Charette <[email protected]> Cr-Commit-Position: refs/heads/master@{#639702} 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 Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value) { setAttribute(attributeName, String::number(value)); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: static int decode_map(codebook *s, oggpack_buffer *b, ogg_int32_t *v, int point){ ogg_uint32_t entry = decode_packed_entry_number(s,b); int i; if(oggpack_eop(b))return(-1); /* 1 used by test file 0 */ /* according to decode type */ switch(s->dec_type){ case 1:{ /* packed vector of values */ int mask=(1<<s->q_bits)-1; for(i=0;i<s->dim;i++){ v[i]=entry&mask; entry>>=s->q_bits; } break; } case 2:{ /* packed vector of column offsets */ int mask=(1<<s->q_pack)-1; for(i=0;i<s->dim;i++){ if(s->q_bits<=8) v[i]=((unsigned char *)(s->q_val))[entry&mask]; else v[i]=((ogg_uint16_t *)(s->q_val))[entry&mask]; entry>>=s->q_pack; } break; } case 3:{ /* offset into array */ void *ptr=((char *)s->q_val)+entry*s->q_pack; if(s->q_bits<=8){ for(i=0;i<s->dim;i++) v[i]=((unsigned char *)ptr)[i]; }else{ for(i=0;i<s->dim;i++) v[i]=((ogg_uint16_t *)ptr)[i]; } break; } default: return -1; } /* we have the unpacked multiplicands; compute final vals */ { int shiftM = point-s->q_delp; ogg_int32_t add = point-s->q_minp; int mul = s->q_del; if(add>0) add= s->q_min >> add; else add= s->q_min << -add; if (shiftM<0) { mul <<= -shiftM; shiftM = 0; } add <<= shiftM; for(i=0;i<s->dim;i++) v[i]= ((add + v[i] * mul) >> shiftM); if(s->q_seq) for(i=1;i<s->dim;i++) v[i]+=v[i-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 Target: 1 Example 2: Code: void Document::scheduleStyleRecalc() { if (shouldDisplaySeamlesslyWithParent()) { ownerElement()->setNeedsStyleRecalc(); ownerElement()->document()->scheduleStyleRecalc(); return; } if (m_styleRecalcTimer.isActive() || inPageCache()) return; ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce); if (!documentsThatNeedStyleRecalc) documentsThatNeedStyleRecalc = new HashSet<Document*>; documentsThatNeedStyleRecalc->add(this); invalidateAccessKeyMap(); m_styleRecalcTimer.startOneShot(0); InspectorInstrumentation::didScheduleStyleRecalculation(this); } 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: int BassBoost_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; int32_t param2; char *name; switch (param){ case BASSBOOST_PARAM_STRENGTH_SUPPORTED: if (*pValueSize != sizeof(uint32_t)){ ALOGV("\tLVM_ERROR : BassBoost_getParameter() invalid pValueSize1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(uint32_t); break; case BASSBOOST_PARAM_STRENGTH: if (*pValueSize != sizeof(int16_t)){ ALOGV("\tLVM_ERROR : BassBoost_getParameter() invalid pValueSize2 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; default: ALOGV("\tLVM_ERROR : BassBoost_getParameter() invalid param %d", param); return -EINVAL; } switch (param){ case BASSBOOST_PARAM_STRENGTH_SUPPORTED: *(uint32_t *)pValue = 1; break; case BASSBOOST_PARAM_STRENGTH: *(int16_t *)pValue = BassGetStrength(pContext); break; default: ALOGV("\tLVM_ERROR : BassBoost_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end BassBoost_getParameter */ 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