instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: server_request_direct_streamlocal(void) { Channel *c = NULL; char *target, *originator; u_short originator_port; target = packet_get_string(NULL); originator = packet_get_string(NULL); originator_port = packet_get_int(); packet_check_eom(); debug("server_request_direct_streamlocal: originator %s port %d, target %s", originator, originator_port, target); /* XXX fine grained permissions */ if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 && !no_port_forwarding_flag && !options.disable_forwarding) { c = channel_connect_to_path(target, "[email protected]", "direct-streamlocal"); } else { logit("refused streamlocal port forward: " "originator %s port %d, target %s", originator, originator_port, target); } free(originator); free(target); return c; } Commit Message: disable Unix-domain socket forwarding when privsep is disabled CWE ID: CWE-264
server_request_direct_streamlocal(void) { Channel *c = NULL; char *target, *originator; u_short originator_port; target = packet_get_string(NULL); originator = packet_get_string(NULL); originator_port = packet_get_int(); packet_check_eom(); debug("server_request_direct_streamlocal: originator %s port %d, target %s", originator, originator_port, target); /* XXX fine grained permissions */ if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 && !no_port_forwarding_flag && !options.disable_forwarding && use_privsep) { c = channel_connect_to_path(target, "[email protected]", "direct-streamlocal"); } else { logit("refused streamlocal port forward: " "originator %s port %d, target %s", originator, originator_port, target); } free(originator); free(target); return c; }
168,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int aac_send_raw_srb(struct aac_dev* dev, void __user * arg) { struct fib* srbfib; int status; struct aac_srb *srbcmd = NULL; struct user_aac_srb *user_srbcmd = NULL; struct user_aac_srb __user *user_srb = arg; struct aac_srb_reply __user *user_reply; struct aac_srb_reply* reply; u32 fibsize = 0; u32 flags = 0; s32 rcode = 0; u32 data_dir; void __user *sg_user[32]; void *sg_list[32]; u32 sg_indx = 0; u32 byte_count = 0; u32 actual_fibsize64, actual_fibsize = 0; int i; if (dev->in_reset) { dprintk((KERN_DEBUG"aacraid: send raw srb -EBUSY\n")); return -EBUSY; } if (!capable(CAP_SYS_ADMIN)){ dprintk((KERN_DEBUG"aacraid: No permission to send raw srb\n")); return -EPERM; } /* * Allocate and initialize a Fib then setup a SRB command */ if (!(srbfib = aac_fib_alloc(dev))) { return -ENOMEM; } aac_fib_init(srbfib); /* raw_srb FIB is not FastResponseCapable */ srbfib->hw_fib_va->header.XferState &= ~cpu_to_le32(FastResponseCapable); srbcmd = (struct aac_srb*) fib_data(srbfib); memset(sg_list, 0, sizeof(sg_list)); /* cleanup may take issue */ if(copy_from_user(&fibsize, &user_srb->count,sizeof(u32))){ dprintk((KERN_DEBUG"aacraid: Could not copy data size from user\n")); rcode = -EFAULT; goto cleanup; } if (fibsize > (dev->max_fib_size - sizeof(struct aac_fibhdr))) { rcode = -EINVAL; goto cleanup; } user_srbcmd = kmalloc(fibsize, GFP_KERNEL); if (!user_srbcmd) { dprintk((KERN_DEBUG"aacraid: Could not make a copy of the srb\n")); rcode = -ENOMEM; goto cleanup; } if(copy_from_user(user_srbcmd, user_srb,fibsize)){ dprintk((KERN_DEBUG"aacraid: Could not copy srb from user\n")); rcode = -EFAULT; goto cleanup; } user_reply = arg+fibsize; flags = user_srbcmd->flags; /* from user in cpu order */ srbcmd->function = cpu_to_le32(SRBF_ExecuteScsi); // Force this srbcmd->channel = cpu_to_le32(user_srbcmd->channel); srbcmd->id = cpu_to_le32(user_srbcmd->id); srbcmd->lun = cpu_to_le32(user_srbcmd->lun); srbcmd->timeout = cpu_to_le32(user_srbcmd->timeout); srbcmd->flags = cpu_to_le32(flags); srbcmd->retry_limit = 0; // Obsolete parameter srbcmd->cdb_size = cpu_to_le32(user_srbcmd->cdb_size); memcpy(srbcmd->cdb, user_srbcmd->cdb, sizeof(srbcmd->cdb)); switch (flags & (SRB_DataIn | SRB_DataOut)) { case SRB_DataOut: data_dir = DMA_TO_DEVICE; break; case (SRB_DataIn | SRB_DataOut): data_dir = DMA_BIDIRECTIONAL; break; case SRB_DataIn: data_dir = DMA_FROM_DEVICE; break; default: data_dir = DMA_NONE; } if (user_srbcmd->sg.count > ARRAY_SIZE(sg_list)) { dprintk((KERN_DEBUG"aacraid: too many sg entries %d\n", le32_to_cpu(srbcmd->sg.count))); rcode = -EINVAL; goto cleanup; } actual_fibsize = sizeof(struct aac_srb) - sizeof(struct sgentry) + ((user_srbcmd->sg.count & 0xff) * sizeof(struct sgentry)); actual_fibsize64 = actual_fibsize + (user_srbcmd->sg.count & 0xff) * (sizeof(struct sgentry64) - sizeof(struct sgentry)); /* User made a mistake - should not continue */ if ((actual_fibsize != fibsize) && (actual_fibsize64 != fibsize)) { dprintk((KERN_DEBUG"aacraid: Bad Size specified in " "Raw SRB command calculated fibsize=%lu;%lu " "user_srbcmd->sg.count=%d aac_srb=%lu sgentry=%lu;%lu " "issued fibsize=%d\n", actual_fibsize, actual_fibsize64, user_srbcmd->sg.count, sizeof(struct aac_srb), sizeof(struct sgentry), sizeof(struct sgentry64), fibsize)); rcode = -EINVAL; goto cleanup; } if ((data_dir == DMA_NONE) && user_srbcmd->sg.count) { dprintk((KERN_DEBUG"aacraid: SG with no direction specified in Raw SRB command\n")); rcode = -EINVAL; goto cleanup; } byte_count = 0; if (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) { struct user_sgmap64* upsg = (struct user_sgmap64*)&user_srbcmd->sg; struct sgmap64* psg = (struct sgmap64*)&srbcmd->sg; /* * This should also catch if user used the 32 bit sgmap */ if (actual_fibsize64 == fibsize) { actual_fibsize = actual_fibsize64; for (i = 0; i < upsg->count; i++) { u64 addr; void* p; if (upsg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(upsg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", upsg->sg[i].count,i,upsg->count)); rcode = -ENOMEM; goto cleanup; } addr = (u64)upsg->sg[i].addr[0]; addr += ((u64)upsg->sg[i].addr[1]) << 32; sg_user[i] = (void __user *)(uintptr_t)addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir); psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff); psg->sg[i].addr[1] = cpu_to_le32(addr>>32); byte_count += upsg->sg[i].count; psg->sg[i].count = cpu_to_le32(upsg->sg[i].count); } } else { struct user_sgmap* usg; usg = kmalloc(actual_fibsize - sizeof(struct aac_srb) + sizeof(struct sgmap), GFP_KERNEL); if (!usg) { dprintk((KERN_DEBUG"aacraid: Allocation error in Raw SRB command\n")); rcode = -ENOMEM; goto cleanup; } memcpy (usg, upsg, actual_fibsize - sizeof(struct aac_srb) + sizeof(struct sgmap)); actual_fibsize = actual_fibsize64; for (i = 0; i < usg->count; i++) { u64 addr; void* p; if (usg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { kfree(usg); rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG "aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", usg->sg[i].count,i,usg->count)); kfree(usg); rcode = -ENOMEM; goto cleanup; } sg_user[i] = (void __user *)(uintptr_t)usg->sg[i].addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){ kfree (usg); dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir); psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff); psg->sg[i].addr[1] = cpu_to_le32(addr>>32); byte_count += usg->sg[i].count; psg->sg[i].count = cpu_to_le32(usg->sg[i].count); } kfree (usg); } srbcmd->count = cpu_to_le32(byte_count); psg->count = cpu_to_le32(sg_indx+1); status = aac_fib_send(ScsiPortCommand64, srbfib, actual_fibsize, FsaNormal, 1, 1,NULL,NULL); } else { struct user_sgmap* upsg = &user_srbcmd->sg; struct sgmap* psg = &srbcmd->sg; if (actual_fibsize64 == fibsize) { struct user_sgmap64* usg = (struct user_sgmap64 *)upsg; for (i = 0; i < upsg->count; i++) { uintptr_t addr; void* p; if (usg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", usg->sg[i].count,i,usg->count)); rcode = -ENOMEM; goto cleanup; } addr = (u64)usg->sg[i].addr[0]; addr += ((u64)usg->sg[i].addr[1]) << 32; sg_user[i] = (void __user *)addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],usg->sg[i].count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir); psg->sg[i].addr = cpu_to_le32(addr & 0xffffffff); byte_count += usg->sg[i].count; psg->sg[i].count = cpu_to_le32(usg->sg[i].count); } } else { for (i = 0; i < upsg->count; i++) { dma_addr_t addr; void* p; if (upsg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } p = kmalloc(upsg->sg[i].count, GFP_KERNEL); if (!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", upsg->sg[i].count, i, upsg->count)); rcode = -ENOMEM; goto cleanup; } sg_user[i] = (void __user *)(uintptr_t)upsg->sg[i].addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p, sg_user[i], upsg->sg[i].count)) { dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir); psg->sg[i].addr = cpu_to_le32(addr); byte_count += upsg->sg[i].count; psg->sg[i].count = cpu_to_le32(upsg->sg[i].count); } } srbcmd->count = cpu_to_le32(byte_count); psg->count = cpu_to_le32(sg_indx+1); status = aac_fib_send(ScsiPortCommand, srbfib, actual_fibsize, FsaNormal, 1, 1, NULL, NULL); } if (status == -ERESTARTSYS) { rcode = -ERESTARTSYS; goto cleanup; } if (status != 0){ dprintk((KERN_DEBUG"aacraid: Could not send raw srb fib to hba\n")); rcode = -ENXIO; goto cleanup; } if (flags & SRB_DataIn) { for(i = 0 ; i <= sg_indx; i++){ byte_count = le32_to_cpu( (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) ? ((struct sgmap64*)&srbcmd->sg)->sg[i].count : srbcmd->sg.sg[i].count); if(copy_to_user(sg_user[i], sg_list[i], byte_count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data to user\n")); rcode = -EFAULT; goto cleanup; } } } reply = (struct aac_srb_reply *) fib_data(srbfib); if(copy_to_user(user_reply,reply,sizeof(struct aac_srb_reply))){ dprintk((KERN_DEBUG"aacraid: Could not copy reply to user\n")); rcode = -EFAULT; goto cleanup; } cleanup: kfree(user_srbcmd); for(i=0; i <= sg_indx; i++){ kfree(sg_list[i]); } if (rcode != -ERESTARTSYS) { aac_fib_complete(srbfib); aac_fib_free(srbfib); } return rcode; } Commit Message: aacraid: prevent invalid pointer dereference It appears that driver runs into a problem here if fibsize is too small because we allocate user_srbcmd with fibsize size only but later we access it until user_srbcmd->sg.count to copy it over to srbcmd. It is not correct to test (fibsize < sizeof(*user_srbcmd)) because this structure already includes one sg element and this is not needed for commands without data. So, we would recommend to add the following (instead of test for fibsize == 0). Signed-off-by: Mahesh Rajashekhara <[email protected]> Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
static int aac_send_raw_srb(struct aac_dev* dev, void __user * arg) { struct fib* srbfib; int status; struct aac_srb *srbcmd = NULL; struct user_aac_srb *user_srbcmd = NULL; struct user_aac_srb __user *user_srb = arg; struct aac_srb_reply __user *user_reply; struct aac_srb_reply* reply; u32 fibsize = 0; u32 flags = 0; s32 rcode = 0; u32 data_dir; void __user *sg_user[32]; void *sg_list[32]; u32 sg_indx = 0; u32 byte_count = 0; u32 actual_fibsize64, actual_fibsize = 0; int i; if (dev->in_reset) { dprintk((KERN_DEBUG"aacraid: send raw srb -EBUSY\n")); return -EBUSY; } if (!capable(CAP_SYS_ADMIN)){ dprintk((KERN_DEBUG"aacraid: No permission to send raw srb\n")); return -EPERM; } /* * Allocate and initialize a Fib then setup a SRB command */ if (!(srbfib = aac_fib_alloc(dev))) { return -ENOMEM; } aac_fib_init(srbfib); /* raw_srb FIB is not FastResponseCapable */ srbfib->hw_fib_va->header.XferState &= ~cpu_to_le32(FastResponseCapable); srbcmd = (struct aac_srb*) fib_data(srbfib); memset(sg_list, 0, sizeof(sg_list)); /* cleanup may take issue */ if(copy_from_user(&fibsize, &user_srb->count,sizeof(u32))){ dprintk((KERN_DEBUG"aacraid: Could not copy data size from user\n")); rcode = -EFAULT; goto cleanup; } if ((fibsize < (sizeof(struct user_aac_srb) - sizeof(struct user_sgentry))) || (fibsize > (dev->max_fib_size - sizeof(struct aac_fibhdr)))) { rcode = -EINVAL; goto cleanup; } user_srbcmd = kmalloc(fibsize, GFP_KERNEL); if (!user_srbcmd) { dprintk((KERN_DEBUG"aacraid: Could not make a copy of the srb\n")); rcode = -ENOMEM; goto cleanup; } if(copy_from_user(user_srbcmd, user_srb,fibsize)){ dprintk((KERN_DEBUG"aacraid: Could not copy srb from user\n")); rcode = -EFAULT; goto cleanup; } user_reply = arg+fibsize; flags = user_srbcmd->flags; /* from user in cpu order */ srbcmd->function = cpu_to_le32(SRBF_ExecuteScsi); // Force this srbcmd->channel = cpu_to_le32(user_srbcmd->channel); srbcmd->id = cpu_to_le32(user_srbcmd->id); srbcmd->lun = cpu_to_le32(user_srbcmd->lun); srbcmd->timeout = cpu_to_le32(user_srbcmd->timeout); srbcmd->flags = cpu_to_le32(flags); srbcmd->retry_limit = 0; // Obsolete parameter srbcmd->cdb_size = cpu_to_le32(user_srbcmd->cdb_size); memcpy(srbcmd->cdb, user_srbcmd->cdb, sizeof(srbcmd->cdb)); switch (flags & (SRB_DataIn | SRB_DataOut)) { case SRB_DataOut: data_dir = DMA_TO_DEVICE; break; case (SRB_DataIn | SRB_DataOut): data_dir = DMA_BIDIRECTIONAL; break; case SRB_DataIn: data_dir = DMA_FROM_DEVICE; break; default: data_dir = DMA_NONE; } if (user_srbcmd->sg.count > ARRAY_SIZE(sg_list)) { dprintk((KERN_DEBUG"aacraid: too many sg entries %d\n", le32_to_cpu(srbcmd->sg.count))); rcode = -EINVAL; goto cleanup; } actual_fibsize = sizeof(struct aac_srb) - sizeof(struct sgentry) + ((user_srbcmd->sg.count & 0xff) * sizeof(struct sgentry)); actual_fibsize64 = actual_fibsize + (user_srbcmd->sg.count & 0xff) * (sizeof(struct sgentry64) - sizeof(struct sgentry)); /* User made a mistake - should not continue */ if ((actual_fibsize != fibsize) && (actual_fibsize64 != fibsize)) { dprintk((KERN_DEBUG"aacraid: Bad Size specified in " "Raw SRB command calculated fibsize=%lu;%lu " "user_srbcmd->sg.count=%d aac_srb=%lu sgentry=%lu;%lu " "issued fibsize=%d\n", actual_fibsize, actual_fibsize64, user_srbcmd->sg.count, sizeof(struct aac_srb), sizeof(struct sgentry), sizeof(struct sgentry64), fibsize)); rcode = -EINVAL; goto cleanup; } if ((data_dir == DMA_NONE) && user_srbcmd->sg.count) { dprintk((KERN_DEBUG"aacraid: SG with no direction specified in Raw SRB command\n")); rcode = -EINVAL; goto cleanup; } byte_count = 0; if (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) { struct user_sgmap64* upsg = (struct user_sgmap64*)&user_srbcmd->sg; struct sgmap64* psg = (struct sgmap64*)&srbcmd->sg; /* * This should also catch if user used the 32 bit sgmap */ if (actual_fibsize64 == fibsize) { actual_fibsize = actual_fibsize64; for (i = 0; i < upsg->count; i++) { u64 addr; void* p; if (upsg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(upsg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", upsg->sg[i].count,i,upsg->count)); rcode = -ENOMEM; goto cleanup; } addr = (u64)upsg->sg[i].addr[0]; addr += ((u64)upsg->sg[i].addr[1]) << 32; sg_user[i] = (void __user *)(uintptr_t)addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir); psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff); psg->sg[i].addr[1] = cpu_to_le32(addr>>32); byte_count += upsg->sg[i].count; psg->sg[i].count = cpu_to_le32(upsg->sg[i].count); } } else { struct user_sgmap* usg; usg = kmalloc(actual_fibsize - sizeof(struct aac_srb) + sizeof(struct sgmap), GFP_KERNEL); if (!usg) { dprintk((KERN_DEBUG"aacraid: Allocation error in Raw SRB command\n")); rcode = -ENOMEM; goto cleanup; } memcpy (usg, upsg, actual_fibsize - sizeof(struct aac_srb) + sizeof(struct sgmap)); actual_fibsize = actual_fibsize64; for (i = 0; i < usg->count; i++) { u64 addr; void* p; if (usg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { kfree(usg); rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG "aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", usg->sg[i].count,i,usg->count)); kfree(usg); rcode = -ENOMEM; goto cleanup; } sg_user[i] = (void __user *)(uintptr_t)usg->sg[i].addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){ kfree (usg); dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir); psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff); psg->sg[i].addr[1] = cpu_to_le32(addr>>32); byte_count += usg->sg[i].count; psg->sg[i].count = cpu_to_le32(usg->sg[i].count); } kfree (usg); } srbcmd->count = cpu_to_le32(byte_count); psg->count = cpu_to_le32(sg_indx+1); status = aac_fib_send(ScsiPortCommand64, srbfib, actual_fibsize, FsaNormal, 1, 1,NULL,NULL); } else { struct user_sgmap* upsg = &user_srbcmd->sg; struct sgmap* psg = &srbcmd->sg; if (actual_fibsize64 == fibsize) { struct user_sgmap64* usg = (struct user_sgmap64 *)upsg; for (i = 0; i < upsg->count; i++) { uintptr_t addr; void* p; if (usg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", usg->sg[i].count,i,usg->count)); rcode = -ENOMEM; goto cleanup; } addr = (u64)usg->sg[i].addr[0]; addr += ((u64)usg->sg[i].addr[1]) << 32; sg_user[i] = (void __user *)addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],usg->sg[i].count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir); psg->sg[i].addr = cpu_to_le32(addr & 0xffffffff); byte_count += usg->sg[i].count; psg->sg[i].count = cpu_to_le32(usg->sg[i].count); } } else { for (i = 0; i < upsg->count; i++) { dma_addr_t addr; void* p; if (upsg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } p = kmalloc(upsg->sg[i].count, GFP_KERNEL); if (!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", upsg->sg[i].count, i, upsg->count)); rcode = -ENOMEM; goto cleanup; } sg_user[i] = (void __user *)(uintptr_t)upsg->sg[i].addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p, sg_user[i], upsg->sg[i].count)) { dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir); psg->sg[i].addr = cpu_to_le32(addr); byte_count += upsg->sg[i].count; psg->sg[i].count = cpu_to_le32(upsg->sg[i].count); } } srbcmd->count = cpu_to_le32(byte_count); psg->count = cpu_to_le32(sg_indx+1); status = aac_fib_send(ScsiPortCommand, srbfib, actual_fibsize, FsaNormal, 1, 1, NULL, NULL); } if (status == -ERESTARTSYS) { rcode = -ERESTARTSYS; goto cleanup; } if (status != 0){ dprintk((KERN_DEBUG"aacraid: Could not send raw srb fib to hba\n")); rcode = -ENXIO; goto cleanup; } if (flags & SRB_DataIn) { for(i = 0 ; i <= sg_indx; i++){ byte_count = le32_to_cpu( (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) ? ((struct sgmap64*)&srbcmd->sg)->sg[i].count : srbcmd->sg.sg[i].count); if(copy_to_user(sg_user[i], sg_list[i], byte_count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data to user\n")); rcode = -EFAULT; goto cleanup; } } } reply = (struct aac_srb_reply *) fib_data(srbfib); if(copy_to_user(user_reply,reply,sizeof(struct aac_srb_reply))){ dprintk((KERN_DEBUG"aacraid: Could not copy reply to user\n")); rcode = -EFAULT; goto cleanup; } cleanup: kfree(user_srbcmd); for(i=0; i <= sg_indx; i++){ kfree(sg_list[i]); } if (rcode != -ERESTARTSYS) { aac_fib_complete(srbfib); aac_fib_free(srbfib); } return rcode; }
165,941
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_gb_surface_create_arg *arg = (union drm_vmw_gb_surface_create_arg *)data; struct drm_vmw_gb_surface_create_req *req = &arg->req; struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; uint32_t size; uint32_t backup_handle; if (req->multisample_count != 0) return -EINVAL; if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS) return -EINVAL; if (unlikely(vmw_user_surface_size == 0)) vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + 128; size = vmw_user_surface_size + 128; /* Define a surface based on the parameters. */ ret = vmw_surface_gb_priv_define(dev, size, req->svga3d_flags, req->format, req->drm_surface_flags & drm_vmw_surface_flag_scanout, req->mip_levels, req->multisample_count, req->array_size, req->base_size, &srf); if (unlikely(ret != 0)) return ret; user_srf = container_of(srf, struct vmw_user_surface, srf); if (drm_is_primary_client(file_priv)) user_srf->master = drm_master_get(file_priv->master); ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; res = &user_srf->srf.res; if (req->buffer_handle != SVGA3D_INVALID_ID) { ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, &res->backup, &user_srf->backup_base); if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE < res->backup_size) { DRM_ERROR("Surface backup buffer is too small.\n"); vmw_dmabuf_unreference(&res->backup); ret = -EINVAL; goto out_unlock; } } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) ret = vmw_user_dmabuf_alloc(dev_priv, tfile, res->backup_size, req->drm_surface_flags & drm_vmw_surface_flag_shareable, &backup_handle, &res->backup, &user_srf->backup_base); if (unlikely(ret != 0)) { vmw_resource_unreference(&res); goto out_unlock; } tmp = vmw_resource_reference(res); ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, req->drm_surface_flags & drm_vmw_surface_flag_shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); goto out_unlock; } rep->handle = user_srf->prime.base.hash.key; rep->backup_size = res->backup_size; if (res->backup) { rep->buffer_map_handle = drm_vma_node_offset_addr(&res->backup->base.vma_node); rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; rep->buffer_handle = backup_handle; } else { rep->buffer_map_handle = 0; rep->buffer_size = 0; rep->buffer_handle = SVGA3D_INVALID_ID; } vmw_resource_unreference(&res); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; } Commit Message: drm/vmwgfx: Make sure backup_handle is always valid When vmw_gb_surface_define_ioctl() is called with an existing buffer, we end up returning an uninitialized variable in the backup_handle. The fix is to first initialize backup_handle to 0 just to be sure, and second, when a user-provided buffer is found, we will use the req->buffer_handle as the backup_handle. Cc: <[email protected]> Reported-by: Murray McAllister <[email protected]> Signed-off-by: Sinclair Yeh <[email protected]> Reviewed-by: Deepak Rawat <[email protected]> CWE ID: CWE-200
int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_gb_surface_create_arg *arg = (union drm_vmw_gb_surface_create_arg *)data; struct drm_vmw_gb_surface_create_req *req = &arg->req; struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; uint32_t size; uint32_t backup_handle = 0; if (req->multisample_count != 0) return -EINVAL; if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS) return -EINVAL; if (unlikely(vmw_user_surface_size == 0)) vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + 128; size = vmw_user_surface_size + 128; /* Define a surface based on the parameters. */ ret = vmw_surface_gb_priv_define(dev, size, req->svga3d_flags, req->format, req->drm_surface_flags & drm_vmw_surface_flag_scanout, req->mip_levels, req->multisample_count, req->array_size, req->base_size, &srf); if (unlikely(ret != 0)) return ret; user_srf = container_of(srf, struct vmw_user_surface, srf); if (drm_is_primary_client(file_priv)) user_srf->master = drm_master_get(file_priv->master); ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; res = &user_srf->srf.res; if (req->buffer_handle != SVGA3D_INVALID_ID) { ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, &res->backup, &user_srf->backup_base); if (ret == 0) { if (res->backup->base.num_pages * PAGE_SIZE < res->backup_size) { DRM_ERROR("Surface backup buffer is too small.\n"); vmw_dmabuf_unreference(&res->backup); ret = -EINVAL; goto out_unlock; } else { backup_handle = req->buffer_handle; } } } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) ret = vmw_user_dmabuf_alloc(dev_priv, tfile, res->backup_size, req->drm_surface_flags & drm_vmw_surface_flag_shareable, &backup_handle, &res->backup, &user_srf->backup_base); if (unlikely(ret != 0)) { vmw_resource_unreference(&res); goto out_unlock; } tmp = vmw_resource_reference(res); ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, req->drm_surface_flags & drm_vmw_surface_flag_shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); goto out_unlock; } rep->handle = user_srf->prime.base.hash.key; rep->backup_size = res->backup_size; if (res->backup) { rep->buffer_map_handle = drm_vma_node_offset_addr(&res->backup->base.vma_node); rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; rep->buffer_handle = backup_handle; } else { rep->buffer_map_handle = 0; rep->buffer_size = 0; rep->buffer_handle = SVGA3D_INVALID_ID; } vmw_resource_unreference(&res); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; }
168,093
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int generic_permission(struct inode *inode, int mask) { int ret; /* * Do the basic permission checks. */ ret = acl_permission_check(inode, mask); if (ret != -EACCES) return ret; if (S_ISDIR(inode->i_mode)) { /* DACs are overridable for directories */ if (inode_capable(inode, CAP_DAC_OVERRIDE)) return 0; if (!(mask & MAY_WRITE)) if (inode_capable(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } /* * Read/write DACs are always overridable. * Executable DACs are overridable when there is * at least one exec bit set. */ if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO)) if (inode_capable(inode, CAP_DAC_OVERRIDE)) return 0; /* * Searching includes executable on directories, else just read. */ mask &= MAY_READ | MAY_WRITE | MAY_EXEC; if (mask == MAY_READ) if (inode_capable(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid The kernel has no concept of capabilities with respect to inodes; inodes exist independently of namespaces. For example, inode_capable(inode, CAP_LINUX_IMMUTABLE) would be nonsense. This patch changes inode_capable to check for uid and gid mappings and renames it to capable_wrt_inode_uidgid, which should make it more obvious what it does. Fixes CVE-2014-4014. Cc: Theodore Ts'o <[email protected]> Cc: Serge Hallyn <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: Dave Chinner <[email protected]> Cc: [email protected] Signed-off-by: Andy Lutomirski <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
int generic_permission(struct inode *inode, int mask) { int ret; /* * Do the basic permission checks. */ ret = acl_permission_check(inode, mask); if (ret != -EACCES) return ret; if (S_ISDIR(inode->i_mode)) { /* DACs are overridable for directories */ if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; if (!(mask & MAY_WRITE)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } /* * Read/write DACs are always overridable. * Executable DACs are overridable when there is * at least one exec bit set. */ if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; /* * Searching includes executable on directories, else just read. */ mask &= MAY_READ | MAY_WRITE | MAY_EXEC; if (mask == MAY_READ) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; }
166,321
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); directory=exif+offset; level=0; entry=0; do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format-1) >= EXIF_NUM_FORMATS) break; components=(ssize_t) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((size_t) (offset+number_bytes) > length) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/280 CWE ID: CWE-125
MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); directory=exif+offset; level=0; entry=0; do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS)) break; components=(ssize_t) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((size_t) (offset+number_bytes) > length) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); return(MagickTrue); }
168,777
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t ucma_process_join(struct ucma_file *file, struct rdma_ucm_join_mcast *cmd, int out_len) { struct rdma_ucm_create_id_resp resp; struct ucma_context *ctx; struct ucma_multicast *mc; struct sockaddr *addr; int ret; u8 join_state; if (out_len < sizeof(resp)) return -ENOSPC; addr = (struct sockaddr *) &cmd->addr; if (cmd->addr_size != rdma_addr_size(addr)) return -EINVAL; if (cmd->join_flags == RDMA_MC_JOIN_FLAG_FULLMEMBER) join_state = BIT(FULLMEMBER_JOIN); else if (cmd->join_flags == RDMA_MC_JOIN_FLAG_SENDONLY_FULLMEMBER) join_state = BIT(SENDONLY_FULLMEMBER_JOIN); else return -EINVAL; ctx = ucma_get_ctx_dev(file, cmd->id); if (IS_ERR(ctx)) return PTR_ERR(ctx); mutex_lock(&file->mut); mc = ucma_alloc_multicast(ctx); if (!mc) { ret = -ENOMEM; goto err1; } mc->join_state = join_state; mc->uid = cmd->uid; memcpy(&mc->addr, addr, cmd->addr_size); ret = rdma_join_multicast(ctx->cm_id, (struct sockaddr *)&mc->addr, join_state, mc); if (ret) goto err2; resp.id = mc->id; if (copy_to_user(u64_to_user_ptr(cmd->response), &resp, sizeof(resp))) { ret = -EFAULT; goto err3; } mutex_unlock(&file->mut); ucma_put_ctx(ctx); return 0; err3: rdma_leave_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr); ucma_cleanup_mc_events(mc); err2: mutex_lock(&mut); idr_remove(&multicast_idr, mc->id); mutex_unlock(&mut); list_del(&mc->list); kfree(mc); err1: mutex_unlock(&file->mut); ucma_put_ctx(ctx); return ret; } Commit Message: infiniband: fix a possible use-after-free bug ucma_process_join() will free the new allocated "mc" struct, if there is any error after that, especially the copy_to_user(). But in parallel, ucma_leave_multicast() could find this "mc" through idr_find() before ucma_process_join() frees it, since it is already published. So "mc" could be used in ucma_leave_multicast() after it is been allocated and freed in ucma_process_join(), since we don't refcnt it. Fix this by separating "publish" from ID allocation, so that we can get an ID first and publish it later after copy_to_user(). Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support") Reported-by: Noam Rathaus <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> CWE ID: CWE-416
static ssize_t ucma_process_join(struct ucma_file *file, struct rdma_ucm_join_mcast *cmd, int out_len) { struct rdma_ucm_create_id_resp resp; struct ucma_context *ctx; struct ucma_multicast *mc; struct sockaddr *addr; int ret; u8 join_state; if (out_len < sizeof(resp)) return -ENOSPC; addr = (struct sockaddr *) &cmd->addr; if (cmd->addr_size != rdma_addr_size(addr)) return -EINVAL; if (cmd->join_flags == RDMA_MC_JOIN_FLAG_FULLMEMBER) join_state = BIT(FULLMEMBER_JOIN); else if (cmd->join_flags == RDMA_MC_JOIN_FLAG_SENDONLY_FULLMEMBER) join_state = BIT(SENDONLY_FULLMEMBER_JOIN); else return -EINVAL; ctx = ucma_get_ctx_dev(file, cmd->id); if (IS_ERR(ctx)) return PTR_ERR(ctx); mutex_lock(&file->mut); mc = ucma_alloc_multicast(ctx); if (!mc) { ret = -ENOMEM; goto err1; } mc->join_state = join_state; mc->uid = cmd->uid; memcpy(&mc->addr, addr, cmd->addr_size); ret = rdma_join_multicast(ctx->cm_id, (struct sockaddr *)&mc->addr, join_state, mc); if (ret) goto err2; resp.id = mc->id; if (copy_to_user(u64_to_user_ptr(cmd->response), &resp, sizeof(resp))) { ret = -EFAULT; goto err3; } mutex_lock(&mut); idr_replace(&multicast_idr, mc, mc->id); mutex_unlock(&mut); mutex_unlock(&file->mut); ucma_put_ctx(ctx); return 0; err3: rdma_leave_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr); ucma_cleanup_mc_events(mc); err2: mutex_lock(&mut); idr_remove(&multicast_idr, mc->id); mutex_unlock(&mut); list_del(&mc->list); kfree(mc); err1: mutex_unlock(&file->mut); ucma_put_ctx(ctx); return ret; }
169,110
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct svc_rdma_req_map *svc_rdma_get_req_map(struct svcxprt_rdma *xprt) { struct svc_rdma_req_map *map = NULL; spin_lock(&xprt->sc_map_lock); if (list_empty(&xprt->sc_maps)) goto out_empty; map = list_first_entry(&xprt->sc_maps, struct svc_rdma_req_map, free); list_del_init(&map->free); spin_unlock(&xprt->sc_map_lock); out: map->count = 0; return map; out_empty: spin_unlock(&xprt->sc_map_lock); /* Pre-allocation amount was incorrect */ map = alloc_req_map(GFP_NOIO); if (map) goto out; WARN_ONCE(1, "svcrdma: empty request map list?\n"); return NULL; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
struct svc_rdma_req_map *svc_rdma_get_req_map(struct svcxprt_rdma *xprt)
168,181
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(old_dir)->root; struct btrfs_root *dest = BTRFS_I(new_dir)->root; struct inode *new_inode = new_dentry->d_inode; struct inode *old_inode = old_dentry->d_inode; struct timespec ctime = CURRENT_TIME; u64 index = 0; u64 root_objectid; int ret; u64 old_ino = btrfs_ino(old_inode); if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return -EPERM; /* we only allow rename subvolume link between subvolumes */ if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest) return -EXDEV; if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID || (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID)) return -ENOTEMPTY; if (S_ISDIR(old_inode->i_mode) && new_inode && new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; /* * we're using rename to replace one file with another. * and the replacement file is large. Start IO on it now so * we don't add too much work to the end of the transaction */ if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size && old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT) filemap_flush(old_inode->i_mapping); /* close the racy window with snapshot create/destroy ioctl */ if (old_ino == BTRFS_FIRST_FREE_OBJECTID) down_read(&root->fs_info->subvol_sem); /* * We want to reserve the absolute worst case amount of items. So if * both inodes are subvols and we need to unlink them then that would * require 4 item modifications, but if they are both normal inodes it * would require 5 item modifications, so we'll assume their normal * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items * should cover the worst case number of items we'll modify. */ trans = btrfs_start_transaction(root, 20); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_notrans; } if (dest != root) btrfs_record_root_in_trans(trans, dest); ret = btrfs_set_inode_index(new_dir, &index); if (ret) goto out_fail; if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { /* force full log commit if subvolume involved. */ root->fs_info->last_trans_log_full_commit = trans->transid; } else { ret = btrfs_insert_inode_ref(trans, dest, new_dentry->d_name.name, new_dentry->d_name.len, old_ino, btrfs_ino(new_dir), index); if (ret) goto out_fail; /* * this is an ugly little race, but the rename is required * to make sure that if we crash, the inode is either at the * old name or the new one. pinning the log transaction lets * us make sure we don't allow a log commit to come in after * we unlink the name but before we add the new name back in. */ btrfs_pin_log_trans(root); } /* * make sure the inode gets flushed if it is replacing * something. */ if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode)) btrfs_add_ordered_operation(trans, root, old_inode); inode_inc_iversion(old_dir); inode_inc_iversion(new_dir); inode_inc_iversion(old_inode); old_dir->i_ctime = old_dir->i_mtime = ctime; new_dir->i_ctime = new_dir->i_mtime = ctime; old_inode->i_ctime = ctime; if (old_dentry->d_parent != new_dentry->d_parent) btrfs_record_unlink_dir(trans, old_dir, old_inode, 1); if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { root_objectid = BTRFS_I(old_inode)->root->root_key.objectid; ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid, old_dentry->d_name.name, old_dentry->d_name.len); } else { ret = __btrfs_unlink_inode(trans, root, old_dir, old_dentry->d_inode, old_dentry->d_name.name, old_dentry->d_name.len); if (!ret) ret = btrfs_update_inode(trans, root, old_inode); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (new_inode) { inode_inc_iversion(new_inode); new_inode->i_ctime = CURRENT_TIME; if (unlikely(btrfs_ino(new_inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { root_objectid = BTRFS_I(new_inode)->location.objectid; ret = btrfs_unlink_subvol(trans, dest, new_dir, root_objectid, new_dentry->d_name.name, new_dentry->d_name.len); BUG_ON(new_inode->i_nlink == 0); } else { ret = btrfs_unlink_inode(trans, dest, new_dir, new_dentry->d_inode, new_dentry->d_name.name, new_dentry->d_name.len); } if (!ret && new_inode->i_nlink == 0) { ret = btrfs_orphan_add(trans, new_dentry->d_inode); BUG_ON(ret); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } } fixup_inode_flags(new_dir, old_inode); ret = btrfs_add_link(trans, new_dir, old_inode, new_dentry->d_name.name, new_dentry->d_name.len, 0, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (old_ino != BTRFS_FIRST_FREE_OBJECTID) { struct dentry *parent = new_dentry->d_parent; btrfs_log_new_name(trans, old_inode, old_dir, parent); btrfs_end_log_trans(root); } out_fail: btrfs_end_transaction(trans, root); out_notrans: if (old_ino == BTRFS_FIRST_FREE_OBJECTID) up_read(&root->fs_info->subvol_sem); return ret; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310
static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(old_dir)->root; struct btrfs_root *dest = BTRFS_I(new_dir)->root; struct inode *new_inode = new_dentry->d_inode; struct inode *old_inode = old_dentry->d_inode; struct timespec ctime = CURRENT_TIME; u64 index = 0; u64 root_objectid; int ret; u64 old_ino = btrfs_ino(old_inode); if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return -EPERM; /* we only allow rename subvolume link between subvolumes */ if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest) return -EXDEV; if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID || (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID)) return -ENOTEMPTY; if (S_ISDIR(old_inode->i_mode) && new_inode && new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; /* check for collisions, even if the name isn't there */ ret = btrfs_check_dir_item_collision(root, new_dir->i_ino, new_dentry->d_name.name, new_dentry->d_name.len); if (ret) { if (ret == -EEXIST) { /* we shouldn't get * eexist without a new_inode */ if (!new_inode) { WARN_ON(1); return ret; } } else { /* maybe -EOVERFLOW */ return ret; } } ret = 0; /* * we're using rename to replace one file with another. * and the replacement file is large. Start IO on it now so * we don't add too much work to the end of the transaction */ if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size && old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT) filemap_flush(old_inode->i_mapping); /* close the racy window with snapshot create/destroy ioctl */ if (old_ino == BTRFS_FIRST_FREE_OBJECTID) down_read(&root->fs_info->subvol_sem); /* * We want to reserve the absolute worst case amount of items. So if * both inodes are subvols and we need to unlink them then that would * require 4 item modifications, but if they are both normal inodes it * would require 5 item modifications, so we'll assume their normal * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items * should cover the worst case number of items we'll modify. */ trans = btrfs_start_transaction(root, 20); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_notrans; } if (dest != root) btrfs_record_root_in_trans(trans, dest); ret = btrfs_set_inode_index(new_dir, &index); if (ret) goto out_fail; if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { /* force full log commit if subvolume involved. */ root->fs_info->last_trans_log_full_commit = trans->transid; } else { ret = btrfs_insert_inode_ref(trans, dest, new_dentry->d_name.name, new_dentry->d_name.len, old_ino, btrfs_ino(new_dir), index); if (ret) goto out_fail; /* * this is an ugly little race, but the rename is required * to make sure that if we crash, the inode is either at the * old name or the new one. pinning the log transaction lets * us make sure we don't allow a log commit to come in after * we unlink the name but before we add the new name back in. */ btrfs_pin_log_trans(root); } /* * make sure the inode gets flushed if it is replacing * something. */ if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode)) btrfs_add_ordered_operation(trans, root, old_inode); inode_inc_iversion(old_dir); inode_inc_iversion(new_dir); inode_inc_iversion(old_inode); old_dir->i_ctime = old_dir->i_mtime = ctime; new_dir->i_ctime = new_dir->i_mtime = ctime; old_inode->i_ctime = ctime; if (old_dentry->d_parent != new_dentry->d_parent) btrfs_record_unlink_dir(trans, old_dir, old_inode, 1); if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { root_objectid = BTRFS_I(old_inode)->root->root_key.objectid; ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid, old_dentry->d_name.name, old_dentry->d_name.len); } else { ret = __btrfs_unlink_inode(trans, root, old_dir, old_dentry->d_inode, old_dentry->d_name.name, old_dentry->d_name.len); if (!ret) ret = btrfs_update_inode(trans, root, old_inode); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (new_inode) { inode_inc_iversion(new_inode); new_inode->i_ctime = CURRENT_TIME; if (unlikely(btrfs_ino(new_inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { root_objectid = BTRFS_I(new_inode)->location.objectid; ret = btrfs_unlink_subvol(trans, dest, new_dir, root_objectid, new_dentry->d_name.name, new_dentry->d_name.len); BUG_ON(new_inode->i_nlink == 0); } else { ret = btrfs_unlink_inode(trans, dest, new_dir, new_dentry->d_inode, new_dentry->d_name.name, new_dentry->d_name.len); } if (!ret && new_inode->i_nlink == 0) { ret = btrfs_orphan_add(trans, new_dentry->d_inode); BUG_ON(ret); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } } fixup_inode_flags(new_dir, old_inode); ret = btrfs_add_link(trans, new_dir, old_inode, new_dentry->d_name.name, new_dentry->d_name.len, 0, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (old_ino != BTRFS_FIRST_FREE_OBJECTID) { struct dentry *parent = new_dentry->d_parent; btrfs_log_new_name(trans, old_inode, old_dir, parent); btrfs_end_log_trans(root); } out_fail: btrfs_end_transaction(trans, root); out_notrans: if (old_ino == BTRFS_FIRST_FREE_OBJECTID) up_read(&root->fs_info->subvol_sem); return ret; }
166,194
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void color_cmyk_to_rgb(opj_image_t *image) { float C, M, Y, K; float sC, sM, sY, sK; unsigned int w, h, max, i; w = image->comps[0].w; h = image->comps[0].h; if(image->numcomps < 4) return; max = w * h; sC = 1.0F / (float)((1 << image->comps[0].prec) - 1); sM = 1.0F / (float)((1 << image->comps[1].prec) - 1); sY = 1.0F / (float)((1 << image->comps[2].prec) - 1); sK = 1.0F / (float)((1 << image->comps[3].prec) - 1); for(i = 0; i < max; ++i) { /* CMYK values from 0 to 1 */ C = (float)(image->comps[0].data[i]) * sC; M = (float)(image->comps[1].data[i]) * sM; Y = (float)(image->comps[2].data[i]) * sY; K = (float)(image->comps[3].data[i]) * sK; /* Invert all CMYK values */ C = 1.0F - C; M = 1.0F - M; Y = 1.0F - Y; K = 1.0F - K; /* CMYK -> RGB : RGB results from 0 to 255 */ image->comps[0].data[i] = (int)(255.0F * C * K); /* R */ image->comps[1].data[i] = (int)(255.0F * M * K); /* G */ image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */ } free(image->comps[3].data); image->comps[3].data = NULL; image->comps[0].prec = 8; image->comps[1].prec = 8; image->comps[2].prec = 8; image->numcomps -= 1; image->color_space = OPJ_CLRSPC_SRGB; for (i = 3; i < image->numcomps; ++i) { memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i])); } }/* color_cmyk_to_rgb() */ Commit Message: Fix Heap Buffer Overflow in function color_cmyk_to_rgb Fix uclouvain/openjpeg#774 CWE ID: CWE-119
void color_cmyk_to_rgb(opj_image_t *image) { float C, M, Y, K; float sC, sM, sY, sK; unsigned int w, h, max, i; w = image->comps[0].w; h = image->comps[0].h; if ( (image->numcomps < 4) || (image->comps[0].dx != image->comps[1].dx) || (image->comps[0].dx != image->comps[2].dx) || (image->comps[0].dx != image->comps[3].dx) || (image->comps[0].dy != image->comps[1].dy) || (image->comps[0].dy != image->comps[2].dy) || (image->comps[0].dy != image->comps[3].dy) ) { fprintf(stderr,"%s:%d:color_cmyk_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } max = w * h; sC = 1.0F / (float)((1 << image->comps[0].prec) - 1); sM = 1.0F / (float)((1 << image->comps[1].prec) - 1); sY = 1.0F / (float)((1 << image->comps[2].prec) - 1); sK = 1.0F / (float)((1 << image->comps[3].prec) - 1); for(i = 0; i < max; ++i) { /* CMYK values from 0 to 1 */ C = (float)(image->comps[0].data[i]) * sC; M = (float)(image->comps[1].data[i]) * sM; Y = (float)(image->comps[2].data[i]) * sY; K = (float)(image->comps[3].data[i]) * sK; /* Invert all CMYK values */ C = 1.0F - C; M = 1.0F - M; Y = 1.0F - Y; K = 1.0F - K; /* CMYK -> RGB : RGB results from 0 to 255 */ image->comps[0].data[i] = (int)(255.0F * C * K); /* R */ image->comps[1].data[i] = (int)(255.0F * M * K); /* G */ image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */ } free(image->comps[3].data); image->comps[3].data = NULL; image->comps[0].prec = 8; image->comps[1].prec = 8; image->comps[2].prec = 8; image->numcomps -= 1; image->color_space = OPJ_CLRSPC_SRGB; for (i = 3; i < image->numcomps; ++i) { memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i])); } }/* color_cmyk_to_rgb() */
168,836
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); url_util::AddStandardScheme(kPrivilegedScheme); url_util::AddStandardScheme(chrome::kChromeUIScheme); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual void SetUp() { old_client_ = content::GetContentClient(); content::SetContentClient(&client_); old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); url_util::AddStandardScheme(kPrivilegedScheme); url_util::AddStandardScheme(chrome::kChromeUIScheme); }
171,010
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHPAPI void php_pcre_match_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *return_value, zval *subpats, int global, int use_flags, long flags, long start_offset TSRMLS_DC) { zval *result_set, /* Holds a set of subpatterns after a global match */ **match_sets = NULL; /* An array of sets of matches for each subpattern after a global match */ pcre_extra *extra = pce->extra;/* Holds results of studying */ pcre_extra extra_data; /* Used locally for exec options */ int exoptions = 0; /* Execution options */ int count = 0; /* Count of matched subpatterns */ int *offsets; /* Array of subpattern offsets */ int num_subpats; /* Number of captured subpatterns */ int size_offsets; /* Size of the offsets array */ int matched; /* Has anything matched */ int g_notempty = 0; /* If the match should not be empty */ const char **stringlist; /* Holds list of subpatterns */ char **subpat_names; /* Array for named subpatterns */ int i, rc; int subpats_order; /* Order of subpattern matches */ int offset_capture; /* Capture match offsets: yes/no */ /* Overwrite the passed-in value for subpatterns with an empty array. */ if (subpats != NULL) { zval_dtor(subpats); array_init(subpats); } subpats_order = global ? PREG_PATTERN_ORDER : 0; if (use_flags) { offset_capture = flags & PREG_OFFSET_CAPTURE; /* * subpats_order is pre-set to pattern mode so we change it only if * necessary. */ if (flags & 0xff) { subpats_order = flags & 0xff; } if ((global && (subpats_order < PREG_PATTERN_ORDER || subpats_order > PREG_SET_ORDER)) || (!global && subpats_order != 0)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid flags specified"); return; } } else { offset_capture = 0; } /* Negative offset counts from the end of the string. */ if (start_offset < 0) { start_offset = subject_len + start_offset; if (start_offset < 0) { start_offset = 0; } } if (extra == NULL) { extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION; extra = &extra_data; } extra->match_limit = PCRE_G(backtrack_limit); extra->match_limit_recursion = PCRE_G(recursion_limit); /* Calculate the size of the offsets array, and allocate memory for it. */ rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &num_subpats); if (rc < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc); RETURN_FALSE; } num_subpats++; size_offsets = num_subpats * 3; /* * Build a mapping from subpattern numbers to their names. We will always * allocate the table, even though there may be no named subpatterns. This * avoids somewhat more complicated logic in the inner loops. */ subpat_names = make_subpats_table(num_subpats, pce TSRMLS_CC); if (!subpat_names) { RETURN_FALSE; } offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0); /* Allocate match sets array and initialize the values. */ if (global && subpats && subpats_order == PREG_PATTERN_ORDER) { match_sets = (zval **)safe_emalloc(num_subpats, sizeof(zval *), 0); for (i=0; i<num_subpats; i++) { ALLOC_ZVAL(match_sets[i]); array_init(match_sets[i]); INIT_PZVAL(match_sets[i]); } } matched = 0; PCRE_G(error_code) = PHP_PCRE_NO_ERROR; do { /* Execute the regular expression. */ count = pcre_exec(pce->re, extra, subject, subject_len, start_offset, exoptions|g_notempty, offsets, size_offsets); /* the string was already proved to be valid UTF-8 */ exoptions |= PCRE_NO_UTF8_CHECK; /* Check for too many substrings condition. */ if (count == 0) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Matched, but too many substrings"); count = size_offsets/3; } /* If something has matched */ if (count > 0) { matched++; /* If subpatterns array has been passed, fill it in with values. */ if (subpats != NULL) { /* Try to get the list of substrings and display a warning if failed. */ if (pcre_get_substring_list(subject, offsets, count, &stringlist) < 0) { efree(subpat_names); efree(offsets); if (match_sets) efree(match_sets); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Get subpatterns list failed"); RETURN_FALSE; } if (global) { /* global pattern matching */ if (subpats && subpats_order == PREG_PATTERN_ORDER) { /* For each subpattern, insert it into the appropriate array. */ for (i = 0; i < count; i++) { if (offset_capture) { add_offset_pair(match_sets[i], (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], NULL); } else { add_next_index_stringl(match_sets[i], (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } } /* * If the number of captured subpatterns on this run is * less than the total possible number, pad the result * arrays with empty strings. */ if (count < num_subpats) { for (; i < num_subpats; i++) { add_next_index_string(match_sets[i], "", 1); } } } else { /* Allocate the result set array */ ALLOC_ZVAL(result_set); array_init(result_set); INIT_PZVAL(result_set); /* Add all the subpatterns to it */ for (i = 0; i < count; i++) { if (offset_capture) { add_offset_pair(result_set, (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], subpat_names[i]); } else { if (subpat_names[i]) { add_assoc_stringl(result_set, subpat_names[i], (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } add_next_index_stringl(result_set, (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } } /* And add it to the output array */ zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &result_set, sizeof(zval *), NULL); } } else { /* single pattern matching */ /* For each subpattern, insert it into the subpatterns array. */ for (i = 0; i < count; i++) { if (offset_capture) { add_offset_pair(subpats, (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], subpat_names[i]); } else { if (subpat_names[i]) { add_assoc_stringl(subpats, subpat_names[i], (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } add_next_index_stringl(subpats, (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } } } pcre_free((void *) stringlist); } } else if (count == PCRE_ERROR_NOMATCH) { /* If we previously set PCRE_NOTEMPTY after a null match, this is not necessarily the end. We need to advance the start offset, and continue. Fudge the offset values to achieve this, unless we're already at the end of the string. */ if (g_notempty != 0 && start_offset < subject_len) { offsets[0] = start_offset; offsets[1] = start_offset + 1; } else break; } else { pcre_handle_exec_error(count TSRMLS_CC); break; } /* If we have matched an empty string, mimic what Perl's /g options does. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and try the match again at the same point. If this fails (picked up above) we advance to the next character. */ g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY | PCRE_ANCHORED : 0; /* Advance to the position right after the last full match */ start_offset = offsets[1]; } while (global); /* Add the match sets to the output array and clean up */ if (global && subpats && subpats_order == PREG_PATTERN_ORDER) { for (i = 0; i < num_subpats; i++) { if (subpat_names[i]) { zend_hash_update(Z_ARRVAL_P(subpats), subpat_names[i], strlen(subpat_names[i])+1, &match_sets[i], sizeof(zval *), NULL); Z_ADDREF_P(match_sets[i]); } zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i], sizeof(zval *), NULL); } efree(match_sets); } efree(offsets); efree(subpat_names); /* Did we encounter an error? */ if (PCRE_G(error_code) == PHP_PCRE_NO_ERROR) { RETVAL_LONG(matched); } else { RETVAL_FALSE; } } Commit Message: CWE ID: CWE-119
PHPAPI void php_pcre_match_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *return_value, zval *subpats, int global, int use_flags, long flags, long start_offset TSRMLS_DC) { zval *result_set, /* Holds a set of subpatterns after a global match */ **match_sets = NULL; /* An array of sets of matches for each subpattern after a global match */ pcre_extra *extra = pce->extra;/* Holds results of studying */ pcre_extra extra_data; /* Used locally for exec options */ int exoptions = 0; /* Execution options */ int count = 0; /* Count of matched subpatterns */ int *offsets; /* Array of subpattern offsets */ int num_subpats; /* Number of captured subpatterns */ int size_offsets; /* Size of the offsets array */ int matched; /* Has anything matched */ int g_notempty = 0; /* If the match should not be empty */ const char **stringlist; /* Holds list of subpatterns */ char **subpat_names; /* Array for named subpatterns */ int i, rc; int subpats_order; /* Order of subpattern matches */ int offset_capture; /* Capture match offsets: yes/no */ /* Overwrite the passed-in value for subpatterns with an empty array. */ if (subpats != NULL) { zval_dtor(subpats); array_init(subpats); } subpats_order = global ? PREG_PATTERN_ORDER : 0; if (use_flags) { offset_capture = flags & PREG_OFFSET_CAPTURE; /* * subpats_order is pre-set to pattern mode so we change it only if * necessary. */ if (flags & 0xff) { subpats_order = flags & 0xff; } if ((global && (subpats_order < PREG_PATTERN_ORDER || subpats_order > PREG_SET_ORDER)) || (!global && subpats_order != 0)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid flags specified"); return; } } else { offset_capture = 0; } /* Negative offset counts from the end of the string. */ if (start_offset < 0) { start_offset = subject_len + start_offset; if (start_offset < 0) { start_offset = 0; } } if (extra == NULL) { extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION; extra = &extra_data; } extra->match_limit = PCRE_G(backtrack_limit); extra->match_limit_recursion = PCRE_G(recursion_limit); /* Calculate the size of the offsets array, and allocate memory for it. */ rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &num_subpats); if (rc < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc); RETURN_FALSE; } num_subpats++; size_offsets = num_subpats * 3; /* * Build a mapping from subpattern numbers to their names. We will always * allocate the table, even though there may be no named subpatterns. This * avoids somewhat more complicated logic in the inner loops. */ subpat_names = make_subpats_table(num_subpats, pce TSRMLS_CC); if (!subpat_names) { RETURN_FALSE; } offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0); memset(offsets, 0, size_offsets*sizeof(int)); /* Allocate match sets array and initialize the values. */ if (global && subpats && subpats_order == PREG_PATTERN_ORDER) { match_sets = (zval **)safe_emalloc(num_subpats, sizeof(zval *), 0); for (i=0; i<num_subpats; i++) { ALLOC_ZVAL(match_sets[i]); array_init(match_sets[i]); INIT_PZVAL(match_sets[i]); } } matched = 0; PCRE_G(error_code) = PHP_PCRE_NO_ERROR; do { /* Execute the regular expression. */ count = pcre_exec(pce->re, extra, subject, subject_len, start_offset, exoptions|g_notempty, offsets, size_offsets); /* the string was already proved to be valid UTF-8 */ exoptions |= PCRE_NO_UTF8_CHECK; /* Check for too many substrings condition. */ if (count == 0) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Matched, but too many substrings"); count = size_offsets/3; } /* If something has matched */ if (count > 0) { matched++; /* If subpatterns array has been passed, fill it in with values. */ if (subpats != NULL) { /* Try to get the list of substrings and display a warning if failed. */ if (pcre_get_substring_list(subject, offsets, count, &stringlist) < 0) { efree(subpat_names); efree(offsets); if (match_sets) efree(match_sets); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Get subpatterns list failed"); RETURN_FALSE; } if (global) { /* global pattern matching */ if (subpats && subpats_order == PREG_PATTERN_ORDER) { /* For each subpattern, insert it into the appropriate array. */ for (i = 0; i < count; i++) { if (offset_capture) { add_offset_pair(match_sets[i], (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], NULL); } else { add_next_index_stringl(match_sets[i], (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } } /* * If the number of captured subpatterns on this run is * less than the total possible number, pad the result * arrays with empty strings. */ if (count < num_subpats) { for (; i < num_subpats; i++) { add_next_index_string(match_sets[i], "", 1); } } } else { /* Allocate the result set array */ ALLOC_ZVAL(result_set); array_init(result_set); INIT_PZVAL(result_set); /* Add all the subpatterns to it */ for (i = 0; i < count; i++) { if (offset_capture) { add_offset_pair(result_set, (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], subpat_names[i]); } else { if (subpat_names[i]) { add_assoc_stringl(result_set, subpat_names[i], (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } add_next_index_stringl(result_set, (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } } /* And add it to the output array */ zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &result_set, sizeof(zval *), NULL); } } else { /* single pattern matching */ /* For each subpattern, insert it into the subpatterns array. */ for (i = 0; i < count; i++) { if (offset_capture) { add_offset_pair(subpats, (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], subpat_names[i]); } else { if (subpat_names[i]) { add_assoc_stringl(subpats, subpat_names[i], (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } add_next_index_stringl(subpats, (char *)stringlist[i], offsets[(i<<1)+1] - offsets[i<<1], 1); } } } pcre_free((void *) stringlist); } } else if (count == PCRE_ERROR_NOMATCH) { /* If we previously set PCRE_NOTEMPTY after a null match, this is not necessarily the end. We need to advance the start offset, and continue. Fudge the offset values to achieve this, unless we're already at the end of the string. */ if (g_notempty != 0 && start_offset < subject_len) { offsets[0] = start_offset; offsets[1] = start_offset + 1; } else break; } else { pcre_handle_exec_error(count TSRMLS_CC); break; } /* If we have matched an empty string, mimic what Perl's /g options does. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and try the match again at the same point. If this fails (picked up above) we advance to the next character. */ g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY | PCRE_ANCHORED : 0; /* Advance to the position right after the last full match */ start_offset = offsets[1]; } while (global); /* Add the match sets to the output array and clean up */ if (global && subpats && subpats_order == PREG_PATTERN_ORDER) { for (i = 0; i < num_subpats; i++) { if (subpat_names[i]) { zend_hash_update(Z_ARRVAL_P(subpats), subpat_names[i], strlen(subpat_names[i])+1, &match_sets[i], sizeof(zval *), NULL); Z_ADDREF_P(match_sets[i]); } zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i], sizeof(zval *), NULL); } efree(match_sets); } efree(offsets); efree(subpat_names); /* Did we encounter an error? */ if (PCRE_G(error_code) == PHP_PCRE_NO_ERROR) { RETVAL_LONG(matched); } else { RETVAL_FALSE; } }
164,565
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr) { mainprog_info *mainprog_ptr; int color_type, bit_depth; png_uint_32 width, height; #ifdef PNG_FLOATING_POINT_SUPPORTED double gamma; #else png_fixed_point gamma; #endif /* setjmp() doesn't make sense here, because we'd either have to exit(), * longjmp() ourselves, or return control to libpng, which doesn't want * to see us again. By not doing anything here, libpng will instead jump * to readpng2_decode_data(), which can return an error value to the main * program. */ /* retrieve the pointer to our special-purpose struct, using the png_ptr * that libpng passed back to us (i.e., not a global this time--there's * no real difference for a single image, but for a multithreaded browser * decoding several PNG images at the same time, one needs to avoid mixing * up different images' structs) */ mainprog_ptr = png_get_progressive_ptr(png_ptr); if (mainprog_ptr == NULL) { /* we be hosed */ fprintf(stderr, "readpng2 error: main struct not recoverable in info_callback.\n"); fflush(stderr); return; /* * Alternatively, we could call our error-handler just like libpng * does, which would effectively terminate the program. Since this * can only happen if png_ptr gets redirected somewhere odd or the * main PNG struct gets wiped, we're probably toast anyway. (If * png_ptr itself is NULL, we would not have been called.) */ } /* this is just like in the non-progressive case */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); mainprog_ptr->width = (ulg)width; mainprog_ptr->height = (ulg)height; /* since we know we've read all of the PNG file's "header" (i.e., up * to IDAT), we can check for a background color here */ if (mainprog_ptr->need_bgcolor && png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD)) { png_color_16p pBackground; /* it is not obvious from the libpng documentation, but this function * takes a pointer to a pointer, and it always returns valid red, * green and blue values, regardless of color_type: */ png_get_bKGD(png_ptr, info_ptr, &pBackground); /* however, it always returns the raw bKGD data, regardless of any * bit-depth transformations, so check depth and adjust if necessary */ if (bit_depth == 16) { mainprog_ptr->bg_red = pBackground->red >> 8; mainprog_ptr->bg_green = pBackground->green >> 8; mainprog_ptr->bg_blue = pBackground->blue >> 8; } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { if (bit_depth == 1) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = pBackground->gray? 255 : 0; else if (bit_depth == 2) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/3) * pBackground->gray; else /* bit_depth == 4 */ mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/15) * pBackground->gray; } else { mainprog_ptr->bg_red = (uch)pBackground->red; mainprog_ptr->bg_green = (uch)pBackground->green; mainprog_ptr->bg_blue = (uch)pBackground->blue; } } /* as before, let libpng expand palette images to RGB, low-bit-depth * grayscale images to 8 bits, transparency chunks to full alpha channel; * strip 16-bit-per-sample images to 8 bits per sample; and convert * grayscale to RGB[A] */ if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); #ifdef PNG_READ_16_TO_8_SUPPORTED if (bit_depth == 16) # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED png_set_scale_16(png_ptr); # else png_set_strip_16(png_ptr); # endif #endif if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); /* Unlike the basic viewer, which was designed to operate on local files, * this program is intended to simulate a web browser--even though we * actually read from a local file, too. But because we are pretending * that most of the images originate on the Internet, we follow the recom- * mendation of the sRGB proposal and treat unlabelled images (no gAMA * chunk) as existing in the sRGB color space. That is, we assume that * such images have a file gamma of 0.45455, which corresponds to a PC-like * display system. This change in assumptions will have no effect on a * PC-like system, but on a Mac, SGI, NeXT or other system with a non- * identity lookup table, it will darken unlabelled images, which effec- * tively favors images from PC-like systems over those originating on * the local platform. Note that mainprog_ptr->display_exponent is the * "gamma" value for the entire display system, i.e., the product of * LUT_exponent and CRT_exponent. */ #ifdef PNG_FLOATING_POINT_SUPPORTED if (png_get_gAMA(png_ptr, info_ptr, &gamma)) png_set_gamma(png_ptr, mainprog_ptr->display_exponent, gamma); else png_set_gamma(png_ptr, mainprog_ptr->display_exponent, 0.45455); #else if (png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), gamma); else png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), 45455); #endif /* we'll let libpng expand interlaced images, too */ mainprog_ptr->passes = png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data and * then get rowbytes and channels */ png_read_update_info(png_ptr, info_ptr); mainprog_ptr->rowbytes = (int)png_get_rowbytes(png_ptr, info_ptr); mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr); /* Call the main program to allocate memory for the image buffer and * initialize windows and whatnot. (The old-style function-pointer * invocation is used for compatibility with a few supposedly ANSI * compilers that nevertheless barf on "fn_ptr()"-style syntax.) */ (*mainprog_ptr->mainprog_init)(); /* and that takes care of initialization */ return; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr) { mainprog_info *mainprog_ptr; int color_type, bit_depth; png_uint_32 width, height; #ifdef PNG_FLOATING_POINT_SUPPORTED double gamma; #else png_fixed_point gamma; #endif /* setjmp() doesn't make sense here, because we'd either have to exit(), * longjmp() ourselves, or return control to libpng, which doesn't want * to see us again. By not doing anything here, libpng will instead jump * to readpng2_decode_data(), which can return an error value to the main * program. */ /* retrieve the pointer to our special-purpose struct, using the png_ptr * that libpng passed back to us (i.e., not a global this time--there's * no real difference for a single image, but for a multithreaded browser * decoding several PNG images at the same time, one needs to avoid mixing * up different images' structs) */ mainprog_ptr = png_get_progressive_ptr(png_ptr); if (mainprog_ptr == NULL) { /* we be hosed */ fprintf(stderr, "readpng2 error: main struct not recoverable in info_callback.\n"); fflush(stderr); return; /* * Alternatively, we could call our error-handler just like libpng * does, which would effectively terminate the program. Since this * can only happen if png_ptr gets redirected somewhere odd or the * main PNG struct gets wiped, we're probably toast anyway. (If * png_ptr itself is NULL, we would not have been called.) */ } /* this is just like in the non-progressive case */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); mainprog_ptr->width = (ulg)width; mainprog_ptr->height = (ulg)height; /* since we know we've read all of the PNG file's "header" (i.e., up * to IDAT), we can check for a background color here */ if (mainprog_ptr->need_bgcolor) { png_color_16p pBackground; /* it is not obvious from the libpng documentation, but this function * takes a pointer to a pointer, and it always returns valid red, * green and blue values, regardless of color_type: */ if (png_get_bKGD(png_ptr, info_ptr, &pBackground)) { /* however, it always returns the raw bKGD data, regardless of any * bit-depth transformations, so check depth and adjust if necessary */ if (bit_depth == 16) { mainprog_ptr->bg_red = pBackground->red >> 8; mainprog_ptr->bg_green = pBackground->green >> 8; mainprog_ptr->bg_blue = pBackground->blue >> 8; } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { if (bit_depth == 1) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = pBackground->gray? 255 : 0; else if (bit_depth == 2) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/3) * pBackground->gray; else /* bit_depth == 4 */ mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/15) * pBackground->gray; } else { mainprog_ptr->bg_red = (uch)pBackground->red; mainprog_ptr->bg_green = (uch)pBackground->green; mainprog_ptr->bg_blue = (uch)pBackground->blue; } } } /* as before, let libpng expand palette images to RGB, low-bit-depth * grayscale images to 8 bits, transparency chunks to full alpha channel; * strip 16-bit-per-sample images to 8 bits per sample; and convert * grayscale to RGB[A] */ if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); #ifdef PNG_READ_16_TO_8_SUPPORTED if (bit_depth == 16) # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED png_set_scale_16(png_ptr); # else png_set_strip_16(png_ptr); # endif #endif if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); /* Unlike the basic viewer, which was designed to operate on local files, * this program is intended to simulate a web browser--even though we * actually read from a local file, too. But because we are pretending * that most of the images originate on the Internet, we follow the recom- * mendation of the sRGB proposal and treat unlabelled images (no gAMA * chunk) as existing in the sRGB color space. That is, we assume that * such images have a file gamma of 0.45455, which corresponds to a PC-like * display system. This change in assumptions will have no effect on a * PC-like system, but on a Mac, SGI, NeXT or other system with a non- * identity lookup table, it will darken unlabelled images, which effec- * tively favors images from PC-like systems over those originating on * the local platform. Note that mainprog_ptr->display_exponent is the * "gamma" value for the entire display system, i.e., the product of * LUT_exponent and CRT_exponent. */ #ifdef PNG_FLOATING_POINT_SUPPORTED if (png_get_gAMA(png_ptr, info_ptr, &gamma)) png_set_gamma(png_ptr, mainprog_ptr->display_exponent, gamma); else png_set_gamma(png_ptr, mainprog_ptr->display_exponent, 0.45455); #else if (png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), gamma); else png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), 45455); #endif /* we'll let libpng expand interlaced images, too */ mainprog_ptr->passes = png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data and * then get rowbytes and channels */ png_read_update_info(png_ptr, info_ptr); mainprog_ptr->rowbytes = (int)png_get_rowbytes(png_ptr, info_ptr); mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr); /* Call the main program to allocate memory for the image buffer and * initialize windows and whatnot. (The old-style function-pointer * invocation is used for compatibility with a few supposedly ANSI * compilers that nevertheless barf on "fn_ptr()"-style syntax.) */ (*mainprog_ptr->mainprog_init)(); /* and that takes care of initialization */ return; }
173,569
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ndp_sock_recv(struct ndp *ndp) { struct ndp_msg *msg; enum ndp_msg_type msg_type; size_t len; int err; msg = ndp_msg_alloc(); if (!msg) return -ENOMEM; len = ndp_msg_payload_maxlen(msg); err = myrecvfrom6(ndp->sock, msg->buf, &len, 0, &msg->addrto, &msg->ifindex); if (err) { err(ndp, "Failed to receive message"); goto free_msg; } dbg(ndp, "rcvd from: %s, ifindex: %u", str_in6_addr(&msg->addrto), msg->ifindex); if (len < sizeof(*msg->icmp6_hdr)) { warn(ndp, "rcvd icmp6 packet too short (%luB)", len); err = 0; goto free_msg; } err = ndp_msg_type_by_raw_type(&msg_type, msg->icmp6_hdr->icmp6_type); if (err) { err = 0; goto free_msg; } ndp_msg_init(msg, msg_type); ndp_msg_payload_len_set(msg, len); if (!ndp_msg_check_valid(msg)) { warn(ndp, "rcvd invalid ND message"); err = 0; goto free_msg; } dbg(ndp, "rcvd %s, len: %zuB", ndp_msg_type_info(msg_type)->strabbr, len); if (!ndp_msg_check_opts(msg)) { err = 0; goto free_msg; } err = ndp_call_handlers(ndp, msg);; free_msg: ndp_msg_destroy(msg); return err; } Commit Message: libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <[email protected]> Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]> CWE ID: CWE-284
static int ndp_sock_recv(struct ndp *ndp) { struct ndp_msg *msg; enum ndp_msg_type msg_type; size_t len; int err; msg = ndp_msg_alloc(); if (!msg) return -ENOMEM; len = ndp_msg_payload_maxlen(msg); err = myrecvfrom6(ndp->sock, msg->buf, &len, 0, &msg->addrto, &msg->ifindex, &msg->hoplimit); if (err) { err(ndp, "Failed to receive message"); goto free_msg; } dbg(ndp, "rcvd from: %s, ifindex: %u, hoplimit: %d", str_in6_addr(&msg->addrto), msg->ifindex, msg->hoplimit); if (msg->hoplimit != 255) { warn(ndp, "ignoring packet with bad hop limit (%d)", msg->hoplimit); err = 0; goto free_msg; } if (len < sizeof(*msg->icmp6_hdr)) { warn(ndp, "rcvd icmp6 packet too short (%luB)", len); err = 0; goto free_msg; } err = ndp_msg_type_by_raw_type(&msg_type, msg->icmp6_hdr->icmp6_type); if (err) { err = 0; goto free_msg; } ndp_msg_init(msg, msg_type); ndp_msg_payload_len_set(msg, len); if (!ndp_msg_check_valid(msg)) { warn(ndp, "rcvd invalid ND message"); err = 0; goto free_msg; } dbg(ndp, "rcvd %s, len: %zuB", ndp_msg_type_info(msg_type)->strabbr, len); if (!ndp_msg_check_opts(msg)) { err = 0; goto free_msg; } err = ndp_call_handlers(ndp, msg);; free_msg: ndp_msg_destroy(msg); return err; }
167,350
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int 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
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 = UINT64_MAX; 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; }
168,498
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::Edition::~Edition() { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Chapters::Edition::~Edition() Chapters::Atom::~Atom() {} unsigned long long Chapters::Atom::GetUID() const { return m_uid; } const char* Chapters::Atom::GetStringUID() const { return m_string_uid; } long long Chapters::Atom::GetStartTimecode() const { return m_start_timecode; } long long Chapters::Atom::GetStopTimecode() const { return m_stop_timecode; } long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const { return GetTime(pChapters, m_start_timecode); }
174,466
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResetPaddingKeyForTesting() { *GetPaddingKey() = SymmetricKey::GenerateRandomKey(kPaddingKeyAlgorithm, 128); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void ResetPaddingKeyForTesting() { *GetPaddingKeyInternal() = SymmetricKey::GenerateRandomKey(kPaddingKeyAlgorithm, 128); }
173,001
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { const xmlChar *in; int nbchar = 0; int line = ctxt->input->line; int col = ctxt->input->col; int ccol; SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ if (!cdata) { in = ctxt->input->cur; do { get_more_space: while (*in == 0x20) { in++; ctxt->input->col++; } if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more_space; } if (*in == '<') { nbchar = in - ctxt->input->cur; if (nbchar > 0) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters)) { if (areBlanks(ctxt, tmp, nbchar, 1)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } } else if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL)) { ctxt->sax->characters(ctxt->userData, tmp, nbchar); } } return; } get_more: ccol = ctxt->input->col; while (test_char_data[*in]) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } if (*in == ']') { if ((in[1] == ']') && (in[2] == '>')) { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); ctxt->input->cur = in; return; } in++; ctxt->input->col++; goto get_more; } nbchar = in - ctxt->input->cur; if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters) && (IS_BLANK_CH(*ctxt->input->cur))) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if (areBlanks(ctxt, tmp, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } line = ctxt->input->line; col = ctxt->input->col; } else if (ctxt->sax != NULL) { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, nbchar); line = ctxt->input->line; col = ctxt->input->col; } /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } ctxt->input->cur = in; if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } if (*in == '<') { return; } if (*in == '&') { return; } SHRINK; GROW; in = ctxt->input->cur; } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); nbchar = 0; } ctxt->input->line = line; ctxt->input->col = col; xmlParseCharDataComplex(ctxt, cdata); } 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
xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { const xmlChar *in; int nbchar = 0; int line = ctxt->input->line; int col = ctxt->input->col; int ccol; SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ if (!cdata) { in = ctxt->input->cur; do { get_more_space: while (*in == 0x20) { in++; ctxt->input->col++; } if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more_space; } if (*in == '<') { nbchar = in - ctxt->input->cur; if (nbchar > 0) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters)) { if (areBlanks(ctxt, tmp, nbchar, 1)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } } else if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL)) { ctxt->sax->characters(ctxt->userData, tmp, nbchar); } } return; } get_more: ccol = ctxt->input->col; while (test_char_data[*in]) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } if (*in == ']') { if ((in[1] == ']') && (in[2] == '>')) { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); ctxt->input->cur = in; return; } in++; ctxt->input->col++; goto get_more; } nbchar = in - ctxt->input->cur; if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters) && (IS_BLANK_CH(*ctxt->input->cur))) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if (areBlanks(ctxt, tmp, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } line = ctxt->input->line; col = ctxt->input->col; } else if (ctxt->sax != NULL) { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, nbchar); line = ctxt->input->line; col = ctxt->input->col; } /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } ctxt->input->cur = in; if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } if (*in == '<') { return; } if (*in == '&') { return; } SHRINK; GROW; if (ctxt->instate == XML_PARSER_EOF) return; in = ctxt->input->cur; } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); nbchar = 0; } ctxt->input->line = line; ctxt->input->col = col; xmlParseCharDataComplex(ctxt, cdata); }
171,274
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t BnGraphicBufferProducer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case REQUEST_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferIdx = data.readInt32(); sp<GraphicBuffer> buffer; int result = requestBuffer(bufferIdx, &buffer); reply->writeInt32(buffer != 0); if (buffer != 0) { reply->write(*buffer); } reply->writeInt32(result); return NO_ERROR; } case SET_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferCount = data.readInt32(); int result = setBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } case DEQUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = static_cast<bool>(data.readInt32()); uint32_t width = data.readUint32(); uint32_t height = data.readUint32(); PixelFormat format = static_cast<PixelFormat>(data.readInt32()); uint32_t usage = data.readUint32(); int buf = 0; sp<Fence> fence; int result = dequeueBuffer(&buf, &fence, async, width, height, format, usage); reply->writeInt32(buf); reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } reply->writeInt32(result); return NO_ERROR; } case DETACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int slot = data.readInt32(); int result = detachBuffer(slot); reply->writeInt32(result); return NO_ERROR; } case DETACH_NEXT_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<GraphicBuffer> buffer; sp<Fence> fence; int32_t result = detachNextBuffer(&buffer, &fence); reply->writeInt32(result); if (result == NO_ERROR) { reply->writeInt32(buffer != NULL); if (buffer != NULL) { reply->write(*buffer); } reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } } return NO_ERROR; } case ATTACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<GraphicBuffer> buffer = new GraphicBuffer(); data.read(*buffer.get()); int slot = 0; int result = attachBuffer(&slot, buffer); reply->writeInt32(slot); reply->writeInt32(result); return NO_ERROR; } case QUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); QueueBufferInput input(data); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); memset(output, 0, sizeof(QueueBufferOutput)); status_t result = queueBuffer(buf, input, output); reply->writeInt32(result); return NO_ERROR; } case CANCEL_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); sp<Fence> fence = new Fence(); data.read(*fence.get()); cancelBuffer(buf, fence); return NO_ERROR; } case QUERY: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int value = 0; int what = data.readInt32(); int res = query(what, &value); reply->writeInt32(value); reply->writeInt32(res); return NO_ERROR; } case CONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<IProducerListener> listener; if (data.readInt32() == 1) { listener = IProducerListener::asInterface(data.readStrongBinder()); } int api = data.readInt32(); bool producerControlledByApp = data.readInt32(); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); status_t res = connect(listener, api, producerControlledByApp, output); reply->writeInt32(res); return NO_ERROR; } case DISCONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int api = data.readInt32(); status_t res = disconnect(api); reply->writeInt32(res); return NO_ERROR; } case SET_SIDEBAND_STREAM: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<NativeHandle> stream; if (data.readInt32()) { stream = NativeHandle::create(data.readNativeHandle(), true); } status_t result = setSidebandStream(stream); reply->writeInt32(result); return NO_ERROR; } case ALLOCATE_BUFFERS: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = static_cast<bool>(data.readInt32()); uint32_t width = data.readUint32(); uint32_t height = data.readUint32(); PixelFormat format = static_cast<PixelFormat>(data.readInt32()); uint32_t usage = data.readUint32(); allocateBuffers(async, width, height, format, usage); return NO_ERROR; } case ALLOW_ALLOCATION: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool allow = static_cast<bool>(data.readInt32()); status_t result = allowAllocation(allow); reply->writeInt32(result); return NO_ERROR; } case SET_GENERATION_NUMBER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); uint32_t generationNumber = data.readUint32(); status_t result = setGenerationNumber(generationNumber); reply->writeInt32(result); return NO_ERROR; } case GET_CONSUMER_NAME: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); reply->writeString8(getConsumerName()); return NO_ERROR; } } return BBinder::onTransact(code, data, reply, flags); } Commit Message: BQ: fix some uninitialized variables Bug 27555981 Bug 27556038 Change-Id: I436b6fec589677d7e36c0e980f6e59808415dc0e CWE ID: CWE-200
status_t BnGraphicBufferProducer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case REQUEST_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferIdx = data.readInt32(); sp<GraphicBuffer> buffer; int result = requestBuffer(bufferIdx, &buffer); reply->writeInt32(buffer != 0); if (buffer != 0) { reply->write(*buffer); } reply->writeInt32(result); return NO_ERROR; } case SET_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferCount = data.readInt32(); int result = setBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } case DEQUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = static_cast<bool>(data.readInt32()); uint32_t width = data.readUint32(); uint32_t height = data.readUint32(); PixelFormat format = static_cast<PixelFormat>(data.readInt32()); uint32_t usage = data.readUint32(); int buf = 0; sp<Fence> fence; int result = dequeueBuffer(&buf, &fence, async, width, height, format, usage); reply->writeInt32(buf); reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } reply->writeInt32(result); return NO_ERROR; } case DETACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int slot = data.readInt32(); int result = detachBuffer(slot); reply->writeInt32(result); return NO_ERROR; } case DETACH_NEXT_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<GraphicBuffer> buffer; sp<Fence> fence; int32_t result = detachNextBuffer(&buffer, &fence); reply->writeInt32(result); if (result == NO_ERROR) { reply->writeInt32(buffer != NULL); if (buffer != NULL) { reply->write(*buffer); } reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } } return NO_ERROR; } case ATTACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<GraphicBuffer> buffer = new GraphicBuffer(); data.read(*buffer.get()); int slot = 0; int result = attachBuffer(&slot, buffer); reply->writeInt32(slot); reply->writeInt32(result); return NO_ERROR; } case QUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); QueueBufferInput input(data); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); memset(output, 0, sizeof(QueueBufferOutput)); status_t result = queueBuffer(buf, input, output); reply->writeInt32(result); return NO_ERROR; } case CANCEL_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); sp<Fence> fence = new Fence(); data.read(*fence.get()); cancelBuffer(buf, fence); return NO_ERROR; } case QUERY: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int value = 0; int what = data.readInt32(); int res = query(what, &value); reply->writeInt32(value); reply->writeInt32(res); return NO_ERROR; } case CONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<IProducerListener> listener; if (data.readInt32() == 1) { listener = IProducerListener::asInterface(data.readStrongBinder()); } int api = data.readInt32(); bool producerControlledByApp = data.readInt32(); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); memset(output, 0, sizeof(QueueBufferOutput)); status_t res = connect(listener, api, producerControlledByApp, output); reply->writeInt32(res); return NO_ERROR; } case DISCONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int api = data.readInt32(); status_t res = disconnect(api); reply->writeInt32(res); return NO_ERROR; } case SET_SIDEBAND_STREAM: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<NativeHandle> stream; if (data.readInt32()) { stream = NativeHandle::create(data.readNativeHandle(), true); } status_t result = setSidebandStream(stream); reply->writeInt32(result); return NO_ERROR; } case ALLOCATE_BUFFERS: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = static_cast<bool>(data.readInt32()); uint32_t width = data.readUint32(); uint32_t height = data.readUint32(); PixelFormat format = static_cast<PixelFormat>(data.readInt32()); uint32_t usage = data.readUint32(); allocateBuffers(async, width, height, format, usage); return NO_ERROR; } case ALLOW_ALLOCATION: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool allow = static_cast<bool>(data.readInt32()); status_t result = allowAllocation(allow); reply->writeInt32(result); return NO_ERROR; } case SET_GENERATION_NUMBER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); uint32_t generationNumber = data.readUint32(); status_t result = setGenerationNumber(generationNumber); reply->writeInt32(result); return NO_ERROR; } case GET_CONSUMER_NAME: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); reply->writeString8(getConsumerName()); return NO_ERROR; } } return BBinder::onTransact(code, data, reply, flags); }
173,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int tmx_check_pretran(sip_msg_t *msg) { unsigned int chid; unsigned int slotid; int dsize; struct via_param *vbr; str scallid; str scseqmet; str scseqnum; str sftag; str svbranch = {NULL, 0}; pretran_t *it; if(_tmx_ptran_table==NULL) { LM_ERR("pretran hash table not initialized yet\n"); return -1; } if(get_route_type()!=REQUEST_ROUTE) { LM_ERR("invalid usage - not in request route\n"); return -1; } if(msg->first_line.type!=SIP_REQUEST) { LM_ERR("invalid usage - not a sip request\n"); return -1; } if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { LM_ERR("failed to parse required headers\n"); return -1; } if(msg->cseq==NULL || msg->cseq->parsed==NULL) { LM_ERR("failed to parse cseq headers\n"); return -1; } if(get_cseq(msg)->method_id==METHOD_ACK || get_cseq(msg)->method_id==METHOD_CANCEL) { LM_DBG("no pre-transaction management for ACK or CANCEL\n"); return -1; } if (msg->via1==0) { LM_ERR("failed to get Via header\n"); return -1; } if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { LM_ERR("failed to get From header\n"); return -1; } if (msg->callid==NULL || msg->callid->body.s==NULL) { LM_ERR("failed to parse callid headers\n"); return -1; } vbr = msg->via1->branch; scallid = msg->callid->body; trim(&scallid); scseqmet = get_cseq(msg)->method; trim(&scseqmet); scseqnum = get_cseq(msg)->number; trim(&scseqnum); sftag = get_from(msg)->tag_value; trim(&sftag); chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); slotid = chid & (_tmx_ptran_size-1); if(unlikely(_tmx_proc_ptran == NULL)) { _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); if(_tmx_proc_ptran == NULL) { LM_ERR("not enough memory for pretran structure\n"); return -1; } memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); _tmx_proc_ptran->pid = my_pid(); } dsize = scallid.len + scseqnum.len + scseqmet.len + sftag.len + 4; if(likely(vbr!=NULL)) { svbranch = vbr->value; trim(&svbranch); dsize += svbranch.len; } if(dsize<256) dsize = 256; tmx_pretran_unlink(); if(dsize > _tmx_proc_ptran->dbuf.len) { if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); if(_tmx_proc_ptran->dbuf.s==NULL) { LM_ERR("not enough memory for pretran data\n"); return -1; } _tmx_proc_ptran->dbuf.len = dsize; } _tmx_proc_ptran->hid = chid; _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); _tmx_proc_ptran->callid.len = scallid.len; _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + _tmx_proc_ptran->callid.len + 1; memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); _tmx_proc_ptran->ftag.len = sftag.len; _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + _tmx_proc_ptran->ftag.len + 1; memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); _tmx_proc_ptran->cseqnum.len = scseqnum.len; _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + _tmx_proc_ptran->cseqnum.len + 1; memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); _tmx_proc_ptran->cseqmet.len = scseqmet.len; _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; if(likely(vbr!=NULL)) { _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + _tmx_proc_ptran->cseqmet.len + 1; memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); _tmx_proc_ptran->vbranch.len = svbranch.len; _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; } else { _tmx_proc_ptran->vbranch.s = NULL; _tmx_proc_ptran->vbranch.len = 0; } lock_get(&_tmx_ptran_table[slotid].lock); it = _tmx_ptran_table[slotid].plist; tmx_pretran_link_safe(slotid); for(; it!=NULL; it=it->next) { if(_tmx_proc_ptran->hid != it->hid || _tmx_proc_ptran->cseqmetid != it->cseqmetid || _tmx_proc_ptran->callid.len != it->callid.len || _tmx_proc_ptran->ftag.len != it->ftag.len || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) continue; if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) continue; /* shortcut - check last char in Via branch * - kamailio/ser adds there branch index => in case of paralel * forking by previous hop, catch it here quickly */ if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] != it->vbranch.s[it->vbranch.len-1]) continue; if(memcmp(_tmx_proc_ptran->vbranch.s, it->vbranch.s, it->vbranch.len)!=0) continue; /* shall stop by matching magic cookie? * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { * LM_DBG("rfc3261 cookie found in Via branch\n"); * } */ } if(memcmp(_tmx_proc_ptran->callid.s, it->callid.s, it->callid.len)!=0 || memcmp(_tmx_proc_ptran->ftag.s, it->ftag.s, it->ftag.len)!=0 || memcmp(_tmx_proc_ptran->cseqnum.s, it->cseqnum.s, it->cseqnum.len)!=0) continue; if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) && memcmp(_tmx_proc_ptran->cseqmet.s, it->cseqmet.s, it->cseqmet.len)!=0) continue; LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n", it->pid, it->callid.len, it->callid.s); lock_release(&_tmx_ptran_table[slotid].lock); return 1; } lock_release(&_tmx_ptran_table[slotid].lock); return 0; } Commit Message: tmx: allocate space to store ending 0 for branch value - reported by Alfred Farrugia and Sandro Gauci CWE ID: CWE-119
int tmx_check_pretran(sip_msg_t *msg) { unsigned int chid; unsigned int slotid; int dsize; struct via_param *vbr; str scallid; str scseqmet; str scseqnum; str sftag; str svbranch = {NULL, 0}; pretran_t *it; if(_tmx_ptran_table==NULL) { LM_ERR("pretran hash table not initialized yet\n"); return -1; } if(get_route_type()!=REQUEST_ROUTE) { LM_ERR("invalid usage - not in request route\n"); return -1; } if(msg->first_line.type!=SIP_REQUEST) { LM_ERR("invalid usage - not a sip request\n"); return -1; } if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { LM_ERR("failed to parse required headers\n"); return -1; } if(msg->cseq==NULL || msg->cseq->parsed==NULL) { LM_ERR("failed to parse cseq headers\n"); return -1; } if(get_cseq(msg)->method_id==METHOD_ACK || get_cseq(msg)->method_id==METHOD_CANCEL) { LM_DBG("no pre-transaction management for ACK or CANCEL\n"); return -1; } if (msg->via1==0) { LM_ERR("failed to get Via header\n"); return -1; } if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { LM_ERR("failed to get From header\n"); return -1; } if (msg->callid==NULL || msg->callid->body.s==NULL) { LM_ERR("failed to parse callid headers\n"); return -1; } vbr = msg->via1->branch; scallid = msg->callid->body; trim(&scallid); scseqmet = get_cseq(msg)->method; trim(&scseqmet); scseqnum = get_cseq(msg)->number; trim(&scseqnum); sftag = get_from(msg)->tag_value; trim(&sftag); chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); slotid = chid & (_tmx_ptran_size-1); if(unlikely(_tmx_proc_ptran == NULL)) { _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); if(_tmx_proc_ptran == NULL) { LM_ERR("not enough memory for pretran structure\n"); return -1; } memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); _tmx_proc_ptran->pid = my_pid(); } dsize = scallid.len + scseqnum.len + scseqmet.len + sftag.len + 4; if(likely(vbr!=NULL)) { svbranch = vbr->value; trim(&svbranch); dsize += svbranch.len + 1; } if(dsize<256) dsize = 256; tmx_pretran_unlink(); if(dsize > _tmx_proc_ptran->dbuf.len) { if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); if(_tmx_proc_ptran->dbuf.s==NULL) { LM_ERR("not enough memory for pretran data\n"); return -1; } _tmx_proc_ptran->dbuf.len = dsize; } _tmx_proc_ptran->hid = chid; _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); _tmx_proc_ptran->callid.len = scallid.len; _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + _tmx_proc_ptran->callid.len + 1; memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); _tmx_proc_ptran->ftag.len = sftag.len; _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + _tmx_proc_ptran->ftag.len + 1; memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); _tmx_proc_ptran->cseqnum.len = scseqnum.len; _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + _tmx_proc_ptran->cseqnum.len + 1; memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); _tmx_proc_ptran->cseqmet.len = scseqmet.len; _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; if(likely(vbr!=NULL)) { _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + _tmx_proc_ptran->cseqmet.len + 1; memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); _tmx_proc_ptran->vbranch.len = svbranch.len; _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; } else { _tmx_proc_ptran->vbranch.s = NULL; _tmx_proc_ptran->vbranch.len = 0; } lock_get(&_tmx_ptran_table[slotid].lock); it = _tmx_ptran_table[slotid].plist; tmx_pretran_link_safe(slotid); for(; it!=NULL; it=it->next) { if(_tmx_proc_ptran->hid != it->hid || _tmx_proc_ptran->cseqmetid != it->cseqmetid || _tmx_proc_ptran->callid.len != it->callid.len || _tmx_proc_ptran->ftag.len != it->ftag.len || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) continue; if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) continue; /* shortcut - check last char in Via branch * - kamailio/ser adds there branch index => in case of paralel * forking by previous hop, catch it here quickly */ if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] != it->vbranch.s[it->vbranch.len-1]) continue; if(memcmp(_tmx_proc_ptran->vbranch.s, it->vbranch.s, it->vbranch.len)!=0) continue; /* shall stop by matching magic cookie? * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { * LM_DBG("rfc3261 cookie found in Via branch\n"); * } */ } if(memcmp(_tmx_proc_ptran->callid.s, it->callid.s, it->callid.len)!=0 || memcmp(_tmx_proc_ptran->ftag.s, it->ftag.s, it->ftag.len)!=0 || memcmp(_tmx_proc_ptran->cseqnum.s, it->cseqnum.s, it->cseqnum.len)!=0) continue; if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) && memcmp(_tmx_proc_ptran->cseqmet.s, it->cseqmet.s, it->cseqmet.len)!=0) continue; LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n", it->pid, it->callid.len, it->callid.s); lock_release(&_tmx_ptran_table[slotid].lock); return 1; } lock_release(&_tmx_ptran_table[slotid].lock); return 0; }
169,271
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebContentsImpl::CreateNewWindow( RenderFrameHost* opener, int32_t render_view_route_id, int32_t main_frame_route_id, int32_t main_frame_widget_route_id, const mojom::CreateNewWindowParams& params, SessionStorageNamespace* session_storage_namespace) { DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE), (main_frame_route_id == MSG_ROUTING_NONE)); DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE), (main_frame_widget_route_id == MSG_ROUTING_NONE)); DCHECK(opener); int render_process_id = opener->GetProcess()->GetID(); SiteInstance* source_site_instance = opener->GetSiteInstance(); DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id)); bool is_guest = BrowserPluginGuest::IsGuest(this); DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE); scoped_refptr<SiteInstance> site_instance = params.opener_suppressed && !is_guest ? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) : source_site_instance; const std::string& partition_id = GetContentClient()->browser()-> GetStoragePartitionIdForSite(GetBrowserContext(), site_instance->GetSiteURL()); StoragePartition* partition = BrowserContext::GetStoragePartition( GetBrowserContext(), site_instance.get()); DOMStorageContextWrapper* dom_storage_context = static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext()); SessionStorageNamespaceImpl* session_storage_namespace_impl = static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace); CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context)); if (delegate_ && !delegate_->ShouldCreateWebContents( this, opener, source_site_instance, render_view_route_id, main_frame_route_id, main_frame_widget_route_id, params.window_container_type, opener->GetLastCommittedURL(), params.frame_name, params.target_url, partition_id, session_storage_namespace)) { RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id); if (rfh) { DCHECK(rfh->IsRenderFrameLive()); rfh->Init(); } return; } CreateParams create_params(GetBrowserContext(), site_instance.get()); create_params.routing_id = render_view_route_id; create_params.main_frame_routing_id = main_frame_route_id; create_params.main_frame_widget_routing_id = main_frame_widget_route_id; create_params.main_frame_name = params.frame_name; create_params.opener_render_process_id = render_process_id; create_params.opener_render_frame_id = opener->GetRoutingID(); create_params.opener_suppressed = params.opener_suppressed; if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) create_params.initially_hidden = true; create_params.renderer_initiated_creation = main_frame_route_id != MSG_ROUTING_NONE; std::unique_ptr<WebContents> new_contents; if (!is_guest) { create_params.context = view_->GetNativeView(); create_params.initial_size = GetContainerBounds().size(); new_contents = WebContents::Create(create_params); } else { new_contents = base::WrapUnique( GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)); } WebContentsImpl* raw_new_contents = static_cast<WebContentsImpl*>(new_contents.get()); raw_new_contents->GetController().SetSessionStorageNamespace( partition_id, session_storage_namespace); if (!params.frame_name.empty()) raw_new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame(); if (!params.opener_suppressed) { if (!is_guest) { WebContentsView* new_view = raw_new_contents->view_.get(); new_view->CreateViewForWidget( new_contents->GetRenderViewHost()->GetWidget(), false); } DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id); pending_contents_[std::make_pair(render_process_id, main_frame_widget_route_id)] = std::move(new_contents); AddDestructionObserver(raw_new_contents); } if (delegate_) { delegate_->WebContentsCreated(this, render_process_id, opener->GetRoutingID(), params.frame_name, params.target_url, raw_new_contents); } if (opener) { for (auto& observer : observers_) { observer.DidOpenRequestedURL(raw_new_contents, opener, params.target_url, params.referrer, params.disposition, ui::PAGE_TRANSITION_LINK, false, // started_from_context_menu true); // renderer_initiated } } if (IsFullscreenForCurrentTab()) ExitFullscreen(true); if (params.opener_suppressed) { bool was_blocked = false; base::WeakPtr<WebContentsImpl> weak_new_contents = raw_new_contents->weak_factory_.GetWeakPtr(); if (delegate_) { gfx::Rect initial_rect; delegate_->AddNewContents(this, std::move(new_contents), params.disposition, initial_rect, params.mimic_user_gesture, &was_blocked); if (!weak_new_contents) return; // The delegate deleted |new_contents| during AddNewContents(). } if (!was_blocked) { OpenURLParams open_params(params.target_url, params.referrer, WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_LINK, true /* is_renderer_initiated */); open_params.user_gesture = params.mimic_user_gesture; if (delegate_ && !is_guest && !delegate_->ShouldResumeRequestsForCreatedWindow()) { DCHECK(weak_new_contents); weak_new_contents->delayed_open_url_params_.reset( new OpenURLParams(open_params)); } else { weak_new_contents->OpenURL(open_params); } } } } Commit Message: Security drop fullscreen for any nested WebContents level. This relands 3dcaec6e30feebefc11e with a fix to the test. BUG=873080 TEST=as in bug Change-Id: Ie68b197fc6b92447e9633f233354a68fefcf20c7 Reviewed-on: https://chromium-review.googlesource.com/1175925 Reviewed-by: Sidney San Martín <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#583335} CWE ID: CWE-20
void WebContentsImpl::CreateNewWindow( RenderFrameHost* opener, int32_t render_view_route_id, int32_t main_frame_route_id, int32_t main_frame_widget_route_id, const mojom::CreateNewWindowParams& params, SessionStorageNamespace* session_storage_namespace) { DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE), (main_frame_route_id == MSG_ROUTING_NONE)); DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE), (main_frame_widget_route_id == MSG_ROUTING_NONE)); DCHECK(opener); int render_process_id = opener->GetProcess()->GetID(); SiteInstance* source_site_instance = opener->GetSiteInstance(); DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id)); bool is_guest = BrowserPluginGuest::IsGuest(this); DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE); scoped_refptr<SiteInstance> site_instance = params.opener_suppressed && !is_guest ? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) : source_site_instance; const std::string& partition_id = GetContentClient()->browser()-> GetStoragePartitionIdForSite(GetBrowserContext(), site_instance->GetSiteURL()); StoragePartition* partition = BrowserContext::GetStoragePartition( GetBrowserContext(), site_instance.get()); DOMStorageContextWrapper* dom_storage_context = static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext()); SessionStorageNamespaceImpl* session_storage_namespace_impl = static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace); CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context)); if (delegate_ && !delegate_->ShouldCreateWebContents( this, opener, source_site_instance, render_view_route_id, main_frame_route_id, main_frame_widget_route_id, params.window_container_type, opener->GetLastCommittedURL(), params.frame_name, params.target_url, partition_id, session_storage_namespace)) { RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id); if (rfh) { DCHECK(rfh->IsRenderFrameLive()); rfh->Init(); } return; } CreateParams create_params(GetBrowserContext(), site_instance.get()); create_params.routing_id = render_view_route_id; create_params.main_frame_routing_id = main_frame_route_id; create_params.main_frame_widget_routing_id = main_frame_widget_route_id; create_params.main_frame_name = params.frame_name; create_params.opener_render_process_id = render_process_id; create_params.opener_render_frame_id = opener->GetRoutingID(); create_params.opener_suppressed = params.opener_suppressed; if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) create_params.initially_hidden = true; create_params.renderer_initiated_creation = main_frame_route_id != MSG_ROUTING_NONE; std::unique_ptr<WebContents> new_contents; if (!is_guest) { create_params.context = view_->GetNativeView(); create_params.initial_size = GetContainerBounds().size(); new_contents = WebContents::Create(create_params); } else { new_contents = base::WrapUnique( GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)); } WebContentsImpl* raw_new_contents = static_cast<WebContentsImpl*>(new_contents.get()); raw_new_contents->GetController().SetSessionStorageNamespace( partition_id, session_storage_namespace); if (!params.frame_name.empty()) raw_new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame(); if (!params.opener_suppressed) { if (!is_guest) { WebContentsView* new_view = raw_new_contents->view_.get(); new_view->CreateViewForWidget( new_contents->GetRenderViewHost()->GetWidget(), false); } DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id); pending_contents_[std::make_pair(render_process_id, main_frame_widget_route_id)] = std::move(new_contents); AddDestructionObserver(raw_new_contents); } if (delegate_) { delegate_->WebContentsCreated(this, render_process_id, opener->GetRoutingID(), params.frame_name, params.target_url, raw_new_contents); } if (opener) { for (auto& observer : observers_) { observer.DidOpenRequestedURL(raw_new_contents, opener, params.target_url, params.referrer, params.disposition, ui::PAGE_TRANSITION_LINK, false, // started_from_context_menu true); // renderer_initiated } } ForSecurityDropFullscreen(); if (params.opener_suppressed) { bool was_blocked = false; base::WeakPtr<WebContentsImpl> weak_new_contents = raw_new_contents->weak_factory_.GetWeakPtr(); if (delegate_) { gfx::Rect initial_rect; delegate_->AddNewContents(this, std::move(new_contents), params.disposition, initial_rect, params.mimic_user_gesture, &was_blocked); if (!weak_new_contents) return; // The delegate deleted |new_contents| during AddNewContents(). } if (!was_blocked) { OpenURLParams open_params(params.target_url, params.referrer, WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_LINK, true /* is_renderer_initiated */); open_params.user_gesture = params.mimic_user_gesture; if (delegate_ && !is_guest && !delegate_->ShouldResumeRequestsForCreatedWindow()) { DCHECK(weak_new_contents); weak_new_contents->delayed_open_url_params_.reset( new OpenURLParams(open_params)); } else { weak_new_contents->OpenURL(open_params); } } } }
172,660
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: http_dissect_hdrs(struct worker *w, struct http *hp, int fd, char *p, const struct http_conn *htc) { char *q, *r; txt t = htc->rxbuf; if (*p == '\r') p++; hp->nhd = HTTP_HDR_FIRST; hp->conds = 0; r = NULL; /* For FlexeLint */ for (; p < t.e; p = r) { /* Find end of next header */ q = r = p; while (r < t.e) { if (!vct_iscrlf(*r)) { r++; continue; } q = r; assert(r < t.e); r += vct_skipcrlf(r); if (r >= t.e) break; /* If line does not continue: got it. */ if (!vct_issp(*r)) break; /* Clear line continuation LWS to spaces */ while (vct_islws(*q)) *q++ = ' '; } if (q - p > htc->maxhdr) { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } /* Empty header = end of headers */ if (p == q) break; if ((p[0] == 'i' || p[0] == 'I') && (p[1] == 'f' || p[1] == 'F') && p[2] == '-') hp->conds = 1; while (q > p && vct_issp(q[-1])) q--; *q = '\0'; if (hp->nhd < hp->shd) { hp->hdf[hp->nhd] = 0; hp->hd[hp->nhd].b = p; hp->hd[hp->nhd].e = q; WSLH(w, fd, hp, hp->nhd); hp->nhd++; } else { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } } return (0); } 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:
http_dissect_hdrs(struct worker *w, struct http *hp, int fd, char *p, const struct http_conn *htc) { char *q, *r; txt t = htc->rxbuf; if (*p == '\r') p++; hp->nhd = HTTP_HDR_FIRST; hp->conds = 0; r = NULL; /* For FlexeLint */ for (; p < t.e; p = r) { /* Find end of next header */ q = r = p; while (r < t.e) { if (!vct_iscrlf(r)) { r++; continue; } q = r; assert(r < t.e); r += vct_skipcrlf(r); if (r >= t.e) break; /* If line does not continue: got it. */ if (!vct_issp(*r)) break; /* Clear line continuation LWS to spaces */ while (vct_islws(*q)) *q++ = ' '; } if (q - p > htc->maxhdr) { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } /* Empty header = end of headers */ if (p == q) break; if ((p[0] == 'i' || p[0] == 'I') && (p[1] == 'f' || p[1] == 'F') && p[2] == '-') hp->conds = 1; while (q > p && vct_issp(q[-1])) q--; *q = '\0'; if (hp->nhd < hp->shd) { hp->hdf[hp->nhd] = 0; hp->hd[hp->nhd].b = p; hp->hd[hp->nhd].e = q; WSLH(w, fd, hp, hp->nhd); hp->nhd++; } else { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } } return (0); }
169,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void grubfs_free (GrubFS *gf) { if (gf) { if (gf->file && gf->file->device) free (gf->file->device->disk); free (gf->file); free (gf); } } Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack CWE ID: CWE-119
void grubfs_free (GrubFS *gf) { if (gf) { if (gf->file && gf->file->device) { free (gf->file->device->disk); } free (gf->file); free (gf); } }
168,090
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LoadingStatsCollector::RecordPreconnectStats( std::unique_ptr<PreconnectStats> stats) { const GURL& main_frame_url = stats->url; auto it = preconnect_stats_.find(main_frame_url); if (it != preconnect_stats_.end()) { ReportPreconnectAccuracy(*it->second, std::map<GURL, OriginRequestSummary>()); preconnect_stats_.erase(it); } preconnect_stats_.emplace(main_frame_url, std::move(stats)); } 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
void LoadingStatsCollector::RecordPreconnectStats( std::unique_ptr<PreconnectStats> stats) { const GURL& main_frame_url = stats->url; auto it = preconnect_stats_.find(main_frame_url); if (it != preconnect_stats_.end()) { ReportPreconnectAccuracy(*it->second, {}); preconnect_stats_.erase(it); } preconnect_stats_.emplace(main_frame_url, std::move(stats)); }
172,371
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { int value; UINT error; UINT32 ChannelId; wStream* data_out; ChannelId = drdynvc_read_variable_uint(s, cbChId); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp, cbChId, ChannelId); if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId))) { WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error); return error; } data_out = Stream_New(NULL, 4); if (!data_out) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03); Stream_Write_UINT8(data_out, value); drdynvc_write_variable_uint(data_out, ChannelId); error = drdynvc_send(drdynvc, data_out); if (error) WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]", WTSErrorToString(error), error); return error; } Commit Message: Fix for #4866: Added additional length checks CWE ID:
static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { int value; UINT error; UINT32 ChannelId; wStream* data_out; if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId)) return ERROR_INVALID_DATA; ChannelId = drdynvc_read_variable_uint(s, cbChId); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp, cbChId, ChannelId); if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId))) { WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error); return error; } data_out = Stream_New(NULL, 4); if (!data_out) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03); Stream_Write_UINT8(data_out, value); drdynvc_write_variable_uint(data_out, ChannelId); error = drdynvc_send(drdynvc, data_out); if (error) WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]", WTSErrorToString(error), error); return error; }
168,935
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __exit xfrm6_tunnel_fini(void) { unregister_pernet_subsys(&xfrm6_tunnel_net_ops); xfrm6_tunnel_spi_fini(); xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET); xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6); xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6); } Commit Message: tunnels: fix netns vs proto registration ordering Same stuff as in ip_gre patch: receive hook can be called before netns setup is done, oopsing in net_generic(). Signed-off-by: Alexey Dobriyan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static void __exit xfrm6_tunnel_fini(void) { xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET); xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6); xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6); unregister_pernet_subsys(&xfrm6_tunnel_net_ops); kmem_cache_destroy(xfrm6_tunnel_spi_kmem); }
165,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AXNodeObject::isMultiSelectable() const { const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr); if (equalIgnoringCase(ariaMultiSelectable, "true")) return true; if (equalIgnoringCase(ariaMultiSelectable, "false")) return false; return isHTMLSelectElement(getNode()) && toHTMLSelectElement(*getNode()).isMultiple(); } 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
bool AXNodeObject::isMultiSelectable() const { const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr); if (equalIgnoringASCIICase(ariaMultiSelectable, "true")) return true; if (equalIgnoringASCIICase(ariaMultiSelectable, "false")) return false; return isHTMLSelectElement(getNode()) && toHTMLSelectElement(*getNode()).isMultiple(); }
171,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileInfo, getFileInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, getFileInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); }
167,042
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SocketStream::SocketStream(const GURL& url, Delegate* delegate) : delegate_(delegate), url_(url), max_pending_send_allowed_(kMaxPendingSendAllowed), next_state_(STATE_NONE), factory_(ClientSocketFactory::GetDefaultFactory()), proxy_mode_(kDirectConnection), proxy_url_(url), pac_request_(NULL), privacy_mode_(kPrivacyModeDisabled), io_callback_(base::Bind(&SocketStream::OnIOCompleted, base::Unretained(this))), read_buf_(NULL), current_write_buf_(NULL), waiting_for_write_completion_(false), closing_(false), server_closed_(false), metrics_(new SocketStreamMetrics(url)) { DCHECK(base::MessageLoop::current()) << "The current base::MessageLoop must exist"; DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type()) << "The current base::MessageLoop must be TYPE_IO"; DCHECK(delegate_); } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
SocketStream::SocketStream(const GURL& url, Delegate* delegate) : delegate_(delegate), url_(url), max_pending_send_allowed_(kMaxPendingSendAllowed), context_(NULL), next_state_(STATE_NONE), factory_(ClientSocketFactory::GetDefaultFactory()), proxy_mode_(kDirectConnection), proxy_url_(url), pac_request_(NULL), privacy_mode_(kPrivacyModeDisabled), io_callback_(base::Bind(&SocketStream::OnIOCompleted, base::Unretained(this))), read_buf_(NULL), current_write_buf_(NULL), waiting_for_write_completion_(false), closing_(false), server_closed_(false), metrics_(new SocketStreamMetrics(url)) { DCHECK(base::MessageLoop::current()) << "The current base::MessageLoop must exist"; DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type()) << "The current base::MessageLoop must be TYPE_IO"; DCHECK(delegate_); }
171,256
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_write_start_row(png_structp png_ptr) { #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif png_size_t buf_size; png_debug(1, "in png_write_start_row"); buf_size = (png_size_t)(PNG_ROWBYTES( png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1); /* Set up row buffer */ png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size); png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE; #ifdef PNG_WRITE_FILTER_SUPPORTED /* Set up filtering buffer, if using this filter */ if (png_ptr->do_filter & PNG_FILTER_SUB) { png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB; } /* We only need to keep the previous row if we are using one of these. */ if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) { /* Set up previous row buffer */ png_ptr->prev_row = (png_bytep)png_calloc(png_ptr, (png_uint_32)buf_size); if (png_ptr->do_filter & PNG_FILTER_UP) { png_ptr->up_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->up_row[0] = PNG_FILTER_VALUE_UP; } if (png_ptr->do_filter & PNG_FILTER_AVG) { png_ptr->avg_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG; } if (png_ptr->do_filter & PNG_FILTER_PAETH) { png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH; } } #endif /* PNG_WRITE_FILTER_SUPPORTED */ #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced, we need to set up width and height of pass */ if (png_ptr->interlaced) { if (!(png_ptr->transformations & PNG_INTERLACE)) { png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 - png_pass_start[0]) / png_pass_inc[0]; } else { png_ptr->num_rows = png_ptr->height; png_ptr->usr_width = png_ptr->width; } } else #endif { png_ptr->num_rows = png_ptr->height; png_ptr->usr_width = png_ptr->width; } png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_ptr->zstream.next_out = png_ptr->zbuf; } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_write_start_row(png_structp png_ptr) { #ifdef PNG_WRITE_INTERLACING_SUPPORTED #ifndef PNG_USE_GLOBAL_ARRAYS /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif #endif png_size_t buf_size; png_debug(1, "in png_write_start_row"); buf_size = (png_size_t)(PNG_ROWBYTES( png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1); /* Set up row buffer */ png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size); png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE; #ifdef PNG_WRITE_FILTER_SUPPORTED /* Set up filtering buffer, if using this filter */ if (png_ptr->do_filter & PNG_FILTER_SUB) { png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB; } /* We only need to keep the previous row if we are using one of these. */ if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) { /* Set up previous row buffer */ png_ptr->prev_row = (png_bytep)png_calloc(png_ptr, (png_uint_32)buf_size); if (png_ptr->do_filter & PNG_FILTER_UP) { png_ptr->up_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->up_row[0] = PNG_FILTER_VALUE_UP; } if (png_ptr->do_filter & PNG_FILTER_AVG) { png_ptr->avg_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG; } if (png_ptr->do_filter & PNG_FILTER_PAETH) { png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH; } } #endif /* PNG_WRITE_FILTER_SUPPORTED */ #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced, we need to set up width and height of pass */ if (png_ptr->interlaced) { if (!(png_ptr->transformations & PNG_INTERLACE)) { png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 - png_pass_start[0]) / png_pass_inc[0]; } else { png_ptr->num_rows = png_ptr->height; png_ptr->usr_width = png_ptr->width; } } else #endif { png_ptr->num_rows = png_ptr->height; png_ptr->usr_width = png_ptr->width; } png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_ptr->zstream.next_out = png_ptr->zbuf; }
172,196
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: main(int argc, char **argv) { png_uint_32 opts = FAST_WRITE; format_list formats; const char *touch = NULL; int log_pass = 0; int redundant = 0; int stride_extra = 0; int retval = 0; int c; init_sRGB_to_d(); #if 0 init_error_via_linear(); #endif format_init(&formats); for (c=1; c<argc; ++c) { const char *arg = argv[c]; if (strcmp(arg, "--log") == 0) log_pass = 1; else if (strcmp(arg, "--fresh") == 0) { memset(gpc_error, 0, sizeof gpc_error); memset(gpc_error_via_linear, 0, sizeof gpc_error_via_linear); } else if (strcmp(arg, "--file") == 0) # ifdef PNG_STDIO_SUPPORTED opts |= READ_FILE; # else return 77; /* skipped: no support */ # endif else if (strcmp(arg, "--memory") == 0) opts &= ~READ_FILE; else if (strcmp(arg, "--stdio") == 0) # ifdef PNG_STDIO_SUPPORTED opts |= USE_STDIO; # else return 77; /* skipped: no support */ # endif else if (strcmp(arg, "--name") == 0) opts &= ~USE_STDIO; else if (strcmp(arg, "--verbose") == 0) opts |= VERBOSE; else if (strcmp(arg, "--quiet") == 0) opts &= ~VERBOSE; else if (strcmp(arg, "--preserve") == 0) opts |= KEEP_TMPFILES; else if (strcmp(arg, "--nopreserve") == 0) opts &= ~KEEP_TMPFILES; else if (strcmp(arg, "--keep-going") == 0) opts |= KEEP_GOING; else if (strcmp(arg, "--fast") == 0) opts |= FAST_WRITE; else if (strcmp(arg, "--slow") == 0) opts &= ~FAST_WRITE; else if (strcmp(arg, "--accumulate") == 0) opts |= ACCUMULATE; else if (strcmp(arg, "--redundant") == 0) redundant = 1; else if (strcmp(arg, "--stop") == 0) opts &= ~KEEP_GOING; else if (strcmp(arg, "--strict") == 0) opts |= STRICT; else if (strcmp(arg, "--sRGB-16bit") == 0) opts |= sRGB_16BIT; else if (strcmp(arg, "--linear-16bit") == 0) opts &= ~sRGB_16BIT; else if (strcmp(arg, "--tmpfile") == 0) { if (c+1 < argc) { if (strlen(argv[++c]) >= sizeof tmpf) { fflush(stdout); fprintf(stderr, "%s: %s is too long for a temp file prefix\n", argv[0], argv[c]); exit(99); } /* Safe: checked above */ strcpy(tmpf, argv[c]); } else { fflush(stdout); fprintf(stderr, "%s: %s requires a temporary file prefix\n", argv[0], arg); exit(99); } } else if (strcmp(arg, "--touch") == 0) { if (c+1 < argc) touch = argv[++c]; else { fflush(stdout); fprintf(stderr, "%s: %s requires a file name argument\n", argv[0], arg); exit(99); } } else if (arg[0] == '+') { png_uint_32 format = formatof(arg+1); if (format > FORMAT_COUNT) exit(99); format_set(&formats, format); } else if (arg[0] == '-' && arg[1] != 0 && (arg[1] != '0' || arg[2] != 0)) { fflush(stdout); fprintf(stderr, "%s: unknown option: %s\n", argv[0], arg); exit(99); } else { if (format_is_initial(&formats)) format_default(&formats, redundant); if (arg[0] == '-') { const int term = (arg[1] == '0' ? 0 : '\n'); unsigned int ich = 0; /* Loop reading files, use a static buffer to simplify this and just * stop if the name gets to long. */ static char buffer[4096]; do { int ch = getchar(); /* Don't allow '\0' in file names, and terminate with '\n' or, * for -0, just '\0' (use -print0 to find to make this work!) */ if (ch == EOF || ch == term || ch == 0) { buffer[ich] = 0; if (ich > 0 && !test_one_file(buffer, &formats, opts, stride_extra, log_pass)) retval = 1; if (ch == EOF) break; ich = 0; --ich; /* so that the increment below sets it to 0 again */ } else buffer[ich] = (char)ch; } while (++ich < sizeof buffer); if (ich) { buffer[32] = 0; buffer[4095] = 0; fprintf(stderr, "%s...%s: file name too long\n", buffer, buffer+(4096-32)); exit(99); } } else if (!test_one_file(arg, &formats, opts, stride_extra, log_pass)) retval = 1; } } if (opts & ACCUMULATE) { unsigned int in; printf("static png_uint_16 gpc_error[16/*in*/][16/*out*/][4/*a*/] =\n"); printf("{\n"); for (in=0; in<16; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<16; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 15) { putchar(','); if (out % 4 == 3) printf("\n "); } } printf("\n }"); if (in < 15) putchar(','); else putchar('\n'); } printf("};\n"); printf("static png_uint_16 gpc_error_via_linear[16][4/*out*/][4] =\n"); printf("{\n"); for (in=0; in<16; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<4; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error_via_linear[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 3) putchar(','); } printf("\n }"); if (in < 15) putchar(','); else putchar('\n'); } printf("};\n"); printf("static png_uint_16 gpc_error_to_colormap[8/*i*/][8/*o*/][4] =\n"); printf("{\n"); for (in=0; in<8; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<8; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error_to_colormap[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 7) { putchar(','); if (out % 4 == 3) printf("\n "); } } printf("\n }"); if (in < 7) putchar(','); else putchar('\n'); } printf("};\n"); } if (retval == 0 && touch != NULL) { FILE *fsuccess = fopen(touch, "wt"); if (fsuccess != NULL) { int error = 0; fprintf(fsuccess, "PNG simple API tests succeeded\n"); fflush(fsuccess); error = ferror(fsuccess); if (fclose(fsuccess) || error) { fflush(stdout); fprintf(stderr, "%s: write failed\n", touch); exit(99); } } else { fflush(stdout); fprintf(stderr, "%s: open failed\n", touch); exit(99); } } return retval; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
main(int argc, char **argv) { png_uint_32 opts = FAST_WRITE; format_list formats; const char *touch = NULL; int log_pass = 0; int redundant = 0; int stride_extra = 0; int retval = 0; int c; init_sRGB_to_d(); #if 0 init_error_via_linear(); #endif format_init(&formats); for (c=1; c<argc; ++c) { const char *arg = argv[c]; if (strcmp(arg, "--log") == 0) log_pass = 1; else if (strcmp(arg, "--fresh") == 0) { memset(gpc_error, 0, sizeof gpc_error); memset(gpc_error_via_linear, 0, sizeof gpc_error_via_linear); } else if (strcmp(arg, "--file") == 0) # ifdef PNG_STDIO_SUPPORTED opts |= READ_FILE; # else return 77; /* skipped: no support */ # endif else if (strcmp(arg, "--memory") == 0) opts &= ~READ_FILE; else if (strcmp(arg, "--stdio") == 0) # ifdef PNG_STDIO_SUPPORTED opts |= USE_STDIO; # else return 77; /* skipped: no support */ # endif else if (strcmp(arg, "--name") == 0) opts &= ~USE_STDIO; else if (strcmp(arg, "--verbose") == 0) opts |= VERBOSE; else if (strcmp(arg, "--quiet") == 0) opts &= ~VERBOSE; else if (strcmp(arg, "--preserve") == 0) opts |= KEEP_TMPFILES; else if (strcmp(arg, "--nopreserve") == 0) opts &= ~KEEP_TMPFILES; else if (strcmp(arg, "--keep-going") == 0) opts |= KEEP_GOING; else if (strcmp(arg, "--fast") == 0) opts |= FAST_WRITE; else if (strcmp(arg, "--slow") == 0) opts &= ~FAST_WRITE; else if (strcmp(arg, "--accumulate") == 0) opts |= ACCUMULATE; else if (strcmp(arg, "--redundant") == 0) redundant = 1; else if (strcmp(arg, "--stop") == 0) opts &= ~KEEP_GOING; else if (strcmp(arg, "--strict") == 0) opts |= STRICT; else if (strcmp(arg, "--sRGB-16bit") == 0) opts |= sRGB_16BIT; else if (strcmp(arg, "--linear-16bit") == 0) opts &= ~sRGB_16BIT; else if (strcmp(arg, "--tmpfile") == 0) { if (c+1 < argc) { if (strlen(argv[++c]) >= sizeof tmpf) { fflush(stdout); fprintf(stderr, "%s: %s is too long for a temp file prefix\n", argv[0], argv[c]); exit(99); } /* Safe: checked above */ strncpy(tmpf, argv[c], sizeof (tmpf)-1); } else { fflush(stdout); fprintf(stderr, "%s: %s requires a temporary file prefix\n", argv[0], arg); exit(99); } } else if (strcmp(arg, "--touch") == 0) { if (c+1 < argc) touch = argv[++c]; else { fflush(stdout); fprintf(stderr, "%s: %s requires a file name argument\n", argv[0], arg); exit(99); } } else if (arg[0] == '+') { png_uint_32 format = formatof(arg+1); if (format > FORMAT_COUNT) exit(99); format_set(&formats, format); } else if (arg[0] == '-' && arg[1] != 0 && (arg[1] != '0' || arg[2] != 0)) { fflush(stdout); fprintf(stderr, "%s: unknown option: %s\n", argv[0], arg); exit(99); } else { if (format_is_initial(&formats)) format_default(&formats, redundant); if (arg[0] == '-') { const int term = (arg[1] == '0' ? 0 : '\n'); unsigned int ich = 0; /* Loop reading files, use a static buffer to simplify this and just * stop if the name gets to long. */ static char buffer[4096]; do { int ch = getchar(); /* Don't allow '\0' in file names, and terminate with '\n' or, * for -0, just '\0' (use -print0 to find to make this work!) */ if (ch == EOF || ch == term || ch == 0) { buffer[ich] = 0; if (ich > 0 && !test_one_file(buffer, &formats, opts, stride_extra, log_pass)) retval = 1; if (ch == EOF) break; ich = 0; --ich; /* so that the increment below sets it to 0 again */ } else buffer[ich] = (char)ch; } while (++ich < sizeof buffer); if (ich) { buffer[32] = 0; buffer[4095] = 0; fprintf(stderr, "%s...%s: file name too long\n", buffer, buffer+(4096-32)); exit(99); } } else if (!test_one_file(arg, &formats, opts, stride_extra, log_pass)) retval = 1; } } if (opts & ACCUMULATE) { unsigned int in; printf("/* contrib/libtests/pngstest-errors.h\n"); printf(" *\n"); printf(" * BUILT USING:" PNG_HEADER_VERSION_STRING); printf(" *\n"); printf(" * This code is released under the libpng license.\n"); printf(" * For conditions of distribution and use, see the disclaimer\n"); printf(" * and license in png.h\n"); printf(" *\n"); printf(" * THIS IS A MACHINE GENERATED FILE: do not edit it directly!\n"); printf(" * Instead run:\n"); printf(" *\n"); printf(" * pngstest --accumulate\n"); printf(" *\n"); printf(" * on as many PNG files as possible; at least PNGSuite and\n"); printf(" * contrib/libtests/testpngs.\n"); printf(" */\n"); printf("static png_uint_16 gpc_error[16/*in*/][16/*out*/][4/*a*/] =\n"); printf("{\n"); for (in=0; in<16; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<16; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 15) { putchar(','); if (out % 4 == 3) printf("\n "); } } printf("\n }"); if (in < 15) putchar(','); else putchar('\n'); } printf("};\n"); printf("static png_uint_16 gpc_error_via_linear[16][4/*out*/][4] =\n"); printf("{\n"); for (in=0; in<16; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<4; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error_via_linear[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 3) putchar(','); } printf("\n }"); if (in < 15) putchar(','); else putchar('\n'); } printf("};\n"); printf("static png_uint_16 gpc_error_to_colormap[8/*i*/][8/*o*/][4] =\n"); printf("{\n"); for (in=0; in<8; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<8; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error_to_colormap[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 7) { putchar(','); if (out % 4 == 3) printf("\n "); } } printf("\n }"); if (in < 7) putchar(','); else putchar('\n'); } printf("};\n"); printf("/* END MACHINE GENERATED */\n"); } if (retval == 0 && touch != NULL) { FILE *fsuccess = fopen(touch, "wt"); if (fsuccess != NULL) { int error = 0; fprintf(fsuccess, "PNG simple API tests succeeded\n"); fflush(fsuccess); error = ferror(fsuccess); if (fclose(fsuccess) || error) { fflush(stdout); fprintf(stderr, "%s: write failed\n", touch); exit(99); } } else { fflush(stdout); fprintf(stderr, "%s: open failed\n", touch); exit(99); } } return retval; }
173,595
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; unsigned char *p,*d; int i,al,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) { if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->s3->flags |= SSL3_FLAGS_CCS_OK; } } #endif /* OPENSSL_NO_TLSEXT */ if (j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->s3->flags |= SSL3_FLAGS_CCS_OK; s->hit=1; } else /* a miss or crap from the other end */ { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ s->hit=0; if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { al=SSL_AD_INTERNAL_ERROR; goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* TLS v1.2 only ciphersuites require v1.2 or later */ if ((c->algorithm_ssl & SSL_TLSV1_2) && (TLS1_get_version(s) < TLS1_2_VERSION)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if TLS v1.2: we may need them for * client authentication. */ if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s)) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (s->options & SSL_OP_NO_COMPRESSION) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (s->version >= SSL3_VERSION) { if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al)) { /* 'al' set by ssl_parse_serverhello_tlsext */ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto f_err; } if (ssl_check_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); goto err; } } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } Commit Message: CWE ID:
int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; unsigned char *p,*d; int i,al,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) { if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->s3->flags |= SSL3_FLAGS_CCS_OK; } } #endif /* OPENSSL_NO_TLSEXT */ if (j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->s3->flags |= SSL3_FLAGS_CCS_OK; s->hit=1; } else /* a miss or crap from the other end */ { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ s->hit=0; if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { al=SSL_AD_INTERNAL_ERROR; goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* TLS v1.2 only ciphersuites require v1.2 or later */ if ((c->algorithm_ssl & SSL_TLSV1_2) && (TLS1_get_version(s) < TLS1_2_VERSION)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } #ifndef OPENSSL_NO_SRP if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) && !(s->srp_ctx.srp_Mask & SSL_kSRP)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } #endif /* OPENSSL_NO_SRP */ p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if TLS v1.2: we may need them for * client authentication. */ if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s)) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (s->options & SSL_OP_NO_COMPRESSION) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (s->version >= SSL3_VERSION) { if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al)) { /* 'al' set by ssl_parse_serverhello_tlsext */ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto f_err; } if (ssl_check_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); goto err; } } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); }
165,022
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentLoader::DidInstallNewDocument(Document* document) { document->SetReadyState(Document::kLoading); document->InitContentSecurityPolicy(content_security_policy_.Release()); if (history_item_ && IsBackForwardLoadType(load_type_)) document->SetStateForNewFormElements(history_item_->GetDocumentState()); String suborigin_header = response_.HttpHeaderField(HTTPNames::Suborigin); if (!suborigin_header.IsNull()) { Vector<String> messages; Suborigin suborigin; if (ParseSuboriginHeader(suborigin_header, &suborigin, messages)) document->EnforceSuborigin(suborigin); for (auto& message : messages) { document->AddConsoleMessage( ConsoleMessage::Create(kSecurityMessageSource, kErrorMessageLevel, "Error with Suborigin header: " + message)); } } document->GetClientHintsPreferences().UpdateFrom(client_hints_preferences_); Settings* settings = document->GetSettings(); fetcher_->SetImagesEnabled(settings->GetImagesEnabled()); fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically()); const AtomicString& dns_prefetch_control = response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control); if (!dns_prefetch_control.IsEmpty()) document->ParseDNSPrefetchControlHeader(dns_prefetch_control); String header_content_language = response_.HttpHeaderField(HTTPNames::Content_Language); if (!header_content_language.IsEmpty()) { size_t comma_index = header_content_language.find(','); header_content_language.Truncate(comma_index); header_content_language = header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>); if (!header_content_language.IsEmpty()) document->SetContentLanguage(AtomicString(header_content_language)); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(HTTPNames::Origin_Trial)); String referrer_policy_header = response_.HttpHeaderField(HTTPNames::Referrer_Policy); if (!referrer_policy_header.IsNull()) { UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader); document->ParseAndSetReferrerPolicy(referrer_policy_header); } GetLocalFrameClient().DidCreateNewDocument(); } 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
void DocumentLoader::DidInstallNewDocument(Document* document) { void DocumentLoader::DidInstallNewDocument(Document* document, InstallNewDocumentReason reason) { document->SetReadyState(Document::kLoading); if (content_security_policy_) { document->InitContentSecurityPolicy(content_security_policy_.Release()); } if (history_item_ && IsBackForwardLoadType(load_type_)) document->SetStateForNewFormElements(history_item_->GetDocumentState()); String suborigin_header = response_.HttpHeaderField(HTTPNames::Suborigin); if (!suborigin_header.IsNull()) { Vector<String> messages; Suborigin suborigin; if (ParseSuboriginHeader(suborigin_header, &suborigin, messages)) document->EnforceSuborigin(suborigin); for (auto& message : messages) { document->AddConsoleMessage( ConsoleMessage::Create(kSecurityMessageSource, kErrorMessageLevel, "Error with Suborigin header: " + message)); } } document->GetClientHintsPreferences().UpdateFrom(client_hints_preferences_); Settings* settings = document->GetSettings(); fetcher_->SetImagesEnabled(settings->GetImagesEnabled()); fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically()); const AtomicString& dns_prefetch_control = response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control); if (!dns_prefetch_control.IsEmpty()) document->ParseDNSPrefetchControlHeader(dns_prefetch_control); String header_content_language = response_.HttpHeaderField(HTTPNames::Content_Language); if (!header_content_language.IsEmpty()) { size_t comma_index = header_content_language.find(','); header_content_language.Truncate(comma_index); header_content_language = header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>); if (!header_content_language.IsEmpty()) document->SetContentLanguage(AtomicString(header_content_language)); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(HTTPNames::Origin_Trial)); String referrer_policy_header = response_.HttpHeaderField(HTTPNames::Referrer_Policy); if (!referrer_policy_header.IsNull()) { UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader); document->ParseAndSetReferrerPolicy(referrer_policy_header); } GetLocalFrameClient().DidCreateNewDocument(); }
172,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Local<v8::Value> compileAndRunPrivateScript(ScriptState* scriptState, String scriptClassName, const char* source, size_t size) { v8::Isolate* isolate = scriptState->isolate(); v8::TryCatch block(isolate); String sourceString(source, size); String fileName = scriptClassName + ".js"; v8::Local<v8::Context> context = scriptState->context(); v8::Local<v8::Object> global = context->Global(); v8::Local<v8::Value> privateScriptController = global->Get(context, v8String(isolate, "privateScriptController")) .ToLocalChecked(); RELEASE_ASSERT(privateScriptController->IsUndefined() || privateScriptController->IsObject()); if (privateScriptController->IsObject()) { v8::Local<v8::Object> privateScriptControllerObject = privateScriptController.As<v8::Object>(); v8::Local<v8::Value> importFunctionValue = privateScriptControllerObject->Get(context, v8String(isolate, "import")) .ToLocalChecked(); if (importFunctionValue->IsUndefined()) { v8::Local<v8::Function> function; if (!v8::FunctionTemplate::New(isolate, importFunction) ->GetFunction(context) .ToLocal(&function) || !v8CallBoolean(privateScriptControllerObject->Set( context, v8String(isolate, "import"), function))) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: Setting import function failed. (Class " "name = " << scriptClassName.utf8().data() << ")"; } } } v8::Local<v8::Script> script; if (!v8Call(V8ScriptRunner::compileScript( v8String(isolate, sourceString), fileName, String(), TextPosition::minimumPosition(), isolate, nullptr, nullptr, nullptr, NotSharableCrossOrigin), script, block)) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: Compile failed. (Class name = " << scriptClassName.utf8().data() << ")"; } v8::Local<v8::Value> result; if (!v8Call(V8ScriptRunner::runCompiledInternalScript(isolate, script), result, block)) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: installClass() failed. (Class name = " << scriptClassName.utf8().data() << ")"; } return result; } Commit Message: Don't touch the prototype chain to get the private script controller. Prior to this patch, private scripts attempted to get the "privateScriptController" property off the global object without verifying if the property actually exists on the global. If the property hasn't been set yet, this operation could descend into the prototype chain and potentially return a named property from the WindowProperties object, leading to release asserts and general confusion. BUG=668552 Review-Url: https://codereview.chromium.org/2529163002 Cr-Commit-Position: refs/heads/master@{#434627} CWE ID: CWE-79
static v8::Local<v8::Value> compileAndRunPrivateScript(ScriptState* scriptState, String scriptClassName, const char* source, size_t size) { v8::Isolate* isolate = scriptState->isolate(); v8::TryCatch block(isolate); String sourceString(source, size); String fileName = scriptClassName + ".js"; v8::Local<v8::Context> context = scriptState->context(); v8::Local<v8::Object> global = context->Global(); v8::Local<v8::String> key = v8String(isolate, "privateScriptController"); if (global->HasOwnProperty(context, key).ToChecked()) { v8::Local<v8::Value> privateScriptController = global->Get(context, key).ToLocalChecked(); CHECK(privateScriptController->IsObject()); v8::Local<v8::Object> privateScriptControllerObject = privateScriptController.As<v8::Object>(); v8::Local<v8::Value> importFunctionValue = privateScriptControllerObject->Get(context, v8String(isolate, "import")) .ToLocalChecked(); if (importFunctionValue->IsUndefined()) { v8::Local<v8::Function> function; if (!v8::FunctionTemplate::New(isolate, importFunction) ->GetFunction(context) .ToLocal(&function) || !v8CallBoolean(privateScriptControllerObject->Set( context, v8String(isolate, "import"), function))) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: Setting import function failed. (Class " "name = " << scriptClassName.utf8().data() << ")"; } } } v8::Local<v8::Script> script; if (!v8Call(V8ScriptRunner::compileScript( v8String(isolate, sourceString), fileName, String(), TextPosition::minimumPosition(), isolate, nullptr, nullptr, nullptr, NotSharableCrossOrigin), script, block)) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: Compile failed. (Class name = " << scriptClassName.utf8().data() << ")"; } v8::Local<v8::Value> result; if (!v8Call(V8ScriptRunner::runCompiledInternalScript(isolate, script), result, block)) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: installClass() failed. (Class name = " << scriptClassName.utf8().data() << ")"; } return result; }
172,450
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MakeGroupObsolete() { PushNextTask( base::BindOnce(&AppCacheStorageImplTest::Verify_MakeGroupObsolete, base::Unretained(this))); MakeCacheAndGroup(kManifestUrl, 1, 1, true); EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]); AppCacheDatabase::EntryRecord entry_record; entry_record.cache_id = 1; entry_record.flags = AppCacheEntry::FALLBACK; entry_record.response_id = 1; entry_record.url = kEntryUrl; EXPECT_TRUE(database()->InsertEntry(&entry_record)); AppCacheDatabase::NamespaceRecord fallback_namespace_record; fallback_namespace_record.cache_id = 1; fallback_namespace_record.namespace_.target_url = kEntryUrl; fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace; fallback_namespace_record.origin = url::Origin::Create(kManifestUrl); EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record)); AppCacheDatabase::OnlineWhiteListRecord online_whitelist_record; online_whitelist_record.cache_id = 1; online_whitelist_record.namespace_url = kOnlineNamespace; EXPECT_TRUE(database()->InsertOnlineWhiteList(&online_whitelist_record)); storage()->MakeGroupObsolete(group_.get(), delegate(), 0); EXPECT_FALSE(group_->is_obsolete()); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void MakeGroupObsolete() { PushNextTask( base::BindOnce(&AppCacheStorageImplTest::Verify_MakeGroupObsolete, base::Unretained(this))); MakeCacheAndGroup(kManifestUrl, 1, 1, true); EXPECT_EQ(kDefaultEntrySize + kDefaultEntryPadding, storage()->usage_map_[kOrigin]); AppCacheDatabase::EntryRecord entry_record; entry_record.cache_id = 1; entry_record.flags = AppCacheEntry::FALLBACK; entry_record.response_id = 1; entry_record.url = kEntryUrl; EXPECT_TRUE(database()->InsertEntry(&entry_record)); AppCacheDatabase::NamespaceRecord fallback_namespace_record; fallback_namespace_record.cache_id = 1; fallback_namespace_record.namespace_.target_url = kEntryUrl; fallback_namespace_record.namespace_.namespace_url = kFallbackNamespace; fallback_namespace_record.origin = url::Origin::Create(kManifestUrl); EXPECT_TRUE(database()->InsertNamespace(&fallback_namespace_record)); AppCacheDatabase::OnlineWhiteListRecord online_whitelist_record; online_whitelist_record.cache_id = 1; online_whitelist_record.namespace_url = kOnlineNamespace; EXPECT_TRUE(database()->InsertOnlineWhiteList(&online_whitelist_record)); storage()->MakeGroupObsolete(group_.get(), delegate(), 0); EXPECT_FALSE(group_->is_obsolete()); }
172,987
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebSocketJob::SendDataInternal(const char* data, int length) { if (spdy_websocket_stream_.get()) return ERR_IO_PENDING == spdy_websocket_stream_->SendData(data, length); return socket_->SendData(data, length); } Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob Don't post SendPending if it is already posted. BUG=89795 TEST=none Review URL: http://codereview.chromium.org/7488007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool WebSocketJob::SendDataInternal(const char* data, int length) { if (spdy_websocket_stream_.get()) return ERR_IO_PENDING == spdy_websocket_stream_->SendData(data, length); if (socket_.get()) return socket_->SendData(data, length); return false; }
170,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void bpf_int_jit_compile(struct bpf_prog *prog) { struct bpf_binary_header *header = NULL; int proglen, oldproglen = 0; struct jit_context ctx = {}; u8 *image = NULL; int *addrs; int pass; int i; if (!bpf_jit_enable) return; if (!prog || !prog->len) return; addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL); if (!addrs) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < prog->len; i++) { proglen += 64; addrs[i] = proglen; } ctx.cleanup_addr = proglen; for (pass = 0; pass < 10; pass++) { proglen = do_jit(prog, addrs, image, oldproglen, &ctx); if (proglen <= 0) { image = NULL; if (header) bpf_jit_binary_free(header); goto out; } if (image) { if (proglen != oldproglen) { pr_err("bpf_jit: proglen=%d != oldproglen=%d\n", proglen, oldproglen); goto out; } break; } if (proglen == oldproglen) { header = bpf_jit_binary_alloc(proglen, &image, 1, jit_fill_hole); if (!header) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) bpf_jit_dump(prog->len, proglen, 0, image); if (image) { bpf_flush_icache(header, image + proglen); set_memory_ro((unsigned long)header, header->pages); prog->bpf_func = (void *)image; prog->jited = true; } out: kfree(addrs); } Commit Message: x86: bpf_jit: fix compilation of large bpf programs x86 has variable length encoding. x86 JIT compiler is trying to pick the shortest encoding for given bpf instruction. While doing so the jump targets are changing, so JIT is doing multiple passes over the program. Typical program needs 3 passes. Some very short programs converge with 2 passes. Large programs may need 4 or 5. But specially crafted bpf programs may hit the pass limit and if the program converges on the last iteration the JIT compiler will be producing an image full of 'int 3' insns. Fix this corner case by doing final iteration over bpf program. Fixes: 0a14842f5a3c ("net: filter: Just In Time compiler for x86-64") Reported-by: Daniel Borkmann <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Tested-by: Daniel Borkmann <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-17
void bpf_int_jit_compile(struct bpf_prog *prog) { struct bpf_binary_header *header = NULL; int proglen, oldproglen = 0; struct jit_context ctx = {}; u8 *image = NULL; int *addrs; int pass; int i; if (!bpf_jit_enable) return; if (!prog || !prog->len) return; addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL); if (!addrs) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < prog->len; i++) { proglen += 64; addrs[i] = proglen; } ctx.cleanup_addr = proglen; /* JITed image shrinks with every pass and the loop iterates * until the image stops shrinking. Very large bpf programs * may converge on the last pass. In such case do one more * pass to emit the final image */ for (pass = 0; pass < 10 || image; pass++) { proglen = do_jit(prog, addrs, image, oldproglen, &ctx); if (proglen <= 0) { image = NULL; if (header) bpf_jit_binary_free(header); goto out; } if (image) { if (proglen != oldproglen) { pr_err("bpf_jit: proglen=%d != oldproglen=%d\n", proglen, oldproglen); goto out; } break; } if (proglen == oldproglen) { header = bpf_jit_binary_alloc(proglen, &image, 1, jit_fill_hole); if (!header) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) bpf_jit_dump(prog->len, proglen, 0, image); if (image) { bpf_flush_icache(header, image + proglen); set_memory_ro((unsigned long)header, header->pages); prog->bpf_func = (void *)image; prog->jited = true; } out: kfree(addrs); }
166,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers( extensions::Dispatcher* dispatcher, extensions::ModuleSystem* module_system, extensions::ScriptContext* context) { module_system->RegisterNativeHandler( "app", std::unique_ptr<NativeHandler>( new extensions::AppBindings(dispatcher, context))); module_system->RegisterNativeHandler( "sync_file_system", std::unique_ptr<NativeHandler>( new extensions::SyncFileSystemCustomBindings(context))); module_system->RegisterNativeHandler( "file_browser_handler", std::unique_ptr<NativeHandler>( new extensions::FileBrowserHandlerCustomBindings(context))); module_system->RegisterNativeHandler( "file_manager_private", std::unique_ptr<NativeHandler>( new extensions::FileManagerPrivateCustomBindings(context))); module_system->RegisterNativeHandler( "notifications_private", std::unique_ptr<NativeHandler>( new extensions::NotificationsNativeHandler(context))); module_system->RegisterNativeHandler( "mediaGalleries", std::unique_ptr<NativeHandler>( new extensions::MediaGalleriesCustomBindings(context))); module_system->RegisterNativeHandler( "page_capture", std::unique_ptr<NativeHandler>( new extensions::PageCaptureCustomBindings(context))); module_system->RegisterNativeHandler( "platform_keys_natives", std::unique_ptr<NativeHandler>( new extensions::PlatformKeysNatives(context))); module_system->RegisterNativeHandler( "tabs", std::unique_ptr<NativeHandler>( new extensions::TabsCustomBindings(context))); module_system->RegisterNativeHandler( "webstore", std::unique_ptr<NativeHandler>( new extensions::WebstoreBindings(context))); #if defined(ENABLE_WEBRTC) module_system->RegisterNativeHandler( "cast_streaming_natives", std::unique_ptr<NativeHandler>( new extensions::CastStreamingNativeHandler(context))); #endif module_system->RegisterNativeHandler( "automationInternal", std::unique_ptr<NativeHandler>( new extensions::AutomationInternalCustomBindings(context))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers( extensions::Dispatcher* dispatcher, extensions::ModuleSystem* module_system, extensions::ScriptContext* context) { module_system->RegisterNativeHandler( "app", std::unique_ptr<NativeHandler>( new extensions::AppBindings(dispatcher, context))); module_system->RegisterNativeHandler( "sync_file_system", std::unique_ptr<NativeHandler>( new extensions::SyncFileSystemCustomBindings(context))); module_system->RegisterNativeHandler( "file_browser_handler", std::unique_ptr<NativeHandler>( new extensions::FileBrowserHandlerCustomBindings(context))); module_system->RegisterNativeHandler( "file_manager_private", std::unique_ptr<NativeHandler>( new extensions::FileManagerPrivateCustomBindings(context))); module_system->RegisterNativeHandler( "notifications_private", std::unique_ptr<NativeHandler>( new extensions::NotificationsNativeHandler(context))); module_system->RegisterNativeHandler( "mediaGalleries", std::unique_ptr<NativeHandler>( new extensions::MediaGalleriesCustomBindings(context))); module_system->RegisterNativeHandler( "page_capture", std::unique_ptr<NativeHandler>( new extensions::PageCaptureCustomBindings(context))); module_system->RegisterNativeHandler( "platform_keys_natives", std::unique_ptr<NativeHandler>( new extensions::PlatformKeysNatives(context))); module_system->RegisterNativeHandler( "tabs", std::unique_ptr<NativeHandler>( new extensions::TabsCustomBindings(context))); module_system->RegisterNativeHandler( "webstore", std::unique_ptr<NativeHandler>( new extensions::WebstoreBindings(context))); #if defined(ENABLE_WEBRTC) module_system->RegisterNativeHandler( "cast_streaming_natives", std::unique_ptr<NativeHandler>( new extensions::CastStreamingNativeHandler(context))); #endif module_system->RegisterNativeHandler( "automationInternal", std::unique_ptr<NativeHandler>( new extensions::AutomationInternalCustomBindings(context))); // The following are native handlers that are defined in //extensions, but // are only used for APIs defined in Chrome. // TODO(devlin): We should clean this up. If an API is defined in Chrome, // there's no reason to have its native handlers residing and being compiled // in //extensions. module_system->RegisterNativeHandler( "i18n", scoped_ptr<NativeHandler>(new extensions::I18NCustomBindings(context))); module_system->RegisterNativeHandler( "lazy_background_page", scoped_ptr<NativeHandler>( new extensions::LazyBackgroundPageNativeHandler(context))); }
172,243
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ int j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: memcpy(file->name, d, len); file->namelen = len; break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ size_t j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: file->namelen = MIN(sizeof file->name, len); memcpy(file->name, d, file->namelen); break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; }
169,075
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace) { if (paintingDisabled()) return; notImplemented(); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace) { if (paintingDisabled()) return; #if USE(WXGC) Path path; path.addRoundedRect(rect, topLeft, topRight, bottomLeft, bottomRight); m_data->context->SetBrush(wxBrush(color)); wxGraphicsContext* gc = m_data->context->GetGraphicsContext(); gc->FillPath(*path.platformPath()); #endif }
170,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseEntityRef(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr ent = NULL; GROW; if (RAW != '&') return(NULL); NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseEntityRef: no name\n"); return(NULL); } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return(NULL); } NEXT; /* * Predefined entites override any extra definition */ if ((ctxt->options & XML_PARSE_OLDSAX) == 0) { ent = xmlGetPredefinedEntity(name); if (ent != NULL) return(ent); } /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Ask first SAX for entity resolution, otherwise try the * entities which may have stored in the parser context. */ if (ctxt->sax != NULL) { if (ctxt->sax->getEntity != NULL) ent = ctxt->sax->getEntity(ctxt->userData, name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX)) ent = xmlGetPredefinedEntity(name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->userData==ctxt)) { ent = xmlSAX2GetEntity(ctxt, name); } } /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", the * Name given in the entity reference must match that in an * entity declaration, except that well-formed documents * need not declare any of the following entities: amp, lt, * gt, apos, quot. * The declaration of a parameter entity must precede any * reference to it. * Similarly, the declaration of a general entity must * precede any reference to it which appears in a default * value in an attribute-list declaration. Note that if * entities are declared in the external subset or in * external parameter entities, a non-validating processor * is not obligated to read and process their declarations; * for such documents, the rule that an entity must be * declared is a well-formedness constraint only if * standalone='yes'. */ if (ent == NULL) { if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } else { xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); if ((ctxt->inSubset == 0) && (ctxt->sax != NULL) && (ctxt->sax->reference != NULL)) { ctxt->sax->reference(ctxt->userData, name); } } ctxt->valid = 0; } /* * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an * unparsed entity */ else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY, "Entity reference to unparsed entity %s\n", name); } /* * [ WFC: No External Entity References ] * Attribute values cannot contain direct or indirect * entity references to external entities. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL, "Attribute references external entity '%s'\n", name); } /* * [ WFC: No < in Attribute Values ] * The replacement text of any entity referred to directly or * indirectly in an attribute value (other than "&lt;") must * not contain a <. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent != NULL) && (ent->content != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (xmlStrchr(ent->content, '<'))) { xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, "'<' in entity '%s' is not allowed in attributes values\n", name); } /* * Internal check, no parameter entities here ... */ else { switch (ent->etype) { case XML_INTERNAL_PARAMETER_ENTITY: case XML_EXTERNAL_PARAMETER_ENTITY: xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "Attempt to reference the parameter entity '%s'\n", name); break; default: break; } } /* * [ WFC: No Recursion ] * A parsed entity must not contain a recursive reference * to itself, either directly or indirectly. * Done somewhere else */ return(ent); } 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
xmlParseEntityRef(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr ent = NULL; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); if (RAW != '&') return(NULL); NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseEntityRef: no name\n"); return(NULL); } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return(NULL); } NEXT; /* * Predefined entites override any extra definition */ if ((ctxt->options & XML_PARSE_OLDSAX) == 0) { ent = xmlGetPredefinedEntity(name); if (ent != NULL) return(ent); } /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Ask first SAX for entity resolution, otherwise try the * entities which may have stored in the parser context. */ if (ctxt->sax != NULL) { if (ctxt->sax->getEntity != NULL) ent = ctxt->sax->getEntity(ctxt->userData, name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX)) ent = xmlGetPredefinedEntity(name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->userData==ctxt)) { ent = xmlSAX2GetEntity(ctxt, name); } } if (ctxt->instate == XML_PARSER_EOF) return(NULL); /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", the * Name given in the entity reference must match that in an * entity declaration, except that well-formed documents * need not declare any of the following entities: amp, lt, * gt, apos, quot. * The declaration of a parameter entity must precede any * reference to it. * Similarly, the declaration of a general entity must * precede any reference to it which appears in a default * value in an attribute-list declaration. Note that if * entities are declared in the external subset or in * external parameter entities, a non-validating processor * is not obligated to read and process their declarations; * for such documents, the rule that an entity must be * declared is a well-formedness constraint only if * standalone='yes'. */ if (ent == NULL) { if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } else { xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); if ((ctxt->inSubset == 0) && (ctxt->sax != NULL) && (ctxt->sax->reference != NULL)) { ctxt->sax->reference(ctxt->userData, name); } } ctxt->valid = 0; } /* * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an * unparsed entity */ else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY, "Entity reference to unparsed entity %s\n", name); } /* * [ WFC: No External Entity References ] * Attribute values cannot contain direct or indirect * entity references to external entities. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL, "Attribute references external entity '%s'\n", name); } /* * [ WFC: No < in Attribute Values ] * The replacement text of any entity referred to directly or * indirectly in an attribute value (other than "&lt;") must * not contain a <. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent != NULL) && (ent->content != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (xmlStrchr(ent->content, '<'))) { xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, "'<' in entity '%s' is not allowed in attributes values\n", name); } /* * Internal check, no parameter entities here ... */ else { switch (ent->etype) { case XML_INTERNAL_PARAMETER_ENTITY: case XML_EXTERNAL_PARAMETER_ENTITY: xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "Attempt to reference the parameter entity '%s'\n", name); break; default: break; } } /* * [ WFC: No Recursion ] * A parsed entity must not contain a recursive reference * to itself, either directly or indirectly. * Done somewhere else */ return(ent); }
171,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pcf_read_TOC( FT_Stream stream, PCF_Face face ) { FT_Error error; PCF_Toc toc = &face->toc; PCF_Table tables; FT_Memory memory = FT_FACE( face )->memory; FT_UInt n; if ( FT_STREAM_SEEK ( 0 ) || FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) ) return FT_THROW( Cannot_Open_Resource ); if ( toc->version != PCF_FILE_VERSION || toc->count > FT_ARRAY_MAX( face->toc.tables ) || toc->count == 0 ) return FT_THROW( Invalid_File_Format ); if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) ) return FT_THROW( Out_Of_Memory ); tables = face->toc.tables; for ( n = 0; n < toc->count; n++ ) { if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) ) goto Exit; tables++; } /* Sort tables and check for overlaps. Because they are almost */ /* always ordered already, an in-place bubble sort with simultaneous */ /* boundary checking seems appropriate. */ tables = face->toc.tables; for ( n = 0; n < toc->count - 1; n++ ) { FT_UInt i, have_change; have_change = 0; for ( i = 0; i < toc->count - 1 - n; i++ ) { PCF_TableRec tmp; if ( tables[i].offset > tables[i + 1].offset ) { tmp = tables[i]; tables[i] = tables[i + 1]; tables[i + 1] = tmp; have_change = 1; } if ( ( tables[i].size > tables[i + 1].offset ) || ( tables[i].offset > tables[i + 1].offset - tables[i].size ) ) { error = FT_THROW( Invalid_Offset ); goto Exit; } } if ( !have_change ) break; } #ifdef FT_DEBUG_LEVEL_TRACE { FT_TRACE4(( " %d: type=%s, format=0x%X, " "size=%ld (0x%lX), offset=%ld (0x%lX)\n", i, name, tables[i].format, tables[i].size, tables[i].size, tables[i].offset, tables[i].offset )); } } Commit Message: CWE ID:
pcf_read_TOC( FT_Stream stream, PCF_Face face ) { FT_Error error; PCF_Toc toc = &face->toc; PCF_Table tables; FT_Memory memory = FT_FACE( face )->memory; FT_UInt n; if ( FT_STREAM_SEEK ( 0 ) || FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) ) return FT_THROW( Cannot_Open_Resource ); if ( toc->version != PCF_FILE_VERSION || toc->count > FT_ARRAY_MAX( face->toc.tables ) || toc->count == 0 ) return FT_THROW( Invalid_File_Format ); if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) ) return FT_THROW( Out_Of_Memory ); tables = face->toc.tables; for ( n = 0; n < toc->count; n++ ) { if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) ) goto Exit; tables++; } /* Sort tables and check for overlaps. Because they are almost */ /* always ordered already, an in-place bubble sort with simultaneous */ /* boundary checking seems appropriate. */ tables = face->toc.tables; for ( n = 0; n < toc->count - 1; n++ ) { FT_UInt i, have_change; have_change = 0; for ( i = 0; i < toc->count - 1 - n; i++ ) { PCF_TableRec tmp; if ( tables[i].offset > tables[i + 1].offset ) { tmp = tables[i]; tables[i] = tables[i + 1]; tables[i + 1] = tmp; have_change = 1; } if ( ( tables[i].size > tables[i + 1].offset ) || ( tables[i].offset > tables[i + 1].offset - tables[i].size ) ) { error = FT_THROW( Invalid_Offset ); goto Exit; } } if ( !have_change ) break; } /* we now check whether the `size' and `offset' values are reasonable: */ /* `offset' + `size' must not exceed the stream size */ tables = face->toc.tables; for ( n = 0; n < toc->count; n++ ) { /* we need two checks to avoid overflow */ if ( ( tables->size > stream->size ) || ( tables->offset > stream->size - tables->size ) ) { error = FT_THROW( Invalid_Table ); goto Exit; } tables++; } #ifdef FT_DEBUG_LEVEL_TRACE { FT_TRACE4(( " %d: type=%s, format=0x%X, " "size=%ld (0x%lX), offset=%ld (0x%lX)\n", i, name, tables[i].format, tables[i].size, tables[i].size, tables[i].offset, tables[i].offset )); } }
164,843
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void scsi_read_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->sector_count == (uint32_t)-1) { DPRINTF("Read buf_len=%zd\n", r->iov.iov_len); r->sector_count = 0; scsi_req_data(&r->req, r->iov.iov_len); return; } DPRINTF("Read sector_count=%d\n", r->sector_count); if (r->sector_count == 0) { /* This also clears the sense buffer for REQUEST SENSE. */ scsi_req_complete(&r->req, GOOD); return; } /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_read_complete(r, -EINVAL); return; } n = r->sector_count; if (n > SCSI_DMA_BUF_SIZE / 512) n = SCSI_DMA_BUF_SIZE / 512; if (s->tray_open) { scsi_read_complete(r, -ENOMEDIUM); } r->iov.iov_len = n * 512; qemu_iovec_init_external(&r->qiov, &r->iov, 1); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n, scsi_read_complete, r); if (r->req.aiocb == NULL) { scsi_read_complete(r, -EIO); } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static void scsi_read_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->sector_count == (uint32_t)-1) { DPRINTF("Read buf_len=%zd\n", r->iov.iov_len); r->sector_count = 0; scsi_req_data(&r->req, r->iov.iov_len); return; } DPRINTF("Read sector_count=%d\n", r->sector_count); if (r->sector_count == 0) { /* This also clears the sense buffer for REQUEST SENSE. */ scsi_req_complete(&r->req, GOOD); return; } /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_read_complete(r, -EINVAL); return; } if (s->tray_open) { scsi_read_complete(r, -ENOMEDIUM); } n = scsi_init_iovec(r); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n, scsi_read_complete, r); if (r->req.aiocb == NULL) { scsi_read_complete(r, -EIO); } }
169,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual InputMethodDescriptor current_input_method() const { if (current_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return current_input_method_; } 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
virtual InputMethodDescriptor current_input_method() const { virtual input_method::InputMethodDescriptor current_input_method() const { if (current_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return current_input_method_; }
170,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { bool ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); return true; }
173,251
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree, guint8 *drep _U_, char **data, int hf_name) { gint len, remaining; char *text; if (offset % 2) offset += 2 - (offset % 2); /* Get remaining data in buffer as a string */ remaining = tvb_captured_length_remaining(tvb, offset); if (remaining <= 0) { if (data) *data = g_strdup(""); return offset; } text = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN); len = (int)strlen(text); proto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text); if (data) *data = text; else g_free(text); return offset + (len + 1) * 2; } Commit Message: SPOOLSS: Try to avoid an infinite loop. Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make sure our offset always increments in dissect_spoolss_keybuffer. Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793 Reviewed-on: https://code.wireshark.org/review/14687 Reviewed-by: Gerald Combs <[email protected]> Petri-Dish: Gerald Combs <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]> CWE ID: CWE-399
dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree, guint8 *drep _U_, char **data, int hf_name) { gint len, remaining; char *text; if (offset % 2) offset += 2 - (offset % 2); /* Get remaining data in buffer as a string */ remaining = tvb_reported_length_remaining(tvb, offset); if (remaining <= 0) { if (data) *data = g_strdup(""); return offset; } text = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN); len = (int)strlen(text); proto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text); if (data) *data = text; else g_free(text); return offset + (len + 1) * 2; }
167,160
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: videobuf_vm_close(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; struct videobuf_queue *q = map->q; int i; dprintk(2,"vm_close %p [count=%d,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count--; if (0 == map->count) { dprintk(1,"munmap %p q=%p\n",map,q); mutex_lock(&q->lock); for (i = 0; i < VIDEO_MAX_FRAME; i++) { if (NULL == q->bufs[i]) continue; if (q->bufs[i]->map != map) continue; q->ops->buf_release(q,q->bufs[i]); q->bufs[i]->map = NULL; q->bufs[i]->baddr = 0; } mutex_unlock(&q->lock); kfree(map); } return; } Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap This is pretty serious bug. map->count is never initialized after the call to kmalloc making the count start at some random trash value. The end result is leaking videobufs. Also, fix up the debug statements to print unsigned values. Pushed to http://ifup.org/hg/v4l-dvb too Signed-off-by: Brandon Philips <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
videobuf_vm_close(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; struct videobuf_queue *q = map->q; int i; dprintk(2,"vm_close %p [count=%u,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count--; if (0 == map->count) { dprintk(1,"munmap %p q=%p\n",map,q); mutex_lock(&q->lock); for (i = 0; i < VIDEO_MAX_FRAME; i++) { if (NULL == q->bufs[i]) continue; if (q->bufs[i]->map != map) continue; q->ops->buf_release(q,q->bufs[i]); q->bufs[i]->map = NULL; q->bufs[i]->baddr = 0; } mutex_unlock(&q->lock); kfree(map); } return; }
168,918
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: P2PQuicStreamImpl* P2PQuicTransportImpl::CreateStreamInternal( quic::QuicStreamId id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(crypto_stream_); DCHECK(IsEncryptionEstablished()); DCHECK(!IsClosed()); return new P2PQuicStreamImpl(id, this); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
P2PQuicStreamImpl* P2PQuicTransportImpl::CreateStreamInternal( quic::QuicStreamId id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(crypto_stream_); DCHECK(IsEncryptionEstablished()); DCHECK(!IsClosed()); return new P2PQuicStreamImpl(id, this, stream_write_buffer_size_); }
172,265
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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
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; ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); return OK; }
174,165
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DoTouchScroll(const gfx::Point& point, const gfx::Vector2d& distance, bool wait_until_scrolled) { EXPECT_EQ(0, GetScrollTop()); int scrollHeight = ExecuteScriptAndExtractInt( "document.documentElement.scrollHeight"); EXPECT_EQ(1200, scrollHeight); scoped_refptr<FrameWatcher> frame_watcher(new FrameWatcher()); frame_watcher->AttachTo(shell()->web_contents()); SyntheticSmoothScrollGestureParams params; params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; params.anchor = gfx::PointF(point); params.distances.push_back(-distance); runner_ = new MessageLoopRunner(); std::unique_ptr<SyntheticSmoothScrollGesture> gesture( new SyntheticSmoothScrollGesture(params)); GetWidgetHost()->QueueSyntheticGesture( std::move(gesture), base::Bind(&TouchActionBrowserTest::OnSyntheticGestureCompleted, base::Unretained(this))); runner_->Run(); runner_ = NULL; while (wait_until_scrolled && frame_watcher->LastMetadata().root_scroll_offset.y() <= 0) { frame_watcher->WaitFrames(1); } int scrollTop = GetScrollTop(); if (scrollTop == 0) return false; EXPECT_EQ(distance.y(), scrollTop); return true; } Commit Message: Drive out additional flakiness of TouchAction browser test. It is relatively stable but it has flaked a couple of times specifically with this: Actual: 44 Expected: distance.y() Which is: 45 I presume that the failure is either we aren't waiting for the additional frame or a subpixel scrolling problem. As a speculative fix wait for the pixel item we are waiting to scroll for. BUG=376668 Review-Url: https://codereview.chromium.org/2281613002 Cr-Commit-Position: refs/heads/master@{#414525} CWE ID: CWE-119
bool DoTouchScroll(const gfx::Point& point, const gfx::Vector2d& distance, bool wait_until_scrolled) { EXPECT_EQ(0, GetScrollTop()); int scrollHeight = ExecuteScriptAndExtractInt( "document.documentElement.scrollHeight"); EXPECT_EQ(1200, scrollHeight); scoped_refptr<FrameWatcher> frame_watcher(new FrameWatcher()); frame_watcher->AttachTo(shell()->web_contents()); SyntheticSmoothScrollGestureParams params; params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; params.anchor = gfx::PointF(point); params.distances.push_back(-distance); runner_ = new MessageLoopRunner(); std::unique_ptr<SyntheticSmoothScrollGesture> gesture( new SyntheticSmoothScrollGesture(params)); GetWidgetHost()->QueueSyntheticGesture( std::move(gesture), base::Bind(&TouchActionBrowserTest::OnSyntheticGestureCompleted, base::Unretained(this))); runner_->Run(); runner_ = NULL; while (wait_until_scrolled && frame_watcher->LastMetadata().root_scroll_offset.y() < distance.y()) { frame_watcher->WaitFrames(1); } int scrollTop = GetScrollTop(); if (scrollTop == 0) return false; EXPECT_EQ(distance.y(), scrollTop); return true; }
171,600
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int uio_mmap_physical(struct vm_area_struct *vma) { struct uio_device *idev = vma->vm_private_data; int mi = uio_find_mem_index(vma); if (mi < 0) return -EINVAL; vma->vm_ops = &uio_physical_vm_ops; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); return remap_pfn_range(vma, vma->vm_start, idev->info->mem[mi].addr >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); } Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that really should use the vm_iomap_memory() helper. This trivially converts two of them to the helper, and comments about why the third one really needs to continue to use remap_pfn_range(), and adds the missing size check. Reported-by: Nico Golde <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]. CWE ID: CWE-119
static int uio_mmap_physical(struct vm_area_struct *vma) { struct uio_device *idev = vma->vm_private_data; int mi = uio_find_mem_index(vma); struct uio_mem *mem; if (mi < 0) return -EINVAL; mem = idev->info->mem + mi; if (vma->vm_end - vma->vm_start > mem->size) return -EINVAL; vma->vm_ops = &uio_physical_vm_ops; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); /* * We cannot use the vm_iomap_memory() helper here, * because vma->vm_pgoff is the map index we looked * up above in uio_find_mem_index(), rather than an * actual page offset into the mmap. * * So we just do the physical mmap without a page * offset. */ return remap_pfn_range(vma, vma->vm_start, mem->addr >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); }
165,934
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ static char base_address; xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)&base_address); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ static char base_address; xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)&base_address); if (val >= 0) { snprintf((char *)str, sizeof(str), "idp%ld", val); } else { snprintf((char *)str, sizeof(str), "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); }
173,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: flac_buffer_copy (SF_PRIVATE *psf) { FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ; const FLAC__Frame *frame = pflac->frame ; const int32_t* const *buffer = pflac->wbuffer ; unsigned i = 0, j, offset, channels, len ; /* ** frame->header.blocksize is variable and we're using a constant blocksize ** of FLAC__MAX_BLOCK_SIZE. ** Check our assumptions here. */ if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE) { psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ; psf->error = SFE_INTERNAL ; return 0 ; } ; if (frame->header.channels > FLAC__MAX_CHANNELS) psf_log_printf (psf, "Ooops : frame->header.channels (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.channels, FLAC__MAX_CHANNELS) ; channels = SF_MIN (frame->header.channels, FLAC__MAX_CHANNELS) ; if (pflac->ptr == NULL) { /* ** Not sure why this code is here and not elsewhere. ** Removing it causes valgrind errors. */ pflac->bufferbackup = SF_TRUE ; for (i = 0 ; i < channels ; i++) { if (pflac->rbuffer [i] == NULL) pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ; memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (int32_t)) ; } ; pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ; return 0 ; } ; len = SF_MIN (pflac->len, frame->header.blocksize) ; switch (pflac->pcmtype) { case PFLAC_PCM_SHORT : { short *retpcm = (short*) pflac->ptr ; int shift = 16 - frame->header.bits_per_sample ; if (shift < 0) { shift = abs (shift) ; for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ; pflac->remain -= channels ; pflac->bufferpos++ ; } } else { for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ; pflac->remain -= channels ; pflac->bufferpos++ ; } ; } ; } ; break ; case PFLAC_PCM_INT : { int *retpcm = (int*) pflac->ptr ; int shift = 32 - frame->header.bits_per_sample ; for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ; pflac->remain -= channels ; pflac->bufferpos++ ; } ; } ; break ; case PFLAC_PCM_FLOAT : { float *retpcm = (float*) pflac->ptr ; float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ; for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ; pflac->remain -= channels ; pflac->bufferpos++ ; } ; } ; break ; case PFLAC_PCM_DOUBLE : { double *retpcm = (double*) pflac->ptr ; double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ; for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ; pflac->remain -= channels ; pflac->bufferpos++ ; } ; } ; break ; default : return 0 ; } ; offset = i * channels ; pflac->pos += i * channels ; return offset ; } /* flac_buffer_copy */ Commit Message: src/flac.c: Improve error handling Especially when dealing with corrupt or malicious files. CWE ID: CWE-119
flac_buffer_copy (SF_PRIVATE *psf) { FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ; const FLAC__Frame *frame = pflac->frame ; const int32_t* const *buffer = pflac->wbuffer ; unsigned i = 0, j, offset, channels, len ; /* ** frame->header.blocksize is variable and we're using a constant blocksize ** of FLAC__MAX_BLOCK_SIZE. ** Check our assumptions here. */ if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE) { psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ; psf->error = SFE_INTERNAL ; return 0 ; } ; if (frame->header.channels > FLAC__MAX_CHANNELS) psf_log_printf (psf, "Ooops : frame->header.channels (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.channels, FLAC__MAX_CHANNELS) ; channels = SF_MIN (frame->header.channels, FLAC__MAX_CHANNELS) ; if (pflac->ptr == NULL) { /* ** This pointer is reset to NULL each time the current frame has been ** decoded. Somehow its used during encoding and decoding. */ for (i = 0 ; i < channels ; i++) { if (pflac->rbuffer [i] == NULL) pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ; memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (int32_t)) ; } ; pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ; return 0 ; } ; len = SF_MIN (pflac->len, frame->header.blocksize) ; if (pflac->remain % channels != 0) { psf_log_printf (psf, "Error: pflac->remain %u channels %u\n", pflac->remain, channels) ; return 0 ; } ; switch (pflac->pcmtype) { case PFLAC_PCM_SHORT : { short *retpcm = (short*) pflac->ptr ; int shift = 16 - frame->header.bits_per_sample ; if (shift < 0) { shift = abs (shift) ; for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ; pflac->remain -= channels ; pflac->bufferpos++ ; } } else { for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ; pflac->remain -= channels ; pflac->bufferpos++ ; } ; } ; } ; break ; case PFLAC_PCM_INT : { int *retpcm = (int*) pflac->ptr ; int shift = 32 - frame->header.bits_per_sample ; for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ; pflac->remain -= channels ; pflac->bufferpos++ ; } ; } ; break ; case PFLAC_PCM_FLOAT : { float *retpcm = (float*) pflac->ptr ; float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ; for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ; pflac->remain -= channels ; pflac->bufferpos++ ; } ; } ; break ; case PFLAC_PCM_DOUBLE : { double *retpcm = (double*) pflac->ptr ; double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ; for (i = 0 ; i < len && pflac->remain > 0 ; i++) { offset = pflac->pos + i * channels ; if (pflac->bufferpos >= frame->header.blocksize) break ; if (offset + channels > pflac->len) break ; for (j = 0 ; j < channels ; j++) retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ; pflac->remain -= channels ; pflac->bufferpos++ ; } ; } ; break ; default : return 0 ; } ; offset = i * channels ; pflac->pos += i * channels ; return offset ; } /* flac_buffer_copy */
168,254
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::AcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params_in_pixel, int gpu_host_id) { surface_route_id_ = params_in_pixel.route_id; if (params_in_pixel.protection_state_id && params_in_pixel.protection_state_id != protection_state_id_) { DCHECK(!current_surface_); InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL); return; } if (ShouldFastACK(params_in_pixel.surface_handle)) { InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL); return; } current_surface_ = params_in_pixel.surface_handle; released_front_lock_ = NULL; DCHECK(current_surface_); UpdateExternalTexture(); ui::Compositor* compositor = GetCompositor(); if (!compositor) { InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, true, NULL); } else { DCHECK(image_transport_clients_.find(params_in_pixel.surface_handle) != image_transport_clients_.end()); gfx::Size surface_size_in_pixel = image_transport_clients_[params_in_pixel.surface_handle]->size(); gfx::Rect rect_to_paint = ConvertRectToDIP(this, gfx::Rect( params_in_pixel.x, surface_size_in_pixel.height() - params_in_pixel.y - params_in_pixel.height, params_in_pixel.width, params_in_pixel.height)); rect_to_paint.Inset(-1, -1); rect_to_paint.Intersect(window_->bounds()); window_->SchedulePaintInRect(rect_to_paint); can_lock_compositor_ = NO_PENDING_COMMIT; on_compositing_did_commit_callbacks_.push_back( base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK, params_in_pixel.route_id, gpu_host_id, true)); if (!compositor->HasObserver(this)) compositor->AddObserver(this); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::AcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params_in_pixel, int gpu_host_id) { const gfx::Rect surface_rect = gfx::Rect(gfx::Point(), params_in_pixel.surface_size); gfx::Rect damage_rect(params_in_pixel.x, params_in_pixel.y, params_in_pixel.width, params_in_pixel.height); BufferPresentedParams ack_params( params_in_pixel.route_id, gpu_host_id, params_in_pixel.surface_handle); if (!SwapBuffersPrepare(surface_rect, damage_rect, &ack_params)) return; SkRegion damage(RectToSkIRect(damage_rect)); if (!skipped_damage_.isEmpty()) { damage.op(skipped_damage_, SkRegion::kUnion_Op); skipped_damage_.setEmpty(); } DCHECK(surface_rect.Contains(SkIRectToRect(damage.getBounds()))); ui::Texture* current_texture = image_transport_clients_[current_surface_]; const gfx::Size surface_size_in_pixel = params_in_pixel.surface_size; DLOG_IF(ERROR, ack_params.texture_to_produce && ack_params.texture_to_produce->size() != current_texture->size() && SkIRectToRect(damage.getBounds()) != surface_rect) << "Expected full damage rect after size change"; if (ack_params.texture_to_produce && !previous_damage_.isEmpty() && ack_params.texture_to_produce->size() == current_texture->size()) { ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); GLHelper* gl_helper = factory->GetGLHelper(); gl_helper->CopySubBufferDamage( current_texture->PrepareTexture(), ack_params.texture_to_produce->PrepareTexture(), damage, previous_damage_); } previous_damage_ = damage; ui::Compositor* compositor = GetCompositor(); if (compositor) { gfx::Rect rect_to_paint = ConvertRectToDIP(this, gfx::Rect( params_in_pixel.x, surface_size_in_pixel.height() - params_in_pixel.y - params_in_pixel.height, params_in_pixel.width, params_in_pixel.height)); rect_to_paint.Inset(-1, -1); rect_to_paint.Intersect(window_->bounds()); window_->SchedulePaintInRect(rect_to_paint); } SwapBuffersCompleted(ack_params); }
171,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->arp)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(e)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; }
167,364
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Maybe<bool> CollectValuesOrEntriesImpl( Isolate* isolate, Handle<JSObject> object, Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items, PropertyFilter filter) { int count = 0; KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES); Subclass::CollectElementIndicesImpl( object, handle(object->elements(), isolate), &accumulator); Handle<FixedArray> keys = accumulator.GetKeys(); for (int i = 0; i < keys->length(); ++i) { Handle<Object> key(keys->get(i), isolate); Handle<Object> value; uint32_t index; if (!key->ToUint32(&index)) continue; uint32_t entry = Subclass::GetEntryForIndexImpl( isolate, *object, object->elements(), index, filter); if (entry == kMaxUInt32) continue; PropertyDetails details = Subclass::GetDetailsImpl(*object, entry); if (details.kind() == kData) { value = Subclass::GetImpl(isolate, object->elements(), entry); } else { LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(&it), Nothing<bool>()); } if (get_entries) { value = MakeEntryPair(isolate, index, value); } values_or_entries->set(count++, *value); } *nof_items = count; return Just(true); } 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
static Maybe<bool> CollectValuesOrEntriesImpl( Isolate* isolate, Handle<JSObject> object, Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items, PropertyFilter filter) { DCHECK_EQ(*nof_items, 0); KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES); Subclass::CollectElementIndicesImpl( object, handle(object->elements(), isolate), &accumulator); Handle<FixedArray> keys = accumulator.GetKeys(); int count = 0; int i = 0; Handle<Map> original_map(object->map(), isolate); for (; i < keys->length(); ++i) { Handle<Object> key(keys->get(i), isolate); uint32_t index; if (!key->ToUint32(&index)) continue; DCHECK_EQ(object->map(), *original_map); uint32_t entry = Subclass::GetEntryForIndexImpl( isolate, *object, object->elements(), index, filter); if (entry == kMaxUInt32) continue; PropertyDetails details = Subclass::GetDetailsImpl(*object, entry); Handle<Object> value; if (details.kind() == kData) { value = Subclass::GetImpl(isolate, object->elements(), entry); } else { // This might modify the elements and/or change the elements kind. LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(&it), Nothing<bool>()); } if (get_entries) value = MakeEntryPair(isolate, index, value); values_or_entries->set(count++, *value); if (object->map() != *original_map) break; } // Slow path caused by changes in elements kind during iteration. for (; i < keys->length(); i++) { Handle<Object> key(keys->get(i), isolate); uint32_t index; if (!key->ToUint32(&index)) continue; if (filter & ONLY_ENUMERABLE) { InternalElementsAccessor* accessor = reinterpret_cast<InternalElementsAccessor*>( object->GetElementsAccessor()); uint32_t entry = accessor->GetEntryForIndex(isolate, *object, object->elements(), index); if (entry == kMaxUInt32) continue; PropertyDetails details = accessor->GetDetails(*object, entry); if (!details.IsEnumerable()) continue; } Handle<Object> value; LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, value, Object::GetProperty(&it), Nothing<bool>()); if (get_entries) value = MakeEntryPair(isolate, index, value); values_or_entries->set(count++, *value); } *nof_items = count; return Just(true); }
174,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); } 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:
virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAgentManagerClient( scoped_ptr<BluetoothAgentManagerClient>( new FakeBluetoothAgentManagerClient)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); }
171,242
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu) CWE ID: CWE-119
static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1); (void) SetImageType(image,BilevelType); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); }
168,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long dgnc_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { unsigned long flags; void __user *uarg = (void __user *)arg; switch (cmd) { case DIGI_GETDD: { /* * This returns the total number of boards * in the system, as well as driver version * and has space for a reserved entry */ struct digi_dinfo ddi; spin_lock_irqsave(&dgnc_global_lock, flags); ddi.dinfo_nboards = dgnc_NumBoards; sprintf(ddi.dinfo_version, "%s", DG_PART); spin_unlock_irqrestore(&dgnc_global_lock, flags); if (copy_to_user(uarg, &ddi, sizeof(ddi))) return -EFAULT; break; } case DIGI_GETBD: { int brd; struct digi_info di; if (copy_from_user(&brd, uarg, sizeof(int))) return -EFAULT; if (brd < 0 || brd >= dgnc_NumBoards) return -ENODEV; memset(&di, 0, sizeof(di)); di.info_bdnum = brd; spin_lock_irqsave(&dgnc_Board[brd]->bd_lock, flags); di.info_bdtype = dgnc_Board[brd]->dpatype; di.info_bdstate = dgnc_Board[brd]->dpastatus; di.info_ioport = 0; di.info_physaddr = (ulong)dgnc_Board[brd]->membase; di.info_physsize = (ulong)dgnc_Board[brd]->membase - dgnc_Board[brd]->membase_end; if (dgnc_Board[brd]->state != BOARD_FAILED) di.info_nports = dgnc_Board[brd]->nasync; else di.info_nports = 0; spin_unlock_irqrestore(&dgnc_Board[brd]->bd_lock, flags); if (copy_to_user(uarg, &di, sizeof(di))) return -EFAULT; break; } case DIGI_GET_NI_INFO: { struct channel_t *ch; struct ni_info ni; unsigned char mstat = 0; uint board = 0; uint channel = 0; if (copy_from_user(&ni, uarg, sizeof(ni))) return -EFAULT; board = ni.board; channel = ni.channel; /* Verify boundaries on board */ if (board >= dgnc_NumBoards) return -ENODEV; /* Verify boundaries on channel */ if (channel >= dgnc_Board[board]->nasync) return -ENODEV; ch = dgnc_Board[board]->channels[channel]; if (!ch || ch->magic != DGNC_CHANNEL_MAGIC) return -ENODEV; memset(&ni, 0, sizeof(ni)); ni.board = board; ni.channel = channel; spin_lock_irqsave(&ch->ch_lock, flags); mstat = (ch->ch_mostat | ch->ch_mistat); if (mstat & UART_MCR_DTR) { ni.mstat |= TIOCM_DTR; ni.dtr = TIOCM_DTR; } if (mstat & UART_MCR_RTS) { ni.mstat |= TIOCM_RTS; ni.rts = TIOCM_RTS; } if (mstat & UART_MSR_CTS) { ni.mstat |= TIOCM_CTS; ni.cts = TIOCM_CTS; } if (mstat & UART_MSR_RI) { ni.mstat |= TIOCM_RI; ni.ri = TIOCM_RI; } if (mstat & UART_MSR_DCD) { ni.mstat |= TIOCM_CD; ni.dcd = TIOCM_CD; } if (mstat & UART_MSR_DSR) ni.mstat |= TIOCM_DSR; ni.iflag = ch->ch_c_iflag; ni.oflag = ch->ch_c_oflag; ni.cflag = ch->ch_c_cflag; ni.lflag = ch->ch_c_lflag; if (ch->ch_digi.digi_flags & CTSPACE || ch->ch_c_cflag & CRTSCTS) ni.hflow = 1; else ni.hflow = 0; if ((ch->ch_flags & CH_STOPI) || (ch->ch_flags & CH_FORCED_STOPI)) ni.recv_stopped = 1; else ni.recv_stopped = 0; if ((ch->ch_flags & CH_STOP) || (ch->ch_flags & CH_FORCED_STOP)) ni.xmit_stopped = 1; else ni.xmit_stopped = 0; ni.curtx = ch->ch_txcount; ni.currx = ch->ch_rxcount; ni.baud = ch->ch_old_baud; spin_unlock_irqrestore(&ch->ch_lock, flags); if (copy_to_user(uarg, &ni, sizeof(ni))) return -EFAULT; break; } } return 0; } Commit Message: staging/dgnc: fix info leak in ioctl The dgnc_mgmt_ioctl() code fails to initialize the 16 _reserved bytes of struct digi_dinfo after the ->dinfo_nboards member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Salva Peiró <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200
long dgnc_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { unsigned long flags; void __user *uarg = (void __user *)arg; switch (cmd) { case DIGI_GETDD: { /* * This returns the total number of boards * in the system, as well as driver version * and has space for a reserved entry */ struct digi_dinfo ddi; spin_lock_irqsave(&dgnc_global_lock, flags); memset(&ddi, 0, sizeof(ddi)); ddi.dinfo_nboards = dgnc_NumBoards; sprintf(ddi.dinfo_version, "%s", DG_PART); spin_unlock_irqrestore(&dgnc_global_lock, flags); if (copy_to_user(uarg, &ddi, sizeof(ddi))) return -EFAULT; break; } case DIGI_GETBD: { int brd; struct digi_info di; if (copy_from_user(&brd, uarg, sizeof(int))) return -EFAULT; if (brd < 0 || brd >= dgnc_NumBoards) return -ENODEV; memset(&di, 0, sizeof(di)); di.info_bdnum = brd; spin_lock_irqsave(&dgnc_Board[brd]->bd_lock, flags); di.info_bdtype = dgnc_Board[brd]->dpatype; di.info_bdstate = dgnc_Board[brd]->dpastatus; di.info_ioport = 0; di.info_physaddr = (ulong)dgnc_Board[brd]->membase; di.info_physsize = (ulong)dgnc_Board[brd]->membase - dgnc_Board[brd]->membase_end; if (dgnc_Board[brd]->state != BOARD_FAILED) di.info_nports = dgnc_Board[brd]->nasync; else di.info_nports = 0; spin_unlock_irqrestore(&dgnc_Board[brd]->bd_lock, flags); if (copy_to_user(uarg, &di, sizeof(di))) return -EFAULT; break; } case DIGI_GET_NI_INFO: { struct channel_t *ch; struct ni_info ni; unsigned char mstat = 0; uint board = 0; uint channel = 0; if (copy_from_user(&ni, uarg, sizeof(ni))) return -EFAULT; board = ni.board; channel = ni.channel; /* Verify boundaries on board */ if (board >= dgnc_NumBoards) return -ENODEV; /* Verify boundaries on channel */ if (channel >= dgnc_Board[board]->nasync) return -ENODEV; ch = dgnc_Board[board]->channels[channel]; if (!ch || ch->magic != DGNC_CHANNEL_MAGIC) return -ENODEV; memset(&ni, 0, sizeof(ni)); ni.board = board; ni.channel = channel; spin_lock_irqsave(&ch->ch_lock, flags); mstat = (ch->ch_mostat | ch->ch_mistat); if (mstat & UART_MCR_DTR) { ni.mstat |= TIOCM_DTR; ni.dtr = TIOCM_DTR; } if (mstat & UART_MCR_RTS) { ni.mstat |= TIOCM_RTS; ni.rts = TIOCM_RTS; } if (mstat & UART_MSR_CTS) { ni.mstat |= TIOCM_CTS; ni.cts = TIOCM_CTS; } if (mstat & UART_MSR_RI) { ni.mstat |= TIOCM_RI; ni.ri = TIOCM_RI; } if (mstat & UART_MSR_DCD) { ni.mstat |= TIOCM_CD; ni.dcd = TIOCM_CD; } if (mstat & UART_MSR_DSR) ni.mstat |= TIOCM_DSR; ni.iflag = ch->ch_c_iflag; ni.oflag = ch->ch_c_oflag; ni.cflag = ch->ch_c_cflag; ni.lflag = ch->ch_c_lflag; if (ch->ch_digi.digi_flags & CTSPACE || ch->ch_c_cflag & CRTSCTS) ni.hflow = 1; else ni.hflow = 0; if ((ch->ch_flags & CH_STOPI) || (ch->ch_flags & CH_FORCED_STOPI)) ni.recv_stopped = 1; else ni.recv_stopped = 0; if ((ch->ch_flags & CH_STOP) || (ch->ch_flags & CH_FORCED_STOP)) ni.xmit_stopped = 1; else ni.xmit_stopped = 0; ni.curtx = ch->ch_txcount; ni.currx = ch->ch_rxcount; ni.baud = ch->ch_old_baud; spin_unlock_irqrestore(&ch->ch_lock, flags); if (copy_to_user(uarg, &ni, sizeof(ni))) return -EFAULT; break; } } return 0; }
166,574
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian, const unsigned char *buffer) { unsigned int value; if (endian == LSBEndian) { value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8 ) | (buffer[0])); return((unsigned int) (value & 0xffffffff)); } value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); return((unsigned int) (value & 0xffffffff)); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian, const unsigned char *buffer) { unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; return(value & 0xffffffff); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; return(value & 0xffffffff); }
169,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_open) { char *cipher, *cipher_dir; char *mode, *mode_dir; int cipher_len, cipher_dir_len; int mode_len, mode_dir_len; MCRYPT td; php_mcrypt *pm; if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &cipher, &cipher_len, &cipher_dir, &cipher_dir_len, &mode, &mode_len, &mode_dir, &mode_dir_len)) { return; } td = mcrypt_module_open ( cipher, cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir), mode, mode_dir_len > 0 ? mode_dir : MCG(modes_dir) ); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module"); RETURN_FALSE; } else { pm = emalloc(sizeof(php_mcrypt)); pm->td = td; pm->init = 0; ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt); } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_open) { char *cipher, *cipher_dir; char *mode, *mode_dir; int cipher_len, cipher_dir_len; int mode_len, mode_dir_len; MCRYPT td; php_mcrypt *pm; if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &cipher, &cipher_len, &cipher_dir, &cipher_dir_len, &mode, &mode_len, &mode_dir, &mode_dir_len)) { return; } td = mcrypt_module_open ( cipher, cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir), mode, mode_dir_len > 0 ? mode_dir : MCG(modes_dir) ); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module"); RETURN_FALSE; } else { pm = emalloc(sizeof(php_mcrypt)); pm->td = td; pm->init = 0; ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt); } }
167,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */
167,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FragmentPaintPropertyTreeBuilder::UpdatePaintOffsetTranslation( const base::Optional<IntPoint>& paint_offset_translation) { DCHECK(properties_); if (paint_offset_translation) { TransformPaintPropertyNode::State state; state.matrix.Translate(paint_offset_translation->X(), paint_offset_translation->Y()); state.flattens_inherited_transform = context_.current.should_flatten_inherited_transform; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) state.rendering_context_id = context_.current.rendering_context_id; OnUpdate(properties_->UpdatePaintOffsetTranslation( context_.current.transform, std::move(state))); context_.current.transform = properties_->PaintOffsetTranslation(); if (object_.IsLayoutView()) { context_.absolute_position.transform = properties_->PaintOffsetTranslation(); context_.fixed_position.transform = properties_->PaintOffsetTranslation(); } } else { OnClear(properties_->ClearPaintOffsetTranslation()); } } 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:
void FragmentPaintPropertyTreeBuilder::UpdatePaintOffsetTranslation( const base::Optional<IntPoint>& paint_offset_translation) { DCHECK(properties_); if (paint_offset_translation) { TransformPaintPropertyNode::State state; state.matrix.Translate(paint_offset_translation->X(), paint_offset_translation->Y()); state.flattens_inherited_transform = context_.current.should_flatten_inherited_transform; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) state.rendering_context_id = context_.current.rendering_context_id; OnUpdate(properties_->UpdatePaintOffsetTranslation( *context_.current.transform, std::move(state))); context_.current.transform = properties_->PaintOffsetTranslation(); if (object_.IsLayoutView()) { context_.absolute_position.transform = properties_->PaintOffsetTranslation(); context_.fixed_position.transform = properties_->PaintOffsetTranslation(); } } else { OnClear(properties_->ClearPaintOffsetTranslation()); } }
171,802
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadWEBPImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; int webp_status; MagickBooleanType status; register unsigned char *p; size_t length; ssize_t count, y; unsigned char header[12], *stream; WebPDecoderConfig configure; WebPDecBuffer *magick_restrict webp_image = &configure.output; WebPBitstreamFeatures *magick_restrict features = &configure.input; /* 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); } if (WebPInitDecoderConfig(&configure) == 0) ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile"); webp_image->colorspace=MODE_RGBA; count=ReadBlob(image,12,header); if (count != 12) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); status=IsWEBP(header,count); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"CorruptImage"); length=(size_t) (ReadWebPLSBWord(header+4)+8); if (length < 12) ThrowReaderException(CorruptImageError,"CorruptImage"); stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream)); if (stream == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memcpy(stream,header,12); count=ReadBlob(image,length-12,stream+12); if (count != (ssize_t) (length-12)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); webp_status=WebPGetFeatures(stream,length,features); if (webp_status == VP8_STATUS_OK) { image->columns=(size_t) features->width; image->rows=(size_t) features->height; image->depth=8; image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse; if (IsWEBPImageLossless(stream,length) != MagickFalse) image->quality=100; if (image_info->ping != MagickFalse) { stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } webp_status=WebPDecode(stream,length,&configure); } if (webp_status != VP8_STATUS_OK) { stream=(unsigned char*) RelinquishMagickMemory(stream); switch (webp_status) { case VP8_STATUS_OUT_OF_MEMORY: { ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); break; } case VP8_STATUS_INVALID_PARAM: { ThrowReaderException(CorruptImageError,"invalid parameter"); break; } case VP8_STATUS_BITSTREAM_ERROR: { ThrowReaderException(CorruptImageError,"CorruptImage"); break; } case VP8_STATUS_UNSUPPORTED_FEATURE: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); break; } case VP8_STATUS_SUSPENDED: { ThrowReaderException(CorruptImageError,"decoder suspended"); break; } case VP8_STATUS_USER_ABORT: { ThrowReaderException(CorruptImageError,"user abort"); break; } case VP8_STATUS_NOT_ENOUGH_DATA: { ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); break; } default: ThrowReaderException(CorruptImageError,"CorruptImage"); } } p=(unsigned char *) webp_image->u.RGBA.rgba; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } WebPFreeDecBuffer(webp_image); stream=(unsigned char*) RelinquishMagickMemory(stream); return(image); } Commit Message: Fixed fd leak for webp coder (patch from #382) CWE ID: CWE-119
static Image *ReadWEBPImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; int webp_status; MagickBooleanType status; register unsigned char *p; size_t length; ssize_t count, y; unsigned char header[12], *stream; WebPDecoderConfig configure; WebPDecBuffer *magick_restrict webp_image = &configure.output; WebPBitstreamFeatures *magick_restrict features = &configure.input; /* 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); } if (WebPInitDecoderConfig(&configure) == 0) ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile"); webp_image->colorspace=MODE_RGBA; count=ReadBlob(image,12,header); if (count != 12) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); status=IsWEBP(header,count); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"CorruptImage"); length=(size_t) (ReadWebPLSBWord(header+4)+8); if (length < 12) ThrowReaderException(CorruptImageError,"CorruptImage"); stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream)); if (stream == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memcpy(stream,header,12); count=ReadBlob(image,length-12,stream+12); if (count != (ssize_t) (length-12)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); webp_status=WebPGetFeatures(stream,length,features); if (webp_status == VP8_STATUS_OK) { image->columns=(size_t) features->width; image->rows=(size_t) features->height; image->depth=8; image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse; if (IsWEBPImageLossless(stream,length) != MagickFalse) image->quality=100; if (image_info->ping != MagickFalse) { stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } webp_status=WebPDecode(stream,length,&configure); } if (webp_status != VP8_STATUS_OK) { stream=(unsigned char*) RelinquishMagickMemory(stream); switch (webp_status) { case VP8_STATUS_OUT_OF_MEMORY: { ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); break; } case VP8_STATUS_INVALID_PARAM: { ThrowReaderException(CorruptImageError,"invalid parameter"); break; } case VP8_STATUS_BITSTREAM_ERROR: { ThrowReaderException(CorruptImageError,"CorruptImage"); break; } case VP8_STATUS_UNSUPPORTED_FEATURE: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); break; } case VP8_STATUS_SUSPENDED: { ThrowReaderException(CorruptImageError,"decoder suspended"); break; } case VP8_STATUS_USER_ABORT: { ThrowReaderException(CorruptImageError,"user abort"); break; } case VP8_STATUS_NOT_ENOUGH_DATA: { ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); break; } default: ThrowReaderException(CorruptImageError,"CorruptImage"); } } p=(unsigned char *) webp_image->u.RGBA.rgba; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } WebPFreeDecBuffer(webp_image); stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(image); }
168,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: HRESULT WaitForLoginUIAndGetResult( CGaiaCredentialBase::UIProcessInfo* uiprocinfo, std::string* json_result, DWORD* exit_code, BSTR* status_text) { LOGFN(INFO); DCHECK(uiprocinfo); DCHECK(json_result); DCHECK(exit_code); DCHECK(status_text); const int kBufferSize = 4096; std::vector<char> output_buffer(kBufferSize, '\0'); base::ScopedClosureRunner zero_buffer_on_exit( base::BindOnce(base::IgnoreResult(&RtlSecureZeroMemory), &output_buffer[0], kBufferSize)); HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(), uiprocinfo->parent_handles, exit_code, &output_buffer[0], kBufferSize); LOGFN(INFO) << "exit_code=" << exit_code; if (*exit_code == kUiecAbort) { LOGFN(ERROR) << "Aborted hr=" << putHR(hr); return E_ABORT; } else if (*exit_code != kUiecSuccess) { LOGFN(ERROR) << "Error hr=" << putHR(hr); *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } *json_result = std::string(&output_buffer[0]); return S_OK; } Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled. Unless the registry key "mdm_aca" is explicitly set to 1, always fail sign in of consumer accounts when mdm enrollment is enabled. Consumer accounts are defined as accounts with gmail.com or googlemail.com domain. Bug: 944049 Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903 Commit-Queue: Tien Mai <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#646278} CWE ID: CWE-284
HRESULT WaitForLoginUIAndGetResult( CGaiaCredentialBase::UIProcessInfo* uiprocinfo, std::string* json_result, DWORD* exit_code, BSTR* status_text) { LOGFN(INFO); DCHECK(uiprocinfo); DCHECK(json_result); DCHECK(exit_code); DCHECK(status_text); const int kBufferSize = 4096; std::vector<char> output_buffer(kBufferSize, '\0'); base::ScopedClosureRunner zero_buffer_on_exit( base::BindOnce(base::IgnoreResult(&RtlSecureZeroMemory), &output_buffer[0], kBufferSize)); HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(), uiprocinfo->parent_handles, exit_code, &output_buffer[0], kBufferSize); LOGFN(INFO) << "exit_code=" << *exit_code; if (*exit_code == kUiecAbort) { LOGFN(ERROR) << "Aborted hr=" << putHR(hr); return E_ABORT; } else if (*exit_code != kUiecSuccess) { LOGFN(ERROR) << "Error hr=" << putHR(hr); *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } *json_result = std::string(&output_buffer[0]); return S_OK; }
172,102
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(navigation_handle); if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSameDocument()) { return; } first_time_title_set_ = false; first_time_favicon_set_ = false; if (!navigation_handle->HasCommitted()) return; const url::Origin new_origin = url::Origin::Create(navigation_handle->GetURL()); if (writer_ && new_origin == writer_origin_) return; writer_.reset(); writer_origin_ = url::Origin(); if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS()) return; Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); DCHECK(profile); SiteCharacteristicsDataStore* data_store = LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile); DCHECK(data_store); writer_ = data_store->GetWriterForOrigin( new_origin, ContentVisibilityToRCVisibility(web_contents()->GetVisibility())); if (TabLoadTracker::Get()->GetLoadingState(web_contents()) == LoadingState::LOADED) { writer_->NotifySiteLoaded(); } writer_origin_ = new_origin; } 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:
void LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(navigation_handle); if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSameDocument()) { return; } first_time_title_set_ = false; first_time_favicon_set_ = false; if (!navigation_handle->HasCommitted()) return; const url::Origin new_origin = url::Origin::Create(navigation_handle->GetURL()); if (writer_ && new_origin == writer_origin_) return; writer_.reset(); writer_origin_ = url::Origin(); if (!URLShouldBeStoredInLocalDatabase(navigation_handle->GetURL())) return; Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); DCHECK(profile); SiteCharacteristicsDataStore* data_store = LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile); DCHECK(data_store); writer_ = data_store->GetWriterForOrigin( new_origin, ContentVisibilityToRCVisibility(web_contents()->GetVisibility())); if (TabLoadTracker::Get()->GetLoadingState(web_contents()) == LoadingState::LOADED) { writer_->NotifySiteLoaded(); } writer_origin_ = new_origin; }
172,216
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> serializedValueCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.serializedValue"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); bool serializedArgDidThrow = false; RefPtr<SerializedScriptValue> serializedArg = SerializedScriptValue::create(args[0], 0, 0, serializedArgDidThrow, args.GetIsolate()); if (serializedArgDidThrow) return v8::Undefined(); imp->serializedValue(serializedArg); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> serializedValueCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.serializedValue"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); bool serializedArgDidThrow = false; RefPtr<SerializedScriptValue> serializedArg = SerializedScriptValue::create(args[0], 0, 0, serializedArgDidThrow, args.GetIsolate()); if (serializedArgDidThrow) return v8::Undefined(); imp->serializedValue(serializedArg); return v8::Handle<v8::Value>(); }
171,104
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: enum nss_status _nss_mymachines_getgrnam_r( const char *name, struct group *gr, char *buffer, size_t buflen, int *errnop) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_bus_message_unref_ sd_bus_message* reply = NULL; _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL; const char *p, *e, *machine; uint32_t mapped; uid_t gid; size_t l; int r; assert(name); assert(gr); p = startswith(name, "vg-"); if (!p) goto not_found; e = strrchr(p, '-'); if (!e || e == p) goto not_found; r = parse_gid(e + 1, &gid); if (r < 0) goto not_found; machine = strndupa(p, e - p); if (!machine_name_is_valid(machine)) goto not_found; r = sd_bus_open_system(&bus); if (r < 0) goto fail; r = sd_bus_call_method(bus, "org.freedesktop.machine1", "/org/freedesktop/machine1", "org.freedesktop.machine1.Manager", "MapFromMachineGroup", &error, &reply, "su", machine, (uint32_t) gid); if (r < 0) { if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_GROUP_MAPPING)) goto not_found; goto fail; } r = sd_bus_message_read(reply, "u", &mapped); if (r < 0) goto fail; l = sizeof(char*) + strlen(name) + 1; if (buflen < l) { *errnop = ENOMEM; return NSS_STATUS_TRYAGAIN; } memzero(buffer, sizeof(char*)); strcpy(buffer + sizeof(char*), name); gr->gr_name = buffer + sizeof(char*); gr->gr_gid = gid; gr->gr_passwd = (char*) "*"; /* locked */ gr->gr_mem = (char**) buffer; *errnop = 0; return NSS_STATUS_SUCCESS; not_found: *errnop = 0; return NSS_STATUS_NOTFOUND; fail: *errnop = -r; return NSS_STATUS_UNAVAIL; } Commit Message: nss-mymachines: do not allow overlong machine names https://github.com/systemd/systemd/issues/2002 CWE ID: CWE-119
enum nss_status _nss_mymachines_getgrnam_r( const char *name, struct group *gr, char *buffer, size_t buflen, int *errnop) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_bus_message_unref_ sd_bus_message* reply = NULL; _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL; const char *p, *e, *machine; uint32_t mapped; uid_t gid; size_t l; int r; assert(name); assert(gr); p = startswith(name, "vg-"); if (!p) goto not_found; e = strrchr(p, '-'); if (!e || e == p) goto not_found; if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */ goto not_found; r = parse_gid(e + 1, &gid); if (r < 0) goto not_found; machine = strndupa(p, e - p); if (!machine_name_is_valid(machine)) goto not_found; r = sd_bus_open_system(&bus); if (r < 0) goto fail; r = sd_bus_call_method(bus, "org.freedesktop.machine1", "/org/freedesktop/machine1", "org.freedesktop.machine1.Manager", "MapFromMachineGroup", &error, &reply, "su", machine, (uint32_t) gid); if (r < 0) { if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_GROUP_MAPPING)) goto not_found; goto fail; } r = sd_bus_message_read(reply, "u", &mapped); if (r < 0) goto fail; l = sizeof(char*) + strlen(name) + 1; if (buflen < l) { *errnop = ENOMEM; return NSS_STATUS_TRYAGAIN; } memzero(buffer, sizeof(char*)); strcpy(buffer + sizeof(char*), name); gr->gr_name = buffer + sizeof(char*); gr->gr_gid = gid; gr->gr_passwd = (char*) "*"; /* locked */ gr->gr_mem = (char**) buffer; *errnop = 0; return NSS_STATUS_SUCCESS; not_found: *errnop = 0; return NSS_STATUS_NOTFOUND; fail: *errnop = -r; return NSS_STATUS_UNAVAIL; }
168,869
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { int refs; struct page *head, *page; if (!pgd_access_permitted(orig, write)) return 0; BUILD_BUG_ON(pgd_devmap(orig)); refs = 0; page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = compound_head(pgd_page(orig)); if (!page_cache_add_speculative(head, refs)) { *nr -= refs; return 0; } if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { int refs; struct page *head, *page; if (!pgd_access_permitted(orig, write)) return 0; BUILD_BUG_ON(pgd_devmap(orig)); refs = 0; page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = try_get_compound_head(pgd_page(orig), refs); if (!head) { *nr -= refs; return 0; } if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; }
170,225
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; }
169,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long vorbis_book_decodev_add(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j; if (!v) return -1; for(i=0;i<n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim;j++) a[i++]+=v[j]; } } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
long vorbis_book_decodev_add(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j; if (!v) return -1; for(i=0;i<n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim && i < n;j++) a[i++]+=v[j]; } } return 0; }
173,986
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cib_timeout_handler(gpointer data) { struct timer_rec_s *timer = data; timer_expired = TRUE; crm_err("Call %d timed out after %ds", timer->call_id, timer->timeout); /* Always return TRUE, never remove the handler * We do that after the while-loop in cib_native_perform_op() */ return TRUE; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_timeout_handler(gpointer data)
166,154
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile( JNIEnv* env, const JavaParamRef<jstring>& java_update_request_path, const JavaParamRef<jstring>& java_start_url, const JavaParamRef<jstring>& java_scope, const JavaParamRef<jstring>& java_name, const JavaParamRef<jstring>& java_short_name, const JavaParamRef<jstring>& java_primary_icon_url, const JavaParamRef<jobject>& java_primary_icon_bitmap, const JavaParamRef<jstring>& java_badge_icon_url, const JavaParamRef<jobject>& java_badge_icon_bitmap, const JavaParamRef<jobjectArray>& java_icon_urls, const JavaParamRef<jobjectArray>& java_icon_hashes, jint java_display_mode, jint java_orientation, jlong java_theme_color, jlong java_background_color, const JavaParamRef<jstring>& java_web_manifest_url, const JavaParamRef<jstring>& java_webapk_package, jint java_webapk_version, jboolean java_is_manifest_stale, jint java_update_reason, const JavaParamRef<jobject>& java_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string update_request_path = ConvertJavaStringToUTF8(env, java_update_request_path); ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url))); info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope)); info.name = ConvertJavaStringToUTF16(env, java_name); info.short_name = ConvertJavaStringToUTF16(env, java_short_name); info.user_title = info.short_name; info.display = static_cast<blink::WebDisplayMode>(java_display_mode); info.orientation = static_cast<blink::WebScreenOrientationLockType>(java_orientation); info.theme_color = (int64_t)java_theme_color; info.background_color = (int64_t)java_background_color; info.best_primary_icon_url = GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url)); info.best_badge_icon_url = GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url)); info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url)); base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls, &info.icon_urls); std::vector<std::string> icon_hashes; base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes, &icon_hashes); std::map<std::string, std::string> icon_url_to_murmur2_hash; for (size_t i = 0; i < info.icon_urls.size(); ++i) icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i]; gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap); SkBitmap primary_icon = gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock); primary_icon.setImmutable(); SkBitmap badge_icon; if (!java_badge_icon_bitmap.is_null()) { gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap); gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock); badge_icon.setImmutable(); } std::string webapk_package; ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package); WebApkUpdateReason update_reason = static_cast<WebApkUpdateReason>(java_update_reason); WebApkInstaller::StoreUpdateRequestToFile( base::FilePath(update_request_path), info, primary_icon, badge_icon, webapk_package, std::to_string(java_webapk_version), icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason, base::BindOnce(&base::android::RunBooleanCallbackAndroid, ScopedJavaGlobalRef<jobject>(java_callback))); } Commit Message: [Android WebAPK] Send share target information in WebAPK updates This CL plumbs through share target information for WebAPK updates. Chromium detects Web Manifest updates (including Web Manifest share target updates) and requests an update. Currently, depending on whether the Web Manifest is for an intranet site, the updated WebAPK would either: - no longer be able handle share intents (even if the Web Manifest share target information was not deleted) - be created with the same share intent handlers as the current WebAPK (regardless of whether the Web Manifest share target information has changed). This CL plumbs through the share target information from WebApkUpdateDataFetcher#onDataAvailable() to WebApkUpdateManager::StoreWebApkUpdateRequestToFile() BUG=912945 Change-Id: Ie416570533abc848eeb23de8c197b44f2a1fd028 Reviewed-on: https://chromium-review.googlesource.com/c/1369709 Commit-Queue: Peter Kotwicz <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Cr-Commit-Position: refs/heads/master@{#616429} CWE ID: CWE-200
static void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile( JNIEnv* env, const JavaParamRef<jstring>& java_update_request_path, const JavaParamRef<jstring>& java_start_url, const JavaParamRef<jstring>& java_scope, const JavaParamRef<jstring>& java_name, const JavaParamRef<jstring>& java_short_name, const JavaParamRef<jstring>& java_primary_icon_url, const JavaParamRef<jobject>& java_primary_icon_bitmap, const JavaParamRef<jstring>& java_badge_icon_url, const JavaParamRef<jobject>& java_badge_icon_bitmap, const JavaParamRef<jobjectArray>& java_icon_urls, const JavaParamRef<jobjectArray>& java_icon_hashes, jint java_display_mode, jint java_orientation, jlong java_theme_color, jlong java_background_color, const JavaParamRef<jstring>& java_share_target_action, const JavaParamRef<jstring>& java_share_target_param_title, const JavaParamRef<jstring>& java_share_target_param_text, const JavaParamRef<jstring>& java_share_target_param_url, const JavaParamRef<jstring>& java_web_manifest_url, const JavaParamRef<jstring>& java_webapk_package, jint java_webapk_version, jboolean java_is_manifest_stale, jint java_update_reason, const JavaParamRef<jobject>& java_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string update_request_path = ConvertJavaStringToUTF8(env, java_update_request_path); ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url))); info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope)); info.name = ConvertJavaStringToUTF16(env, java_name); info.short_name = ConvertJavaStringToUTF16(env, java_short_name); info.user_title = info.short_name; info.display = static_cast<blink::WebDisplayMode>(java_display_mode); info.orientation = static_cast<blink::WebScreenOrientationLockType>(java_orientation); info.theme_color = (int64_t)java_theme_color; info.background_color = (int64_t)java_background_color; info.best_primary_icon_url = GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url)); info.best_badge_icon_url = GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url)); info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url)); GURL share_target_action = GURL(ConvertJavaStringToUTF8(env, java_share_target_action)); if (!share_target_action.is_empty()) { info.share_target = ShareTarget(); info.share_target->action = share_target_action; info.share_target->params.title = ConvertJavaStringToUTF16(java_share_target_param_title); info.share_target->params.text = ConvertJavaStringToUTF16(java_share_target_param_text); info.share_target->params.url = ConvertJavaStringToUTF16(java_share_target_param_url); } base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls, &info.icon_urls); std::vector<std::string> icon_hashes; base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes, &icon_hashes); std::map<std::string, std::string> icon_url_to_murmur2_hash; for (size_t i = 0; i < info.icon_urls.size(); ++i) icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i]; gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap); SkBitmap primary_icon = gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock); primary_icon.setImmutable(); SkBitmap badge_icon; if (!java_badge_icon_bitmap.is_null()) { gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap); gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock); badge_icon.setImmutable(); } std::string webapk_package; ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package); WebApkUpdateReason update_reason = static_cast<WebApkUpdateReason>(java_update_reason); WebApkInstaller::StoreUpdateRequestToFile( base::FilePath(update_request_path), info, primary_icon, badge_icon, webapk_package, std::to_string(java_webapk_version), icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason, base::BindOnce(&base::android::RunBooleanCallbackAndroid, ScopedJavaGlobalRef<jobject>(java_callback))); }
172,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_netscreen_rec_hdr(struct wtap_pkthdr *phdr, const char *line, char *cap_int, gboolean *cap_dir, char *cap_dst, int *err, gchar **err_info) { int sec; int dsec, pkt_len; char direction[2]; char cap_src[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9d:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } *cap_dir = (direction[0] == 'o' ? NETSCREEN_EGRESS : NETSCREEN_INGRESS); phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len; return pkt_len; } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12396 Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f Reviewed-on: https://code.wireshark.org/review/15176 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20
parse_netscreen_rec_hdr(struct wtap_pkthdr *phdr, const char *line, char *cap_int, static gboolean parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf, char *line, int *err, gchar **err_info) { int sec; int dsec; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; char direction[2]; guint pkt_len; char cap_src[13]; char cap_dst[13]; guint8 *pd; gchar *p; int n, i = 0; guint offset = 0; gchar dststr[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9u:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } /* * If direction[0] is 'o', the direction is NETSCREEN_EGRESS, * otherwise it's NETSCREEN_INGRESS. */ phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len;
167,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); }
167,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; int extra; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; } Commit Message: Fixed CVE-2018-8785 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-119
static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; UINT32 extra = 0; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; }
169,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AppCacheBackendImpl::SelectCacheForWorker( int host_id, int parent_process_id, int parent_host_id) { AppCacheHost* host = GetHost(host_id); if (!host || host->was_select_cache_called()) return false; host->SelectCacheForWorker(parent_process_id, parent_host_id); return true; } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
bool AppCacheBackendImpl::SelectCacheForWorker( int host_id, int parent_process_id, int parent_host_id) { AppCacheHost* host = GetHost(host_id); if (!host) return false; return host->SelectCacheForWorker(parent_process_id, parent_host_id); }
171,738
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint32_t fdctrl_read_data(FDCtrl *fdctrl) { FDrive *cur_drv; uint32_t retval = 0; int pos; cur_drv = get_cur_drv(fdctrl); fdctrl->dsr &= ~FD_DSR_PWRDOWN; if (!(fdctrl->msr & FD_MSR_RQM) || !(fdctrl->msr & FD_MSR_DIO)) { FLOPPY_DPRINTF("error: controller not ready for reading\n"); return 0; } pos = fdctrl->data_pos; if (fdctrl->msr & FD_MSR_NONDMA) { pos %= FD_SECTOR_LEN; if (pos == 0) { if (fdctrl->data_pos != 0) if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) { FLOPPY_DPRINTF("error seeking to next sector %d\n", fd_sector(cur_drv)); return 0; } if (blk_read(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) { FLOPPY_DPRINTF("error getting sector %d\n", fd_sector(cur_drv)); /* Sure, image size is too small... */ memset(fdctrl->fifo, 0, FD_SECTOR_LEN); } } } retval = fdctrl->fifo[pos]; if (++fdctrl->data_pos == fdctrl->data_len) { fdctrl->data_pos = 0; /* Switch from transfer mode to status mode * then from status mode to command mode */ if (fdctrl->msr & FD_MSR_NONDMA) { fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00); } else { fdctrl_reset_fifo(fdctrl); fdctrl_reset_irq(fdctrl); } } FLOPPY_DPRINTF("data register: 0x%02x\n", retval); return retval; } Commit Message: CWE ID: CWE-119
static uint32_t fdctrl_read_data(FDCtrl *fdctrl) { FDrive *cur_drv; uint32_t retval = 0; uint32_t pos; cur_drv = get_cur_drv(fdctrl); fdctrl->dsr &= ~FD_DSR_PWRDOWN; if (!(fdctrl->msr & FD_MSR_RQM) || !(fdctrl->msr & FD_MSR_DIO)) { FLOPPY_DPRINTF("error: controller not ready for reading\n"); return 0; } pos = fdctrl->data_pos; pos %= FD_SECTOR_LEN; if (fdctrl->msr & FD_MSR_NONDMA) { if (pos == 0) { if (fdctrl->data_pos != 0) if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) { FLOPPY_DPRINTF("error seeking to next sector %d\n", fd_sector(cur_drv)); return 0; } if (blk_read(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) { FLOPPY_DPRINTF("error getting sector %d\n", fd_sector(cur_drv)); /* Sure, image size is too small... */ memset(fdctrl->fifo, 0, FD_SECTOR_LEN); } } } retval = fdctrl->fifo[pos]; if (++fdctrl->data_pos == fdctrl->data_len) { fdctrl->data_pos = 0; /* Switch from transfer mode to status mode * then from status mode to command mode */ if (fdctrl->msr & FD_MSR_NONDMA) { fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00); } else { fdctrl_reset_fifo(fdctrl); fdctrl_reset_irq(fdctrl); } } FLOPPY_DPRINTF("data register: 0x%02x\n", retval); return retval; }
164,707
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void show_object(struct object *obj, struct strbuf *path, const char *last, void *data) { char *name = path_name(path, last); add_preferred_base_object(name); add_object_entry(obj->oid.hash, obj->type, name, 0); obj->flags |= OBJECT_ADDED; /* * We will have generated the hash from the name, * but not saved a pointer to it - we can free it */ free((char *)name); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
static void show_object(struct object *obj, static void show_object(struct object *obj, const char *name, void *data) { add_preferred_base_object(name); add_object_entry(obj->oid.hash, obj->type, name, 0); obj->flags |= OBJECT_ADDED; }
167,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { handle_t *handle = ext4_journal_current_handle(); struct inode *inode = mapping->host; loff_t old_size = inode->i_size; int ret = 0, ret2; int i_size_changed = 0; trace_ext4_write_end(inode, pos, len, copied); if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) { ret = ext4_jbd2_file_inode(handle, inode); if (ret) { unlock_page(page); put_page(page); goto errout; } } if (ext4_has_inline_data(inode)) { ret = ext4_write_inline_data_end(inode, pos, len, copied, page); if (ret < 0) goto errout; copied = ret; } else copied = block_write_end(file, mapping, pos, len, copied, page, fsdata); /* * it's important to update i_size while still holding page lock: * page writeout could otherwise come in and zero beyond i_size. */ i_size_changed = ext4_update_inode_size(inode, pos + copied); unlock_page(page); put_page(page); if (old_size < pos) pagecache_isize_extended(inode, old_size, pos); /* * Don't mark the inode dirty under page lock. First, it unnecessarily * makes the holding time of page lock longer. Second, it forces lock * ordering of page lock and transaction start for journaling * filesystems. */ if (i_size_changed) ext4_mark_inode_dirty(handle, inode); if (pos + len > inode->i_size && ext4_can_truncate(inode)) /* if we have allocated more blocks and copied * less. We will have blocks allocated outside * inode->i_size. So truncate them */ ext4_orphan_add(handle, inode); errout: ret2 = ext4_journal_stop(handle); if (!ret) ret = ret2; if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might still be * on the orphan list; we need to make sure the inode * is removed from the orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } return ret ? ret : copied; } Commit Message: ext4: fix data exposure after a crash Huang has reported that in his powerfail testing he is seeing stale block contents in some of recently allocated blocks although he mounts ext4 in data=ordered mode. After some investigation I have found out that indeed when delayed allocation is used, we don't add inode to transaction's list of inodes needing flushing before commit. Originally we were doing that but commit f3b59291a69d removed the logic with a flawed argument that it is not needed. The problem is that although for delayed allocated blocks we write their contents immediately after allocating them, there is no guarantee that the IO scheduler or device doesn't reorder things and thus transaction allocating blocks and attaching them to inode can reach stable storage before actual block contents. Actually whenever we attach freshly allocated blocks to inode using a written extent, we should add inode to transaction's ordered inode list to make sure we properly wait for block contents to be written before committing the transaction. So that is what we do in this patch. This also handles other cases where stale data exposure was possible - like filling hole via mmap in data=ordered,nodelalloc mode. The only exception to the above rule are extending direct IO writes where blkdev_direct_IO() waits for IO to complete before increasing i_size and thus stale data exposure is not possible. For now we don't complicate the code with optimizing this special case since the overhead is pretty low. In case this is observed to be a performance problem we can always handle it using a special flag to ext4_map_blocks(). CC: [email protected] Fixes: f3b59291a69d0b734be1fc8be489fef2dd846d3d Reported-by: "HUANG Weller (CM/ESW12-CN)" <[email protected]> Tested-by: "HUANG Weller (CM/ESW12-CN)" <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-200
static int ext4_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { handle_t *handle = ext4_journal_current_handle(); struct inode *inode = mapping->host; loff_t old_size = inode->i_size; int ret = 0, ret2; int i_size_changed = 0; trace_ext4_write_end(inode, pos, len, copied); if (ext4_has_inline_data(inode)) { ret = ext4_write_inline_data_end(inode, pos, len, copied, page); if (ret < 0) goto errout; copied = ret; } else copied = block_write_end(file, mapping, pos, len, copied, page, fsdata); /* * it's important to update i_size while still holding page lock: * page writeout could otherwise come in and zero beyond i_size. */ i_size_changed = ext4_update_inode_size(inode, pos + copied); unlock_page(page); put_page(page); if (old_size < pos) pagecache_isize_extended(inode, old_size, pos); /* * Don't mark the inode dirty under page lock. First, it unnecessarily * makes the holding time of page lock longer. Second, it forces lock * ordering of page lock and transaction start for journaling * filesystems. */ if (i_size_changed) ext4_mark_inode_dirty(handle, inode); if (pos + len > inode->i_size && ext4_can_truncate(inode)) /* if we have allocated more blocks and copied * less. We will have blocks allocated outside * inode->i_size. So truncate them */ ext4_orphan_add(handle, inode); errout: ret2 = ext4_journal_stop(handle); if (!ret) ret = ret2; if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might still be * on the orphan list; we need to make sure the inode * is removed from the orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } return ret ? ret : copied; }
168,271
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void usage() { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, " by Willem van Schaik, 1999\n"); #ifdef __TURBOC__ fprintf (stderr, " for Turbo-C and Borland-C compilers\n"); #else fprintf (stderr, " for Linux (and Unix) compilers\n"); #endif fprintf (stderr, "Usage: png2pnm [options] <file>.png [<file>.pnm]\n"); fprintf (stderr, " or: ... | png2pnm [options]\n"); fprintf (stderr, "Options:\n"); fprintf (stderr, " -r[aw] write pnm-file in binary format (P4/P5/P6) (default)\n"); fprintf (stderr, " -n[oraw] write pnm-file in ascii format (P1/P2/P3)\n"); fprintf (stderr, " -a[lpha] <file>.pgm write PNG alpha channel as pgm-file\n"); fprintf (stderr, " -h | -? print this help-information\n"); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
void usage() { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, " by Willem van Schaik, 1999\n"); #ifdef __TURBOC__ fprintf (stderr, " for Turbo-C and Borland-C compilers\n"); #else fprintf (stderr, " for Linux (and Unix) compilers\n"); #endif fprintf (stderr, "Usage: png2pnm [options] <file>.png [<file>.pnm]\n"); fprintf (stderr, " or: ... | png2pnm [options]\n"); fprintf (stderr, "Options:\n"); fprintf (stderr, " -r[aw] write pnm-file in binary format (P4/P5/P6) (default)\n"); fprintf (stderr, " -n[oraw] write pnm-file in ascii format (P1/P2/P3)\n"); fprintf (stderr, " -a[lpha] <file>.pgm write PNG alpha channel as pgm-file\n"); fprintf (stderr, " -h | -? print this help-information\n"); }
173,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) { debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url); int ret = 400; BUFFER *dimensions = NULL; buffer_flush(w->response.data); char *google_version = "0.6", *google_reqId = "0", *google_sig = "0", *google_out = "json", *responseHandler = NULL, *outFileName = NULL; time_t last_timestamp_in_data = 0, google_timestamp = 0; char *chart = NULL , *before_str = NULL , *after_str = NULL , *group_time_str = NULL , *points_str = NULL; int group = RRDR_GROUPING_AVERAGE; uint32_t format = DATASOURCE_JSON; uint32_t options = 0x00000000; while(url) { char *value = mystrsep(&url, "?&"); if(!value || !*value) continue; char *name = mystrsep(&value, "="); if(!name || !*name) continue; if(!value || !*value) continue; debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value); if(!strcmp(name, "chart")) chart = value; else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) { if(!dimensions) dimensions = buffer_create(100); buffer_strcat(dimensions, "|"); buffer_strcat(dimensions, value); } else if(!strcmp(name, "after")) after_str = value; else if(!strcmp(name, "before")) before_str = value; else if(!strcmp(name, "points")) points_str = value; else if(!strcmp(name, "gtime")) group_time_str = value; else if(!strcmp(name, "group")) { group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE); } else if(!strcmp(name, "format")) { format = web_client_api_request_v1_data_format(value); } else if(!strcmp(name, "options")) { options |= web_client_api_request_v1_data_options(value); } else if(!strcmp(name, "callback")) { responseHandler = value; } else if(!strcmp(name, "filename")) { outFileName = value; } else if(!strcmp(name, "tqx")) { char *tqx_name, *tqx_value; while(value) { tqx_value = mystrsep(&value, ";"); if(!tqx_value || !*tqx_value) continue; tqx_name = mystrsep(&tqx_value, ":"); if(!tqx_name || !*tqx_name) continue; if(!tqx_value || !*tqx_value) continue; if(!strcmp(tqx_name, "version")) google_version = tqx_value; else if(!strcmp(tqx_name, "reqId")) google_reqId = tqx_value; else if(!strcmp(tqx_name, "sig")) { google_sig = tqx_value; google_timestamp = strtoul(google_sig, NULL, 0); } else if(!strcmp(tqx_name, "out")) { google_out = tqx_value; format = web_client_api_request_v1_data_google_format(google_out); } else if(!strcmp(tqx_name, "responseHandler")) responseHandler = tqx_value; else if(!strcmp(tqx_name, "outFileName")) outFileName = tqx_value; } } } if(!chart || !*chart) { buffer_sprintf(w->response.data, "No chart id is given at the request."); goto cleanup; } RRDSET *st = rrdset_find(host, chart); if(!st) st = rrdset_find_byname(host, chart); if(!st) { buffer_strcat(w->response.data, "Chart is not found: "); buffer_strcat_htmlescape(w->response.data, chart); ret = 404; goto cleanup; } st->last_accessed_time = now_realtime_sec(); long long before = (before_str && *before_str)?str2l(before_str):0; long long after = (after_str && *after_str) ?str2l(after_str):0; int points = (points_str && *points_str)?str2i(points_str):0; long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0; debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'" , w->id , chart , (dimensions)?buffer_tostring(dimensions):"" , after , before , points , group , format , options ); if(outFileName && *outFileName) { buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName); debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName); } if(format == DATASOURCE_DATATABLE_JSONP) { if(responseHandler == NULL) responseHandler = "google.visualization.Query.setResponse"; debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'", w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName ); buffer_sprintf(w->response.data, "%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:", responseHandler, google_version, google_reqId, st->last_updated.tv_sec); } else if(format == DATASOURCE_JSONP) { if(responseHandler == NULL) responseHandler = "callback"; buffer_strcat(w->response.data, responseHandler); buffer_strcat(w->response.data, "("); } ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time , options, &last_timestamp_in_data); if(format == DATASOURCE_DATATABLE_JSONP) { if(google_timestamp < last_timestamp_in_data) buffer_strcat(w->response.data, "});"); else { buffer_flush(w->response.data); buffer_sprintf(w->response.data, "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});", responseHandler, google_version, google_reqId); } } else if(format == DATASOURCE_JSONP) buffer_strcat(w->response.data, ");"); cleanup: buffer_free(dimensions); return ret; } Commit Message: fixed vulnerabilities identified by red4sec.com (#4521) CWE ID: CWE-200
inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) { debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url); int ret = 400; BUFFER *dimensions = NULL; buffer_flush(w->response.data); char *google_version = "0.6", *google_reqId = "0", *google_sig = "0", *google_out = "json", *responseHandler = NULL, *outFileName = NULL; time_t last_timestamp_in_data = 0, google_timestamp = 0; char *chart = NULL , *before_str = NULL , *after_str = NULL , *group_time_str = NULL , *points_str = NULL; int group = RRDR_GROUPING_AVERAGE; uint32_t format = DATASOURCE_JSON; uint32_t options = 0x00000000; while(url) { char *value = mystrsep(&url, "?&"); if(!value || !*value) continue; char *name = mystrsep(&value, "="); if(!name || !*name) continue; if(!value || !*value) continue; debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value); if(!strcmp(name, "chart")) chart = value; else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) { if(!dimensions) dimensions = buffer_create(100); buffer_strcat(dimensions, "|"); buffer_strcat(dimensions, value); } else if(!strcmp(name, "after")) after_str = value; else if(!strcmp(name, "before")) before_str = value; else if(!strcmp(name, "points")) points_str = value; else if(!strcmp(name, "gtime")) group_time_str = value; else if(!strcmp(name, "group")) { group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE); } else if(!strcmp(name, "format")) { format = web_client_api_request_v1_data_format(value); } else if(!strcmp(name, "options")) { options |= web_client_api_request_v1_data_options(value); } else if(!strcmp(name, "callback")) { responseHandler = value; } else if(!strcmp(name, "filename")) { outFileName = value; } else if(!strcmp(name, "tqx")) { char *tqx_name, *tqx_value; while(value) { tqx_value = mystrsep(&value, ";"); if(!tqx_value || !*tqx_value) continue; tqx_name = mystrsep(&tqx_value, ":"); if(!tqx_name || !*tqx_name) continue; if(!tqx_value || !*tqx_value) continue; if(!strcmp(tqx_name, "version")) google_version = tqx_value; else if(!strcmp(tqx_name, "reqId")) google_reqId = tqx_value; else if(!strcmp(tqx_name, "sig")) { google_sig = tqx_value; google_timestamp = strtoul(google_sig, NULL, 0); } else if(!strcmp(tqx_name, "out")) { google_out = tqx_value; format = web_client_api_request_v1_data_google_format(google_out); } else if(!strcmp(tqx_name, "responseHandler")) responseHandler = tqx_value; else if(!strcmp(tqx_name, "outFileName")) outFileName = tqx_value; } } } // validate the google parameters given fix_google_param(google_out); fix_google_param(google_sig); fix_google_param(google_reqId); fix_google_param(google_version); fix_google_param(responseHandler); fix_google_param(outFileName); if(!chart || !*chart) { buffer_sprintf(w->response.data, "No chart id is given at the request."); goto cleanup; } RRDSET *st = rrdset_find(host, chart); if(!st) st = rrdset_find_byname(host, chart); if(!st) { buffer_strcat(w->response.data, "Chart is not found: "); buffer_strcat_htmlescape(w->response.data, chart); ret = 404; goto cleanup; } st->last_accessed_time = now_realtime_sec(); long long before = (before_str && *before_str)?str2l(before_str):0; long long after = (after_str && *after_str) ?str2l(after_str):0; int points = (points_str && *points_str)?str2i(points_str):0; long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0; debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'" , w->id , chart , (dimensions)?buffer_tostring(dimensions):"" , after , before , points , group , format , options ); if(outFileName && *outFileName) { buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName); debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName); } if(format == DATASOURCE_DATATABLE_JSONP) { if(responseHandler == NULL) responseHandler = "google.visualization.Query.setResponse"; debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'", w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName ); buffer_sprintf(w->response.data, "%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:", responseHandler, google_version, google_reqId, st->last_updated.tv_sec); } else if(format == DATASOURCE_JSONP) { if(responseHandler == NULL) responseHandler = "callback"; buffer_strcat(w->response.data, responseHandler); buffer_strcat(w->response.data, "("); } ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time , options, &last_timestamp_in_data); if(format == DATASOURCE_DATATABLE_JSONP) { if(google_timestamp < last_timestamp_in_data) buffer_strcat(w->response.data, "});"); else { buffer_flush(w->response.data); buffer_sprintf(w->response.data, "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});", responseHandler, google_version, google_reqId); } } else if(format == DATASOURCE_JSONP) buffer_strcat(w->response.data, ");"); cleanup: buffer_free(dimensions); return ret; }
169,813
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OJPEGPreDecode(TIFF* tif, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint32 m; if (sp->subsamplingcorrect_done==0) OJPEGSubsamplingCorrect(tif); if (sp->readheader_done==0) { if (OJPEGReadHeaderInfo(tif)==0) return(0); } if (sp->sos_end[s].log==0) { if (OJPEGReadSecondarySos(tif,s)==0) return(0); } if isTiled(tif) m=tif->tif_curtile; else m=tif->tif_curstrip; if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m))) { if (sp->libjpeg_session_active!=0) OJPEGLibjpegSessionAbort(tif); sp->writeheader_done=0; } if (sp->writeheader_done==0) { sp->plane_sample_offset=(uint8)s; sp->write_cursample=s; sp->write_curstrile=s*tif->tif_dir.td_stripsperimage; if ((sp->in_buffer_file_pos_log==0) || (sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos)) { sp->in_buffer_source=sp->sos_end[s].in_buffer_source; sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile; sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos; sp->in_buffer_file_pos_log=0; sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo; sp->in_buffer_togo=0; sp->in_buffer_cur=0; } if (OJPEGWriteHeaderInfo(tif)==0) return(0); } while (sp->write_curstrile<m) { if (sp->libjpeg_jpeg_query_style==0) { if (OJPEGPreDecodeSkipRaw(tif)==0) return(0); } else { if (OJPEGPreDecodeSkipScanlines(tif)==0) return(0); } sp->write_curstrile++; } return(1); } Commit Message: * libtiff/tif_ojpeg.c: make OJPEGDecode() early exit in case of failure in OJPEGPreDecode(). This will avoid a divide by zero, and potential other issues. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2611 CWE ID: CWE-369
OJPEGPreDecode(TIFF* tif, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint32 m; if (sp->subsamplingcorrect_done==0) OJPEGSubsamplingCorrect(tif); if (sp->readheader_done==0) { if (OJPEGReadHeaderInfo(tif)==0) return(0); } if (sp->sos_end[s].log==0) { if (OJPEGReadSecondarySos(tif,s)==0) return(0); } if isTiled(tif) m=tif->tif_curtile; else m=tif->tif_curstrip; if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m))) { if (sp->libjpeg_session_active!=0) OJPEGLibjpegSessionAbort(tif); sp->writeheader_done=0; } if (sp->writeheader_done==0) { sp->plane_sample_offset=(uint8)s; sp->write_cursample=s; sp->write_curstrile=s*tif->tif_dir.td_stripsperimage; if ((sp->in_buffer_file_pos_log==0) || (sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos)) { sp->in_buffer_source=sp->sos_end[s].in_buffer_source; sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile; sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos; sp->in_buffer_file_pos_log=0; sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo; sp->in_buffer_togo=0; sp->in_buffer_cur=0; } if (OJPEGWriteHeaderInfo(tif)==0) return(0); } while (sp->write_curstrile<m) { if (sp->libjpeg_jpeg_query_style==0) { if (OJPEGPreDecodeSkipRaw(tif)==0) return(0); } else { if (OJPEGPreDecodeSkipScanlines(tif)==0) return(0); } sp->write_curstrile++; } sp->decoder_ok = 1; return(1); }
168,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int wait_for_fpga_config(void) { int ret = 0, done; /* approx 5 s */ u32 timeout = 500000; printf("PCIe FPGA config:"); do { done = qrio_get_gpio(GPIO_A, FPGA_DONE); if (timeout-- == 0) { printf(" FPGA_DONE timeout\n"); ret = -EFAULT; goto err_out; } udelay(10); } while (!done); printf(" done\n"); err_out: /* deactive CONF_SEL and give the CPU conf EEPROM access */ qrio_set_gpio(GPIO_A, CONF_SEL_L, 1); toggle_fpga_eeprom_bus(true); return ret; } 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
static int wait_for_fpga_config(void) { int ret = 0, done; /* approx 5 s */ u32 timeout = 500000; printf("PCIe FPGA config:"); do { done = qrio_get_gpio(QRIO_GPIO_A, FPGA_DONE); if (timeout-- == 0) { printf(" FPGA_DONE timeout\n"); ret = -EFAULT; goto err_out; } udelay(10); } while (!done); printf(" done\n"); err_out: /* deactive CONF_SEL and give the CPU conf EEPROM access */ qrio_set_gpio(QRIO_GPIO_A, CONF_SEL_L, 1); toggle_fpga_eeprom_bus(true); return ret; }
169,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ComponentControllerImpl::OnNavigationStateChanged( chromium::web::NavigationStateChangeDetails change, OnNavigationStateChangedCallback callback) {} Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
void ComponentControllerImpl::OnNavigationStateChanged(
172,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: sg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { void __user *p = (void __user *)arg; int __user *ip = p; int result, val, read_only; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; unsigned long iflags; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_ioctl: cmd=0x%x\n", (int) cmd_in)); read_only = (O_RDWR != (filp->f_flags & O_ACCMODE)); switch (cmd_in) { case SG_IO: if (atomic_read(&sdp->detaching)) return -ENODEV; if (!scsi_block_when_processing_errors(sdp->device)) return -ENXIO; if (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR)) return -EFAULT; result = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR, 1, read_only, 1, &srp); if (result < 0) return result; result = wait_event_interruptible(sfp->read_wait, (srp_done(sfp, srp) || atomic_read(&sdp->detaching))); if (atomic_read(&sdp->detaching)) return -ENODEV; write_lock_irq(&sfp->rq_list_lock); if (srp->done) { srp->done = 2; write_unlock_irq(&sfp->rq_list_lock); result = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp); return (result < 0) ? result : 0; } srp->orphan = 1; write_unlock_irq(&sfp->rq_list_lock); return result; /* -ERESTARTSYS because signal hit process */ case SG_SET_TIMEOUT: result = get_user(val, ip); if (result) return result; if (val < 0) return -EIO; if (val >= mult_frac((s64)INT_MAX, USER_HZ, HZ)) val = min_t(s64, mult_frac((s64)INT_MAX, USER_HZ, HZ), INT_MAX); sfp->timeout_user = val; sfp->timeout = mult_frac(val, HZ, USER_HZ); return 0; case SG_GET_TIMEOUT: /* N.B. User receives timeout as return value */ /* strange ..., for backward compatibility */ return sfp->timeout_user; case SG_SET_FORCE_LOW_DMA: /* * N.B. This ioctl never worked properly, but failed to * return an error value. So returning '0' to keep compability * with legacy applications. */ return 0; case SG_GET_LOW_DMA: return put_user((int) sdp->device->host->unchecked_isa_dma, ip); case SG_GET_SCSI_ID: if (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t))) return -EFAULT; else { sg_scsi_id_t __user *sg_idp = p; if (atomic_read(&sdp->detaching)) return -ENODEV; __put_user((int) sdp->device->host->host_no, &sg_idp->host_no); __put_user((int) sdp->device->channel, &sg_idp->channel); __put_user((int) sdp->device->id, &sg_idp->scsi_id); __put_user((int) sdp->device->lun, &sg_idp->lun); __put_user((int) sdp->device->type, &sg_idp->scsi_type); __put_user((short) sdp->device->host->cmd_per_lun, &sg_idp->h_cmd_per_lun); __put_user((short) sdp->device->queue_depth, &sg_idp->d_queue_depth); __put_user(0, &sg_idp->unused[0]); __put_user(0, &sg_idp->unused[1]); return 0; } case SG_SET_FORCE_PACK_ID: result = get_user(val, ip); if (result) return result; sfp->force_packid = val ? 1 : 0; return 0; case SG_GET_PACK_ID: if (!access_ok(VERIFY_WRITE, ip, sizeof (int))) return -EFAULT; read_lock_irqsave(&sfp->rq_list_lock, iflags); list_for_each_entry(srp, &sfp->rq_list, entry) { if ((1 == srp->done) && (!srp->sg_io_owned)) { read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(srp->header.pack_id, ip); return 0; } } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(-1, ip); return 0; case SG_GET_NUM_WAITING: read_lock_irqsave(&sfp->rq_list_lock, iflags); val = 0; list_for_each_entry(srp, &sfp->rq_list, entry) { if ((1 == srp->done) && (!srp->sg_io_owned)) ++val; } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); return put_user(val, ip); case SG_GET_SG_TABLESIZE: return put_user(sdp->sg_tablesize, ip); case SG_SET_RESERVED_SIZE: result = get_user(val, ip); if (result) return result; if (val < 0) return -EINVAL; val = min_t(int, val, max_sectors_bytes(sdp->device->request_queue)); mutex_lock(&sfp->f_mutex); if (val != sfp->reserve.bufflen) { if (sfp->mmap_called || sfp->res_in_use) { mutex_unlock(&sfp->f_mutex); return -EBUSY; } sg_remove_scat(sfp, &sfp->reserve); sg_build_reserve(sfp, val); } mutex_unlock(&sfp->f_mutex); return 0; case SG_GET_RESERVED_SIZE: val = min_t(int, sfp->reserve.bufflen, max_sectors_bytes(sdp->device->request_queue)); return put_user(val, ip); case SG_SET_COMMAND_Q: result = get_user(val, ip); if (result) return result; sfp->cmd_q = val ? 1 : 0; return 0; case SG_GET_COMMAND_Q: return put_user((int) sfp->cmd_q, ip); case SG_SET_KEEP_ORPHAN: result = get_user(val, ip); if (result) return result; sfp->keep_orphan = val; return 0; case SG_GET_KEEP_ORPHAN: return put_user((int) sfp->keep_orphan, ip); case SG_NEXT_CMD_LEN: result = get_user(val, ip); if (result) return result; if (val > SG_MAX_CDB_SIZE) return -ENOMEM; sfp->next_cmd_len = (val > 0) ? val : 0; return 0; case SG_GET_VERSION_NUM: return put_user(sg_version_num, ip); case SG_GET_ACCESS_COUNT: /* faked - we don't have a real access count anymore */ val = (sdp->device ? 1 : 0); return put_user(val, ip); case SG_GET_REQUEST_TABLE: if (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE)) return -EFAULT; else { sg_req_info_t *rinfo; rinfo = kmalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE, GFP_KERNEL); if (!rinfo) return -ENOMEM; read_lock_irqsave(&sfp->rq_list_lock, iflags); sg_fill_request_table(sfp, rinfo); read_unlock_irqrestore(&sfp->rq_list_lock, iflags); result = __copy_to_user(p, rinfo, SZ_SG_REQ_INFO * SG_MAX_QUEUE); result = result ? -EFAULT : 0; kfree(rinfo); return result; } case SG_EMULATED_HOST: if (atomic_read(&sdp->detaching)) return -ENODEV; return put_user(sdp->device->host->hostt->emulated, ip); case SCSI_IOCTL_SEND_COMMAND: if (atomic_read(&sdp->detaching)) return -ENODEV; if (read_only) { unsigned char opcode = WRITE_6; Scsi_Ioctl_Command __user *siocp = p; if (copy_from_user(&opcode, siocp->data, 1)) return -EFAULT; if (sg_allow_access(filp, &opcode)) return -EPERM; } return sg_scsi_ioctl(sdp->device->request_queue, NULL, filp->f_mode, p); case SG_SET_DEBUG: result = get_user(val, ip); if (result) return result; sdp->sgdebug = (char) val; return 0; case BLKSECTGET: return put_user(max_sectors_bytes(sdp->device->request_queue), ip); case BLKTRACESETUP: return blk_trace_setup(sdp->device->request_queue, sdp->disk->disk_name, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), NULL, p); case BLKTRACESTART: return blk_trace_startstop(sdp->device->request_queue, 1); case BLKTRACESTOP: return blk_trace_startstop(sdp->device->request_queue, 0); case BLKTRACETEARDOWN: return blk_trace_remove(sdp->device->request_queue); case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: case SCSI_IOCTL_PROBE_HOST: case SG_GET_TRANSFORM: case SG_SCSI_RESET: if (atomic_read(&sdp->detaching)) return -ENODEV; break; default: if (read_only) return -EPERM; /* don't know so take safe approach */ break; } result = scsi_ioctl_block_when_processing_errors(sdp->device, cmd_in, filp->f_flags & O_NDELAY); if (result) return result; return scsi_ioctl(sdp->device, cmd_in, p); } Commit Message: scsi: sg: fixup infoleak when using SG_GET_REQUEST_TABLE When calling SG_GET_REQUEST_TABLE ioctl only a half-filled table is returned; the remaining part will then contain stale kernel memory information. This patch zeroes out the entire table to avoid this issue. Signed-off-by: Hannes Reinecke <[email protected]> Reviewed-by: Bart Van Assche <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Eric Dumazet <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-200
sg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { void __user *p = (void __user *)arg; int __user *ip = p; int result, val, read_only; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; unsigned long iflags; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_ioctl: cmd=0x%x\n", (int) cmd_in)); read_only = (O_RDWR != (filp->f_flags & O_ACCMODE)); switch (cmd_in) { case SG_IO: if (atomic_read(&sdp->detaching)) return -ENODEV; if (!scsi_block_when_processing_errors(sdp->device)) return -ENXIO; if (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR)) return -EFAULT; result = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR, 1, read_only, 1, &srp); if (result < 0) return result; result = wait_event_interruptible(sfp->read_wait, (srp_done(sfp, srp) || atomic_read(&sdp->detaching))); if (atomic_read(&sdp->detaching)) return -ENODEV; write_lock_irq(&sfp->rq_list_lock); if (srp->done) { srp->done = 2; write_unlock_irq(&sfp->rq_list_lock); result = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp); return (result < 0) ? result : 0; } srp->orphan = 1; write_unlock_irq(&sfp->rq_list_lock); return result; /* -ERESTARTSYS because signal hit process */ case SG_SET_TIMEOUT: result = get_user(val, ip); if (result) return result; if (val < 0) return -EIO; if (val >= mult_frac((s64)INT_MAX, USER_HZ, HZ)) val = min_t(s64, mult_frac((s64)INT_MAX, USER_HZ, HZ), INT_MAX); sfp->timeout_user = val; sfp->timeout = mult_frac(val, HZ, USER_HZ); return 0; case SG_GET_TIMEOUT: /* N.B. User receives timeout as return value */ /* strange ..., for backward compatibility */ return sfp->timeout_user; case SG_SET_FORCE_LOW_DMA: /* * N.B. This ioctl never worked properly, but failed to * return an error value. So returning '0' to keep compability * with legacy applications. */ return 0; case SG_GET_LOW_DMA: return put_user((int) sdp->device->host->unchecked_isa_dma, ip); case SG_GET_SCSI_ID: if (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t))) return -EFAULT; else { sg_scsi_id_t __user *sg_idp = p; if (atomic_read(&sdp->detaching)) return -ENODEV; __put_user((int) sdp->device->host->host_no, &sg_idp->host_no); __put_user((int) sdp->device->channel, &sg_idp->channel); __put_user((int) sdp->device->id, &sg_idp->scsi_id); __put_user((int) sdp->device->lun, &sg_idp->lun); __put_user((int) sdp->device->type, &sg_idp->scsi_type); __put_user((short) sdp->device->host->cmd_per_lun, &sg_idp->h_cmd_per_lun); __put_user((short) sdp->device->queue_depth, &sg_idp->d_queue_depth); __put_user(0, &sg_idp->unused[0]); __put_user(0, &sg_idp->unused[1]); return 0; } case SG_SET_FORCE_PACK_ID: result = get_user(val, ip); if (result) return result; sfp->force_packid = val ? 1 : 0; return 0; case SG_GET_PACK_ID: if (!access_ok(VERIFY_WRITE, ip, sizeof (int))) return -EFAULT; read_lock_irqsave(&sfp->rq_list_lock, iflags); list_for_each_entry(srp, &sfp->rq_list, entry) { if ((1 == srp->done) && (!srp->sg_io_owned)) { read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(srp->header.pack_id, ip); return 0; } } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(-1, ip); return 0; case SG_GET_NUM_WAITING: read_lock_irqsave(&sfp->rq_list_lock, iflags); val = 0; list_for_each_entry(srp, &sfp->rq_list, entry) { if ((1 == srp->done) && (!srp->sg_io_owned)) ++val; } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); return put_user(val, ip); case SG_GET_SG_TABLESIZE: return put_user(sdp->sg_tablesize, ip); case SG_SET_RESERVED_SIZE: result = get_user(val, ip); if (result) return result; if (val < 0) return -EINVAL; val = min_t(int, val, max_sectors_bytes(sdp->device->request_queue)); mutex_lock(&sfp->f_mutex); if (val != sfp->reserve.bufflen) { if (sfp->mmap_called || sfp->res_in_use) { mutex_unlock(&sfp->f_mutex); return -EBUSY; } sg_remove_scat(sfp, &sfp->reserve); sg_build_reserve(sfp, val); } mutex_unlock(&sfp->f_mutex); return 0; case SG_GET_RESERVED_SIZE: val = min_t(int, sfp->reserve.bufflen, max_sectors_bytes(sdp->device->request_queue)); return put_user(val, ip); case SG_SET_COMMAND_Q: result = get_user(val, ip); if (result) return result; sfp->cmd_q = val ? 1 : 0; return 0; case SG_GET_COMMAND_Q: return put_user((int) sfp->cmd_q, ip); case SG_SET_KEEP_ORPHAN: result = get_user(val, ip); if (result) return result; sfp->keep_orphan = val; return 0; case SG_GET_KEEP_ORPHAN: return put_user((int) sfp->keep_orphan, ip); case SG_NEXT_CMD_LEN: result = get_user(val, ip); if (result) return result; if (val > SG_MAX_CDB_SIZE) return -ENOMEM; sfp->next_cmd_len = (val > 0) ? val : 0; return 0; case SG_GET_VERSION_NUM: return put_user(sg_version_num, ip); case SG_GET_ACCESS_COUNT: /* faked - we don't have a real access count anymore */ val = (sdp->device ? 1 : 0); return put_user(val, ip); case SG_GET_REQUEST_TABLE: if (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE)) return -EFAULT; else { sg_req_info_t *rinfo; rinfo = kzalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE, GFP_KERNEL); if (!rinfo) return -ENOMEM; read_lock_irqsave(&sfp->rq_list_lock, iflags); sg_fill_request_table(sfp, rinfo); read_unlock_irqrestore(&sfp->rq_list_lock, iflags); result = __copy_to_user(p, rinfo, SZ_SG_REQ_INFO * SG_MAX_QUEUE); result = result ? -EFAULT : 0; kfree(rinfo); return result; } case SG_EMULATED_HOST: if (atomic_read(&sdp->detaching)) return -ENODEV; return put_user(sdp->device->host->hostt->emulated, ip); case SCSI_IOCTL_SEND_COMMAND: if (atomic_read(&sdp->detaching)) return -ENODEV; if (read_only) { unsigned char opcode = WRITE_6; Scsi_Ioctl_Command __user *siocp = p; if (copy_from_user(&opcode, siocp->data, 1)) return -EFAULT; if (sg_allow_access(filp, &opcode)) return -EPERM; } return sg_scsi_ioctl(sdp->device->request_queue, NULL, filp->f_mode, p); case SG_SET_DEBUG: result = get_user(val, ip); if (result) return result; sdp->sgdebug = (char) val; return 0; case BLKSECTGET: return put_user(max_sectors_bytes(sdp->device->request_queue), ip); case BLKTRACESETUP: return blk_trace_setup(sdp->device->request_queue, sdp->disk->disk_name, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), NULL, p); case BLKTRACESTART: return blk_trace_startstop(sdp->device->request_queue, 1); case BLKTRACESTOP: return blk_trace_startstop(sdp->device->request_queue, 0); case BLKTRACETEARDOWN: return blk_trace_remove(sdp->device->request_queue); case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: case SCSI_IOCTL_PROBE_HOST: case SG_GET_TRANSFORM: case SG_SCSI_RESET: if (atomic_read(&sdp->detaching)) return -ENODEV; break; default: if (read_only) return -EPERM; /* don't know so take safe approach */ break; } result = scsi_ioctl_block_when_processing_errors(sdp->device, cmd_in, filp->f_flags & O_NDELAY); if (result) return result; return scsi_ioctl(sdp->device, cmd_in, p); }
167,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: archive_read_format_cpio_read_header(struct archive_read *a, struct archive_entry *entry) { struct cpio *cpio; const void *h; struct archive_string_conv *sconv; size_t namelength; size_t name_pad; int r; cpio = (struct cpio *)(a->format->data); sconv = cpio->opt_sconv; if (sconv == NULL) { if (!cpio->init_default_conversion) { cpio->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); cpio->init_default_conversion = 1; } sconv = cpio->sconv_default; } r = (cpio->read_header(a, cpio, entry, &namelength, &name_pad)); if (r < ARCHIVE_WARN) return (r); /* Read name from buffer. */ h = __archive_read_ahead(a, namelength + name_pad, NULL); if (h == NULL) return (ARCHIVE_FATAL); if (archive_entry_copy_pathname_l(entry, (const char *)h, namelength, sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname can't be converted from %s to current locale.", archive_string_conversion_charset_name(sconv)); r = ARCHIVE_WARN; } cpio->entry_offset = 0; __archive_read_consume(a, namelength + name_pad); /* If this is a symlink, read the link contents. */ if (archive_entry_filetype(entry) == AE_IFLNK) { h = __archive_read_ahead(a, (size_t)cpio->entry_bytes_remaining, NULL); if (h == NULL) return (ARCHIVE_FATAL); if (archive_entry_copy_symlink_l(entry, (const char *)h, (size_t)cpio->entry_bytes_remaining, sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Linkname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Linkname can't be converted from %s to " "current locale.", archive_string_conversion_charset_name(sconv)); r = ARCHIVE_WARN; } __archive_read_consume(a, cpio->entry_bytes_remaining); cpio->entry_bytes_remaining = 0; } /* XXX TODO: If the full mode is 0160200, then this is a Solaris * ACL description for the following entry. Read this body * and parse it as a Solaris-style ACL, then read the next * header. XXX */ /* Compare name to "TRAILER!!!" to test for end-of-archive. */ if (namelength == 11 && strcmp((const char *)h, "TRAILER!!!") == 0) { /* TODO: Store file location of start of block. */ archive_clear_error(&a->archive); return (ARCHIVE_EOF); } /* Detect and record hardlinks to previously-extracted entries. */ if (record_hardlink(a, cpio, entry) != ARCHIVE_OK) { return (ARCHIVE_FATAL); } return (r); } Commit Message: Reject cpio symlinks that exceed 1MB CWE ID: CWE-20
archive_read_format_cpio_read_header(struct archive_read *a, struct archive_entry *entry) { struct cpio *cpio; const void *h; struct archive_string_conv *sconv; size_t namelength; size_t name_pad; int r; cpio = (struct cpio *)(a->format->data); sconv = cpio->opt_sconv; if (sconv == NULL) { if (!cpio->init_default_conversion) { cpio->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); cpio->init_default_conversion = 1; } sconv = cpio->sconv_default; } r = (cpio->read_header(a, cpio, entry, &namelength, &name_pad)); if (r < ARCHIVE_WARN) return (r); /* Read name from buffer. */ h = __archive_read_ahead(a, namelength + name_pad, NULL); if (h == NULL) return (ARCHIVE_FATAL); if (archive_entry_copy_pathname_l(entry, (const char *)h, namelength, sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname can't be converted from %s to current locale.", archive_string_conversion_charset_name(sconv)); r = ARCHIVE_WARN; } cpio->entry_offset = 0; __archive_read_consume(a, namelength + name_pad); /* If this is a symlink, read the link contents. */ if (archive_entry_filetype(entry) == AE_IFLNK) { if (cpio->entry_bytes_remaining > 1024 * 1024) { archive_set_error(&a->archive, ENOMEM, "Rejecting malformed cpio archive: symlink contents exceed 1 megabyte"); return (ARCHIVE_FATAL); } h = __archive_read_ahead(a, (size_t)cpio->entry_bytes_remaining, NULL); if (h == NULL) return (ARCHIVE_FATAL); if (archive_entry_copy_symlink_l(entry, (const char *)h, (size_t)cpio->entry_bytes_remaining, sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Linkname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Linkname can't be converted from %s to " "current locale.", archive_string_conversion_charset_name(sconv)); r = ARCHIVE_WARN; } __archive_read_consume(a, cpio->entry_bytes_remaining); cpio->entry_bytes_remaining = 0; } /* XXX TODO: If the full mode is 0160200, then this is a Solaris * ACL description for the following entry. Read this body * and parse it as a Solaris-style ACL, then read the next * header. XXX */ /* Compare name to "TRAILER!!!" to test for end-of-archive. */ if (namelength == 11 && strcmp((const char *)h, "TRAILER!!!") == 0) { /* TODO: Store file location of start of block. */ archive_clear_error(&a->archive); return (ARCHIVE_EOF); } /* Detect and record hardlinks to previously-extracted entries. */ if (record_hardlink(a, cpio, entry) != ARCHIVE_OK) { return (ARCHIVE_FATAL); } return (r); }
167,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Session* SessionManager::GetSession(const std::string& id) const { std::map<std::string, Session*>::const_iterator it; base::AutoLock lock(map_lock_); it = map_.find(id); if (it == map_.end()) { VLOG(1) << "No such session with ID " << id; return NULL; } return it->second; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
Session* SessionManager::GetSession(const std::string& id) const { std::map<std::string, Session*>::const_iterator it; base::AutoLock lock(map_lock_); it = map_.find(id); if (it == map_.end()) return NULL; return it->second; }
170,463
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = (cdf_secid_t)(sat->sat_len * size); DPRINTF(("Chain:")); for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); errno = EFTYPE; return (size_t)-1; } if (sid > maxsector) { DPRINTF(("Sector %d > %d\n", sid, maxsector)); errno = EFTYPE; return (size_t)-1; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); return (size_t)-1; } DPRINTF(("\n")); return i; } Commit Message: Fix incorrect bounds check for sector count. (Francisco Alonso and Jan Kaluza at RedHat) CWE ID: CWE-20
cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = (cdf_secid_t)((sat->sat_len * size) / sizeof(maxsector)); DPRINTF(("Chain:")); for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); errno = EFTYPE; return (size_t)-1; } if (sid >= maxsector) { DPRINTF(("Sector %d >= %d\n", sid, maxsector)); errno = EFTYPE; return (size_t)-1; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); return (size_t)-1; } DPRINTF(("\n")); return i; }
166,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_rock_ridge_inode_internal(struct iso_directory_record *de, struct inode *inode, int flags) { int symlink_len = 0; int cnt, sig; unsigned int reloc_block; struct inode *reloc; struct rock_ridge *rr; int rootflag; struct rock_state rs; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); if (flags & RR_REGARD_XA) { rs.chr += 14; rs.len -= 14; if (rs.len < 0) rs.len = 0; } repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { #ifndef CONFIG_ZISOFS /* No flag for SF or ZF */ case SIG('R', 'R'): if ((rr->u.RR.flags[0] & (RR_PX | RR_TF | RR_SL | RR_CL)) == 0) goto out; break; #endif case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('E', 'R'): ISOFS_SB(inode->i_sb)->s_rock = 1; printk(KERN_DEBUG "ISO 9660 Extensions: "); { int p; for (p = 0; p < rr->u.ER.len_id; p++) printk("%c", rr->u.ER.data[p]); } printk("\n"); break; case SIG('P', 'X'): inode->i_mode = isonum_733(rr->u.PX.mode); set_nlink(inode, isonum_733(rr->u.PX.n_links)); i_uid_write(inode, isonum_733(rr->u.PX.uid)); i_gid_write(inode, isonum_733(rr->u.PX.gid)); break; case SIG('P', 'N'): { int high, low; high = isonum_733(rr->u.PN.dev_high); low = isonum_733(rr->u.PN.dev_low); /* * The Rock Ridge standard specifies that if * sizeof(dev_t) <= 4, then the high field is * unused, and the device number is completely * stored in the low field. Some writers may * ignore this subtlety, * and as a result we test to see if the entire * device number is * stored in the low field, and use that. */ if ((low & ~0xff) && high == 0) { inode->i_rdev = MKDEV(low >> 8, low & 0xff); } else { inode->i_rdev = MKDEV(high, low); } } break; case SIG('T', 'F'): /* * Some RRIP writers incorrectly place ctime in the * TF_CREATE field. Try to handle this correctly for * either case. */ /* Rock ridge never appears on a High Sierra disk */ cnt = 0; if (rr->u.TF.flags & TF_CREATE) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } if (rr->u.TF.flags & TF_MODIFY) { inode->i_mtime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_mtime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ACCESS) { inode->i_atime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_atime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ATTRIBUTES) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } break; case SIG('S', 'L'): { int slen; struct SL_component *slp; struct SL_component *oldslp; slen = rr->len - 5; slp = &rr->u.SL.link; inode->i_size = symlink_len; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: inode->i_size += slp->len; break; case 2: inode->i_size += 1; break; case 4: inode->i_size += 2; break; case 8: rootflag = 1; inode->i_size += 1; break; default: printk("Symlink component flag " "not implemented\n"); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *) (((char *)slp) + slp->len + 2); if (slen < 2) { if (((rr->u.SL. flags & 1) != 0) && ((oldslp-> flags & 1) == 0)) inode->i_size += 1; break; } /* * If this component record isn't * continued, then append a '/'. */ if (!rootflag && (oldslp->flags & 1) == 0) inode->i_size += 1; } } symlink_len = inode->i_size; break; case SIG('R', 'E'): printk(KERN_WARNING "Attempt to read inode for " "relocated directory\n"); goto out; case SIG('C', 'L'): if (flags & RR_RELOC_DE) { printk(KERN_ERR "ISOFS: Recursive directory relocation " "is not supported\n"); goto eio; } reloc_block = isonum_733(rr->u.CL.location); if (reloc_block == ISOFS_I(inode)->i_iget5_block && ISOFS_I(inode)->i_iget5_offset == 0) { printk(KERN_ERR "ISOFS: Directory relocation points to " "itself\n"); goto eio; } ISOFS_I(inode)->i_first_extent = reloc_block; reloc = isofs_iget_reloc(inode->i_sb, reloc_block, 0); if (IS_ERR(reloc)) { ret = PTR_ERR(reloc); goto out; } inode->i_mode = reloc->i_mode; set_nlink(inode, reloc->i_nlink); inode->i_uid = reloc->i_uid; inode->i_gid = reloc->i_gid; inode->i_rdev = reloc->i_rdev; inode->i_size = reloc->i_size; inode->i_blocks = reloc->i_blocks; inode->i_atime = reloc->i_atime; inode->i_ctime = reloc->i_ctime; inode->i_mtime = reloc->i_mtime; iput(reloc); break; #ifdef CONFIG_ZISOFS case SIG('Z', 'F'): { int algo; if (ISOFS_SB(inode->i_sb)->s_nocompress) break; algo = isonum_721(rr->u.ZF.algorithm); if (algo == SIG('p', 'z')) { int block_shift = isonum_711(&rr->u.ZF.parms[1]); if (block_shift > 17) { printk(KERN_WARNING "isofs: " "Can't handle ZF block " "size of 2^%d\n", block_shift); } else { /* * Note: we don't change * i_blocks here */ ISOFS_I(inode)->i_file_format = isofs_file_compressed; /* * Parameters to compression * algorithm (header size, * block size) */ ISOFS_I(inode)->i_format_parm[0] = isonum_711(&rr->u.ZF.parms[0]); ISOFS_I(inode)->i_format_parm[1] = isonum_711(&rr->u.ZF.parms[1]); inode->i_size = isonum_733(rr->u.ZF. real_size); } } else { printk(KERN_WARNING "isofs: Unknown ZF compression " "algorithm: %c%c\n", rr->u.ZF.algorithm[0], rr->u.ZF.algorithm[1]); } break; } #endif default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) ret = 0; out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } Commit Message: isofs: Fix unchecked printing of ER records We didn't check length of rock ridge ER records before printing them. Thus corrupted isofs image can cause us to access and print some memory behind the buffer with obvious consequences. Reported-and-tested-by: Carl Henrik Lunde <[email protected]> CC: [email protected] Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20
parse_rock_ridge_inode_internal(struct iso_directory_record *de, struct inode *inode, int flags) { int symlink_len = 0; int cnt, sig; unsigned int reloc_block; struct inode *reloc; struct rock_ridge *rr; int rootflag; struct rock_state rs; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); if (flags & RR_REGARD_XA) { rs.chr += 14; rs.len -= 14; if (rs.len < 0) rs.len = 0; } repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { #ifndef CONFIG_ZISOFS /* No flag for SF or ZF */ case SIG('R', 'R'): if ((rr->u.RR.flags[0] & (RR_PX | RR_TF | RR_SL | RR_CL)) == 0) goto out; break; #endif case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('E', 'R'): /* Invalid length of ER tag id? */ if (rr->u.ER.len_id + offsetof(struct rock_ridge, u.ER.data) > rr->len) goto out; ISOFS_SB(inode->i_sb)->s_rock = 1; printk(KERN_DEBUG "ISO 9660 Extensions: "); { int p; for (p = 0; p < rr->u.ER.len_id; p++) printk("%c", rr->u.ER.data[p]); } printk("\n"); break; case SIG('P', 'X'): inode->i_mode = isonum_733(rr->u.PX.mode); set_nlink(inode, isonum_733(rr->u.PX.n_links)); i_uid_write(inode, isonum_733(rr->u.PX.uid)); i_gid_write(inode, isonum_733(rr->u.PX.gid)); break; case SIG('P', 'N'): { int high, low; high = isonum_733(rr->u.PN.dev_high); low = isonum_733(rr->u.PN.dev_low); /* * The Rock Ridge standard specifies that if * sizeof(dev_t) <= 4, then the high field is * unused, and the device number is completely * stored in the low field. Some writers may * ignore this subtlety, * and as a result we test to see if the entire * device number is * stored in the low field, and use that. */ if ((low & ~0xff) && high == 0) { inode->i_rdev = MKDEV(low >> 8, low & 0xff); } else { inode->i_rdev = MKDEV(high, low); } } break; case SIG('T', 'F'): /* * Some RRIP writers incorrectly place ctime in the * TF_CREATE field. Try to handle this correctly for * either case. */ /* Rock ridge never appears on a High Sierra disk */ cnt = 0; if (rr->u.TF.flags & TF_CREATE) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } if (rr->u.TF.flags & TF_MODIFY) { inode->i_mtime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_mtime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ACCESS) { inode->i_atime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_atime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ATTRIBUTES) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } break; case SIG('S', 'L'): { int slen; struct SL_component *slp; struct SL_component *oldslp; slen = rr->len - 5; slp = &rr->u.SL.link; inode->i_size = symlink_len; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: inode->i_size += slp->len; break; case 2: inode->i_size += 1; break; case 4: inode->i_size += 2; break; case 8: rootflag = 1; inode->i_size += 1; break; default: printk("Symlink component flag " "not implemented\n"); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *) (((char *)slp) + slp->len + 2); if (slen < 2) { if (((rr->u.SL. flags & 1) != 0) && ((oldslp-> flags & 1) == 0)) inode->i_size += 1; break; } /* * If this component record isn't * continued, then append a '/'. */ if (!rootflag && (oldslp->flags & 1) == 0) inode->i_size += 1; } } symlink_len = inode->i_size; break; case SIG('R', 'E'): printk(KERN_WARNING "Attempt to read inode for " "relocated directory\n"); goto out; case SIG('C', 'L'): if (flags & RR_RELOC_DE) { printk(KERN_ERR "ISOFS: Recursive directory relocation " "is not supported\n"); goto eio; } reloc_block = isonum_733(rr->u.CL.location); if (reloc_block == ISOFS_I(inode)->i_iget5_block && ISOFS_I(inode)->i_iget5_offset == 0) { printk(KERN_ERR "ISOFS: Directory relocation points to " "itself\n"); goto eio; } ISOFS_I(inode)->i_first_extent = reloc_block; reloc = isofs_iget_reloc(inode->i_sb, reloc_block, 0); if (IS_ERR(reloc)) { ret = PTR_ERR(reloc); goto out; } inode->i_mode = reloc->i_mode; set_nlink(inode, reloc->i_nlink); inode->i_uid = reloc->i_uid; inode->i_gid = reloc->i_gid; inode->i_rdev = reloc->i_rdev; inode->i_size = reloc->i_size; inode->i_blocks = reloc->i_blocks; inode->i_atime = reloc->i_atime; inode->i_ctime = reloc->i_ctime; inode->i_mtime = reloc->i_mtime; iput(reloc); break; #ifdef CONFIG_ZISOFS case SIG('Z', 'F'): { int algo; if (ISOFS_SB(inode->i_sb)->s_nocompress) break; algo = isonum_721(rr->u.ZF.algorithm); if (algo == SIG('p', 'z')) { int block_shift = isonum_711(&rr->u.ZF.parms[1]); if (block_shift > 17) { printk(KERN_WARNING "isofs: " "Can't handle ZF block " "size of 2^%d\n", block_shift); } else { /* * Note: we don't change * i_blocks here */ ISOFS_I(inode)->i_file_format = isofs_file_compressed; /* * Parameters to compression * algorithm (header size, * block size) */ ISOFS_I(inode)->i_format_parm[0] = isonum_711(&rr->u.ZF.parms[0]); ISOFS_I(inode)->i_format_parm[1] = isonum_711(&rr->u.ZF.parms[1]); inode->i_size = isonum_733(rr->u.ZF. real_size); } } else { printk(KERN_WARNING "isofs: Unknown ZF compression " "algorithm: %c%c\n", rr->u.ZF.algorithm[0], rr->u.ZF.algorithm[1]); } break; } #endif default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) ret = 0; out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; }
166,782
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: CCThreadProxy::CCThreadProxy(CCLayerTreeHost* layerTreeHost) : m_commitRequested(false) , m_layerTreeHost(layerTreeHost) , m_compositorIdentifier(-1) , m_started(false) , m_lastExecutedBeginFrameAndCommitSequenceNumber(-1) , m_numBeginFrameAndCommitsIssuedOnCCThread(0) { TRACE_EVENT("CCThreadProxy::CCThreadProxy", this, 0); ASSERT(isMainThread()); } Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests https://bugs.webkit.org/show_bug.cgi?id=70161 Reviewed by David Levin. Source/WebCore: Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was destroyed. This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the CCThreadProxy have been drained. Covered by the now-enabled CCLayerTreeHostTest* unit tests. * WebCore.gypi: * platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added. (WebCore::CCScopedMainThreadProxy::create): (WebCore::CCScopedMainThreadProxy::postTask): (WebCore::CCScopedMainThreadProxy::shutdown): (WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy): (WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown): * platform/graphics/chromium/cc/CCThreadProxy.cpp: (WebCore::CCThreadProxy::CCThreadProxy): (WebCore::CCThreadProxy::~CCThreadProxy): (WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread): * platform/graphics/chromium/cc/CCThreadProxy.h: Source/WebKit/chromium: Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor thread scheduling draws by itself. * tests/CCLayerTreeHostTest.cpp: (::CCLayerTreeHostTest::timeout): (::CCLayerTreeHostTest::clearTimeout): (::CCLayerTreeHostTest::CCLayerTreeHostTest): (::CCLayerTreeHostTest::onEndTest): (::CCLayerTreeHostTest::TimeoutTask::TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::clearTest): (::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::Run): (::CCLayerTreeHostTest::runTest): (::CCLayerTreeHostTest::doBeginTest): (::CCLayerTreeHostTestThreadOnly::runTest): (::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread): git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
CCThreadProxy::CCThreadProxy(CCLayerTreeHost* layerTreeHost) : m_commitRequested(false) , m_layerTreeHost(layerTreeHost) , m_compositorIdentifier(-1) , m_started(false) , m_lastExecutedBeginFrameAndCommitSequenceNumber(-1) , m_numBeginFrameAndCommitsIssuedOnCCThread(0) , m_mainThreadProxy(CCScopedMainThreadProxy::create()) { TRACE_EVENT("CCThreadProxy::CCThreadProxy", this, 0); ASSERT(isMainThread()); }
170,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: LinkChangeSerializerMarkupAccumulator::LinkChangeSerializerMarkupAccumulator(PageSerializer* serializer, Document* document, Vector<Node*>* nodes, LinkLocalPathMap* links, String directoryName) : SerializerMarkupAccumulator(serializer, document, nodes) , m_replaceLinks(links) , m_directoryName(directoryName) { } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
LinkChangeSerializerMarkupAccumulator::LinkChangeSerializerMarkupAccumulator(PageSerializer* serializer, Document* document, Vector<Node*>* nodes, LinkLocalPathMap* links, String directoryName)
171,562
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int createFromTiffRgba(TIFF * tif, gdImagePtr im) { int a; int x, y; int alphaBlendingFlag = 0; int color; int width = im->sx; int height = im->sy; uint32 *buffer; uint32 rgba; /* switch off colour merging on target gd image just while we write out * content - we want to preserve the alpha data until the user chooses * what to do with the image */ alphaBlendingFlag = im->alphaBlendingFlag; gdImageAlphaBlending(im, 0); buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height); if (!buffer) { return GD_FAILURE; } TIFFReadRGBAImage(tif, width, height, buffer, 0); for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { /* if it doesn't already exist, allocate a new colour, * else use existing one */ rgba = buffer[(y * width + x)]; a = (0xff - TIFFGetA(rgba)) / 2; color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a); /* set pixel colour to this colour */ gdImageSetPixel(im, x, height - y - 1, color); } } gdFree(buffer); /* now reset colour merge for alpha blending routines */ gdImageAlphaBlending(im, alphaBlendingFlag); return GD_SUCCESS; } Commit Message: Fix invalid read in gdImageCreateFromTiffPtr() tiff_invalid_read.tiff is corrupt, and causes an invalid read in gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case, dynamicGetbuf() is called with a negative dp->pos, but also positive buffer overflows have to be handled, in which case 0 has to be returned (cf. commit 75e29a9). Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create the image, because the return value of TIFFReadRGBAImage() is not checked. We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails. This issue had been reported by Ibrahim El-Sayed to [email protected]. CVE-2016-6911 CWE ID: CWE-125
static int createFromTiffRgba(TIFF * tif, gdImagePtr im) { int a; int x, y; int alphaBlendingFlag = 0; int color; int width = im->sx; int height = im->sy; uint32 *buffer; uint32 rgba; int success; /* switch off colour merging on target gd image just while we write out * content - we want to preserve the alpha data until the user chooses * what to do with the image */ alphaBlendingFlag = im->alphaBlendingFlag; gdImageAlphaBlending(im, 0); buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height); if (!buffer) { return GD_FAILURE; } success = TIFFReadRGBAImage(tif, width, height, buffer, 1); if (success) { for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { /* if it doesn't already exist, allocate a new colour, * else use existing one */ rgba = buffer[(y * width + x)]; a = (0xff - TIFFGetA(rgba)) / 2; color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a); /* set pixel colour to this colour */ gdImageSetPixel(im, x, height - y - 1, color); } } } gdFree(buffer); /* now reset colour merge for alpha blending routines */ gdImageAlphaBlending(im, alphaBlendingFlag); return success; }
168,822
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Image *AutoResizeImage(const Image *image,const char *option, MagickOffsetType *count,ExceptionInfo *exception) { #define MAX_SIZES 16 char *q; const char *p; Image *resized, *images; register ssize_t i; size_t sizes[MAX_SIZES]={256,192,128,96,64,48,40,32,24,16}; images=NULL; *count=0; i=0; p=option; while (*p != '\0' && i < MAX_SIZES) { size_t size; while ((isspace((int) ((unsigned char) *p)) != 0)) p++; size=(size_t)strtol(p,&q,10); if (p == q || size < 16 || size > 256) return((Image *) NULL); p=q; sizes[i++]=size; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (i==0) i=10; *count=i; for (i=0; i < *count; i++) { resized=ResizeImage(image,sizes[i],sizes[i],image->filter,exception); if (resized == (Image *) NULL) return(DestroyImageList(images)); if (images == (Image *) NULL) images=resized; else AppendImageToList(&images,resized); } return(images); } Commit Message: CWE ID: CWE-189
Image *AutoResizeImage(const Image *image,const char *option, MagickOffsetType *count,ExceptionInfo *exception) { #define MAX_SIZES 16 char *q; const char *p; Image *resized, *images; register ssize_t i; size_t sizes[MAX_SIZES]={256,192,128,96,64,48,40,32,24,16}; images=NULL; *count=0; i=0; p=option; while (*p != '\0' && i < MAX_SIZES) { size_t size; while ((isspace((int) ((unsigned char) *p)) != 0)) p++; size=(size_t)strtol(p,&q,10); if ((p == q) || (size < 16) || (size > 256)) return((Image *) NULL); p=q; sizes[i++]=size; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (i==0) i=10; *count=i; for (i=0; i < *count; i++) { resized=ResizeImage(image,sizes[i],sizes[i],image->filter,exception); if (resized == (Image *) NULL) return(DestroyImageList(images)); if (images == (Image *) NULL) images=resized; else AppendImageToList(&images,resized); } return(images); }
168,862
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok) { /*- * (0) check whether the desired fragment is available * if so: * (1) copy over the fragment to s->init_buf->data[] * (2) update s->init_num */ pitem *item; hm_fragment *frag; int al; *ok = 0; item = pqueue_peek(s->d1->buffered_messages); if (item == NULL) return 0; frag = (hm_fragment *)item->data; /* Don't return if reassembly still in progress */ if (frag->reassembly != NULL) frag->msg_header.frag_len); } Commit Message: CWE ID: CWE-399
static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok) { /*- * (0) check whether the desired fragment is available * if so: * (1) copy over the fragment to s->init_buf->data[] * (2) update s->init_num */ pitem *item; hm_fragment *frag; int al; *ok = 0; do { item = pqueue_peek(s->d1->buffered_messages); if (item == NULL) return 0; frag = (hm_fragment *)item->data; if (frag->msg_header.seq < s->d1->handshake_read_seq) { /* This is a stale message that has been buffered so clear it */ pqueue_pop(s->d1->buffered_messages); dtls1_hm_fragment_free(frag); pitem_free(item); item = NULL; frag = NULL; } } while (item == NULL); /* Don't return if reassembly still in progress */ if (frag->reassembly != NULL) frag->msg_header.frag_len); }
165,197
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod2(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); size_t argsCount = exec->argumentCount(); if (argsCount <= 1) { impl->overloadedMethod(objArg); return JSValue::encode(jsUndefined()); } int intArg(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(objArg, intArg); 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
static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod2(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); size_t argsCount = exec->argumentCount(); if (argsCount <= 1) { impl->overloadedMethod(objArg); return JSValue::encode(jsUndefined()); } int intArg(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(objArg, intArg); return JSValue::encode(jsUndefined()); }
170,601
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void btif_av_event_free_data(btif_sm_event_t event, void* p_data) { switch (event) { case BTA_AV_META_MSG_EVT: { tBTA_AV* av = (tBTA_AV*)p_data; osi_free_and_reset((void**)&av->meta_msg.p_data); if (av->meta_msg.p_msg) { if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) { osi_free(av->meta_msg.p_msg->vendor.p_vendor_data); } osi_free_and_reset((void**)&av->meta_msg.p_msg); } } break; default: break; } } Commit Message: DO NOT MERGE AVRC: Copy browse.p_browse_data in btif_av_event_deep_copy p_msg_src->browse.p_browse_data is not copied, but used after the original pointer is freed Bug: 109699112 Test: manual Change-Id: I1d014eb9a8911da6913173a9b11218bf1c89e16e (cherry picked from commit 1d9a58768e6573899c7e80c2b3f52e22f2d8f58b) CWE ID: CWE-416
static void btif_av_event_free_data(btif_sm_event_t event, void* p_data) { switch (event) { case BTA_AV_META_MSG_EVT: { tBTA_AV* av = (tBTA_AV*)p_data; osi_free_and_reset((void**)&av->meta_msg.p_data); if (av->meta_msg.p_msg) { if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) { osi_free(av->meta_msg.p_msg->vendor.p_vendor_data); } if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_BROWSE) { osi_free(av->meta_msg.p_msg->browse.p_browse_data); } osi_free_and_reset((void**)&av->meta_msg.p_msg); } } break; default: break; } }
174,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename, const std::string& mime_type) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); ScopedJavaLocalRef<jstring> jmime_type = ConvertUTF8ToJavaString(env, mime_type); Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename, jmime_type); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254
void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename, void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename); }
171,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport unsigned char *DetachBlob(BlobInfo *blob_info) { unsigned char *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; return(data); } Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43 CWE ID: CWE-416
MagickExport unsigned char *DetachBlob(BlobInfo *blob_info) { unsigned char *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); blob_info->data=NULL; RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; return(data); }
169,563
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool asn1_write_OctetString(struct asn1_data *data, const void *p, size_t length) { asn1_push_tag(data, ASN1_OCTET_STRING); asn1_write(data, p, length); asn1_pop_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_OctetString(struct asn1_data *data, const void *p, size_t length) { if (!asn1_push_tag(data, ASN1_OCTET_STRING)) return false; if (!asn1_write(data, p, length)) return false; return asn1_pop_tag(data); }
164,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjConstructorFunctionClassMethod2(ExecState* exec) { if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); return JSValue::encode(JSTestObj::classMethod2(exec)); } 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
EncodedJSValue JSC_HOST_CALL jsTestObjConstructorFunctionClassMethod2(ExecState* exec) { if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); return JSValue::encode(JSTestObj::classMethod2(exec)); }
170,579