project
stringclasses
633 values
commit_id
stringlengths
7
81
target
int64
0
1
func
stringlengths
5
484k
cwe
stringclasses
131 values
big_vul_idx
float64
0
189k
idx
int64
0
522k
hash
stringlengths
34
39
size
float64
1
24k
message
stringlengths
0
11.5k
dataset
stringclasses
1 value
tcpdump
c24922e692a52121e853a84ead6b9337f4c08a94
1
rx_cache_insert(netdissect_options *ndo, const u_char *bp, const struct ip *ip, int dport) { struct rx_cache_entry *rxent; const struct rx_header *rxh = (const struct rx_header *) bp; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) return; rxent = &rx_cache[rx_cache_next]; if (++rx_cache_next >= RX_CACHE_SIZE) rx_cache_next = 0; rxent->callnum = EXTRACT_32BITS(&rxh->callNumber); UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t)); UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t)); rxent->dport = dport; rxent->serviceId = EXTRACT_32BITS(&rxh->serviceId); rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header)); }
CWE-125
183,018
9,637
15665195569772353281937519342289828739
null
null
null
linux
04197b341f23b908193308b8d63d17ff23232598
1
__xfs_get_blocks( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create, bool direct, bool dax_fault) { struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; xfs_fileoff_t offset_fsb, end_fsb; int error = 0; int lockmode = 0; struct xfs_bmbt_irec imap; int nimaps = 1; xfs_off_t offset; ssize_t size; int new = 0; bool is_cow = false; bool need_alloc = false; BUG_ON(create && !direct); if (XFS_FORCED_SHUTDOWN(mp)) return -EIO; offset = (xfs_off_t)iblock << inode->i_blkbits; ASSERT(bh_result->b_size >= (1 << inode->i_blkbits)); size = bh_result->b_size; if (!create && offset >= i_size_read(inode)) return 0; /* * Direct I/O is usually done on preallocated files, so try getting * a block mapping without an exclusive lock first. */ lockmode = xfs_ilock_data_map_shared(ip); ASSERT(offset <= mp->m_super->s_maxbytes); if (offset + size > mp->m_super->s_maxbytes) size = mp->m_super->s_maxbytes - offset; end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + size); offset_fsb = XFS_B_TO_FSBT(mp, offset); if (create && direct && xfs_is_reflink_inode(ip)) is_cow = xfs_reflink_find_cow_mapping(ip, offset, &imap, &need_alloc); if (!is_cow) { error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap, &nimaps, XFS_BMAPI_ENTIRE); /* * Truncate an overwrite extent if there's a pending CoW * reservation before the end of this extent. This * forces us to come back to get_blocks to take care of * the CoW. */ if (create && direct && nimaps && imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && !ISUNWRITTEN(&imap)) xfs_reflink_trim_irec_to_next_cow(ip, offset_fsb, &imap); } ASSERT(!need_alloc); if (error) goto out_unlock; /* for DAX, we convert unwritten extents directly */ if (create && (!nimaps || (imap.br_startblock == HOLESTARTBLOCK || imap.br_startblock == DELAYSTARTBLOCK) || (IS_DAX(inode) && ISUNWRITTEN(&imap)))) { /* * xfs_iomap_write_direct() expects the shared lock. It * is unlocked on return. */ if (lockmode == XFS_ILOCK_EXCL) xfs_ilock_demote(ip, lockmode); error = xfs_iomap_write_direct(ip, offset, size, &imap, nimaps); if (error) return error; new = 1; trace_xfs_get_blocks_alloc(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_DELALLOC, &imap); } else if (nimaps) { trace_xfs_get_blocks_found(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_OVERWRITE, &imap); xfs_iunlock(ip, lockmode); } else { trace_xfs_get_blocks_notfound(ip, offset, size); goto out_unlock; } if (IS_DAX(inode) && create) { ASSERT(!ISUNWRITTEN(&imap)); /* zeroing is not needed at a higher layer */ new = 0; } /* trim mapping down to size requested */ xfs_map_trim_size(inode, iblock, bh_result, &imap, offset, size); /* * For unwritten extents do not report a disk address in the buffered * read case (treat as if we're reading into a hole). */ if (imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && (create || !ISUNWRITTEN(&imap))) { if (create && direct && !is_cow) { error = xfs_bounce_unaligned_dio_write(ip, offset_fsb, &imap); if (error) return error; } xfs_map_buffer(inode, bh_result, &imap, offset); if (ISUNWRITTEN(&imap)) set_buffer_unwritten(bh_result); /* direct IO needs special help */ if (create) { if (dax_fault) ASSERT(!ISUNWRITTEN(&imap)); else xfs_map_direct(inode, bh_result, &imap, offset, is_cow); } } /* * If this is a realtime file, data may be on a different device. * to that pointed to from the buffer_head b_bdev currently. */ bh_result->b_bdev = xfs_find_bdev_for_inode(inode); /* * If we previously allocated a block out beyond eof and we are now * coming back to use it then we will need to flag it as new even if it * has a disk address. * * With sub-block writes into unwritten extents we also need to mark * the buffer as new so that the unwritten parts of the buffer gets * correctly zeroed. */ if (create && ((!buffer_mapped(bh_result) && !buffer_uptodate(bh_result)) || (offset >= i_size_read(inode)) || (new || ISUNWRITTEN(&imap)))) set_buffer_new(bh_result); BUG_ON(direct && imap.br_startblock == DELAYSTARTBLOCK); return 0; out_unlock: xfs_iunlock(ip, lockmode); return error; }
CWE-362
183,036
9,638
195875716643763590011242271015838893949
null
null
null
linux
f9432c5ec8b1e9a09b9b0e5569e3c73db8de432a
1
static int rfcomm_get_dev_list(void __user *arg) { struct rfcomm_dev *dev; struct rfcomm_dev_list_req *dl; struct rfcomm_dev_info *di; int n = 0, size, err; u16 dev_num; BT_DBG(""); if (get_user(dev_num, (u16 __user *) arg)) return -EFAULT; if (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di)) return -EINVAL; size = sizeof(*dl) + dev_num * sizeof(*di); dl = kmalloc(size, GFP_KERNEL); if (!dl) return -ENOMEM; di = dl->dev_info; spin_lock(&rfcomm_dev_lock); list_for_each_entry(dev, &rfcomm_dev_list, list) { if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags)) continue; (di + n)->id = dev->id; (di + n)->flags = dev->flags; (di + n)->state = dev->dlc->state; (di + n)->channel = dev->channel; bacpy(&(di + n)->src, &dev->src); bacpy(&(di + n)->dst, &dev->dst); if (++n >= dev_num) break; } spin_unlock(&rfcomm_dev_lock); dl->dev_num = n; size = sizeof(*dl) + n * sizeof(*di); err = copy_to_user(arg, dl, size); kfree(dl); return err ? -EFAULT : 0; }
CWE-200
183,070
9,641
139069687710975938684381653063038131800
null
null
null
linux
7b789836f434c87168eab067cfbed1ec4783dffd
1
static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir) { memcpy(&p->sel, &xp->selector, sizeof(p->sel)); memcpy(&p->lft, &xp->lft, sizeof(p->lft)); memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft)); p->priority = xp->priority; p->index = xp->index; p->sel.family = xp->family; p->dir = dir; p->action = xp->action; p->flags = xp->flags; p->share = XFRM_SHARE_ANY; /* XXX xp->share */ }
CWE-200
183,074
9,642
24315986261003056593467728379763855831
null
null
null
sgminer
78cc408369bdbbd440196c93574098d1482efbce
1
static bool parse_reconnect(struct pool *pool, json_t *val) { char *sockaddr_url, *stratum_port, *tmp; char *url, *port, address[256]; if (opt_disable_client_reconnect) { applog(LOG_WARNING, "Stratum client.reconnect forbidden, aborting."); return false; } memset(address, 0, 255); url = (char *)json_string_value(json_array_get(val, 0)); if (!url) url = pool->sockaddr_url; port = (char *)json_string_value(json_array_get(val, 1)); if (!port) port = pool->stratum_port; sprintf(address, "%s:%s", url, port); if (!extract_sockaddr(address, &sockaddr_url, &stratum_port)) return false; applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address); clear_pool_work(pool); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); tmp = pool->sockaddr_url; pool->sockaddr_url = sockaddr_url; pool->stratum_url = pool->sockaddr_url; free(tmp); tmp = pool->stratum_port; pool->stratum_port = stratum_port; free(tmp); mutex_unlock(&pool->stratum_lock); if (!restart_stratum(pool)) { pool_failed(pool); return false; } return true; }
CWE-119
183,079
9,643
122543891288543544622800839772109429388
null
null
null
libgd
1ccfe21e14c4d18336f9da8515cd17db88c3de61
1
BGD_DECLARE(gdImagePtr) gdImageCropThreshold(gdImagePtr im, const unsigned int color, const float threshold) { const int width = gdImageSX(im); const int height = gdImageSY(im); int x,y; int match; gdRect crop; crop.x = 0; crop.y = 0; crop.width = 0; crop.height = 0; /* Pierre: crop everything sounds bad */ if (threshold > 100.0) { return NULL; } /* TODO: Add gdImageGetRowPtr and works with ptr at the row level * for the true color and palette images * new formats will simply work with ptr */ match = 1; for (y = 0; match && y < height; y++) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } /* Pierre * Nothing to do > bye * Duplicate the image? */ if (y == height - 1) { return NULL; } crop.y = y -1; match = 1; for (y = height - 1; match && y >= 0; y--) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x, y), threshold)) > 0; } } if (y == 0) { crop.height = height - crop.y + 1; } else { crop.height = y - crop.y + 2; } match = 1; for (x = 0; match && x < width; x++) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.x = x - 1; match = 1; for (x = width - 1; match && x >= 0; x--) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.width = x - crop.x + 2; return gdImageCrop(im, &crop); }
CWE-20
183,116
9,646
58602749696991852943700324313298545781
null
null
null
wireshark
11edc83b98a61e890d7bb01855389d40e984ea82
1
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; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); while(1) { /* The last packet is not delimited by an empty line, but by EOF * So accept EOF as a valid delimiter too */ if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) { break; } /* * Skip blanks. * The number of blanks is not fixed - for wireless * interfaces, there may be 14 extra spaces before * the hex data. */ for (p = &line[0]; g_ascii_isspace(*p); p++) ; /* packets are delimited with empty lines */ if (*p == '\0') { break; } n = parse_single_hex_dump_line(p, pd, offset); /* the smallest packet has a length of 6 bytes, if * the first hex-data is less then check whether * it is a info-line and act accordingly */ if (offset == 0 && n < 6) { if (info_line(line)) { if (++i <= NETSCREEN_MAX_INFOLINES) { continue; } } else { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } } /* If there is no more data and the line was not empty, * then there must be an error in the file */ if (n == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } /* Adjust the offset to the data that was just added to the buffer */ offset += n; /* If there was more hex-data than was announced in the len=x * header, then then there must be an error in the file */ if (offset > pkt_len) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: too much hex-data"); return FALSE; } } /* * Determine the encapsulation type, based on the * first 4 characters of the interface name * * XXX convert this to a 'case' structure when adding more * (non-ethernet) interfacetypes */ if (strncmp(cap_int, "adsl", 4) == 0) { /* The ADSL interface can be bridged with or without * PPP encapsulation. Check whether the first six bytes * of the hex data are the same as the destination mac * address in the header. If they are, assume ethernet * LinkLayer or else PPP */ g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x", pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]); if (strncmp(dststr, cap_dst, 12) == 0) phdr->pkt_encap = WTAP_ENCAP_ETHERNET; else phdr->pkt_encap = WTAP_ENCAP_PPP; } else if (strncmp(cap_int, "seri", 4) == 0) phdr->pkt_encap = WTAP_ENCAP_PPP; else phdr->pkt_encap = WTAP_ENCAP_ETHERNET; phdr->caplen = offset; return TRUE; }
CWE-20
183,134
9,649
147371450414689873099723695508004643141
null
null
null
linux
4c185ce06dca14f5cea192f5a2c981ef50663f2b
1
static ssize_t aio_setup_single_vector(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t len, struct iovec *iovec) { if (unlikely(!access_ok(!rw, buf, len))) return -EFAULT; iovec->iov_base = buf; iovec->iov_len = len; *nr_segs = 1; return 0; }
183,174
9,655
1764598624184633205579466501182004427
null
null
null
linux
d11662f4f798b50d8c8743f433842c3e40fe3378
1
static ssize_t snd_timer_user_read(struct file *file, char __user *buffer, size_t count, loff_t *offset) { struct snd_timer_user *tu; long result = 0, unit; int qhead; int err = 0; tu = file->private_data; unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read); spin_lock_irq(&tu->qlock); while ((long)count - result >= unit) { while (!tu->qused) { wait_queue_t wait; if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) { err = -EAGAIN; goto _error; } set_current_state(TASK_INTERRUPTIBLE); init_waitqueue_entry(&wait, current); add_wait_queue(&tu->qchange_sleep, &wait); spin_unlock_irq(&tu->qlock); schedule(); spin_lock_irq(&tu->qlock); remove_wait_queue(&tu->qchange_sleep, &wait); if (tu->disconnected) { err = -ENODEV; goto _error; } if (signal_pending(current)) { err = -ERESTARTSYS; goto _error; } } qhead = tu->qhead++; tu->qhead %= tu->queue_size; tu->qused--; spin_unlock_irq(&tu->qlock); mutex_lock(&tu->ioctl_lock); if (tu->tread) { if (copy_to_user(buffer, &tu->tqueue[qhead], sizeof(struct snd_timer_tread))) err = -EFAULT; } else { if (copy_to_user(buffer, &tu->queue[qhead], sizeof(struct snd_timer_read))) err = -EFAULT; } mutex_unlock(&tu->ioctl_lock); spin_lock_irq(&tu->qlock); if (err < 0) goto _error; result += unit; buffer += unit; } _error: spin_unlock_irq(&tu->qlock); return result > 0 ? result : err; }
CWE-200
183,180
9,656
56027744184134705699771719834420502922
null
null
null
ImageMagick
acee073df34aa4d491bf5cb74d3a15fc80f0a3aa
1
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* 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); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:quality-layers"); if (option == (const char *) NULL) option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image, (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if ((image_info->number_scenes != 0) && (image_info->scene != 0)) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene-1); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0)) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->compression=JPEG2000Compression; if (jp2_image->color_space == 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } else if (jp2_image->color_space == 3) SetImageColorspace(image,Rec601YCbCrColorspace); if (jp2_image->numcomps > 3) image->matte=MagickTrue; if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
CWE-20
183,195
9,659
145640868358261095635083056598479271866
null
null
null
FFmpeg
611b35627488a8d0763e75c25ee0875c5b7987dd
1
static int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; if (cid <= 0) continue; dctx->remaining = avpriv_dnxhd_get_frame_size(cid); if (dctx->remaining <= 0) { dctx->remaining = ff_dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (dctx->remaining <= 0) return dctx->remaining; } if (buf_size - i + 47 >= dctx->remaining) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; return END_NOT_FOUND; }
CWE-476
183,217
9,660
86046191373808073451244271890342921078
null
null
null
ImageMagick
e87af64b1ff1635a32d9b6162f1b0e260fb54ed9
1
static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); }
CWE-787
183,274
9,667
273458965762153777387946204487724852277
null
null
null
ImageMagick
280215b9936d145dd5ee91403738ccce1333cab1
1
static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q), exception),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); }
CWE-125
183,289
9,669
42358738219081615034659307522733389056
null
null
null
ImageMagick
504ada82b6fa38a30c846c1c29116af7290decb2
1
static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status, cubemap = MagickFalse, volume = MagickFalse, matte; CompressionType compression; DDSInfo dds_info; DDSDecoder *decoder; size_t n, num_images; /* 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); } /* Initialize image structure. */ if (ReadDDSInfo(image, &dds_info) != MagickTrue) { ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) cubemap = MagickTrue; if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) volume = MagickTrue; (void) SeekBlob(image, 128, SEEK_SET); /* Determine pixel format */ if (dds_info.pixelformat.flags & DDPF_RGB) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { matte = MagickTrue; decoder = ReadUncompressedRGBA; } else { matte = MagickTrue; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { /* Not sure how to handle this */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } else { matte = MagickFalse; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_FOURCC) { switch (dds_info.pixelformat.fourcc) { case FOURCC_DXT1: { matte = MagickFalse; compression = DXT1Compression; decoder = ReadDXT1; break; } case FOURCC_DXT3: { matte = MagickTrue; compression = DXT3Compression; decoder = ReadDXT3; break; } case FOURCC_DXT5: { matte = MagickTrue; compression = DXT5Compression; decoder = ReadDXT5; break; } default: { /* Unknown FOURCC */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } } } else { /* Neither compressed nor uncompressed... thus unsupported */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } num_images = 1; if (cubemap) { /* Determine number of faces defined in the cubemap */ num_images = 0; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; } if (volume) num_images = dds_info.depth; for (n = 0; n < num_images; n++) { if (n != 0) { /* Start a new image */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } image->matte = matte; image->compression = compression; image->columns = dds_info.width; image->rows = dds_info.height; image->storage_class = DirectClass; image->endian = LSBEndian; image->depth = 8; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((decoder)(image, &dds_info, exception) != MagickTrue) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
CWE-20
183,325
9,672
213987347007398425586591215259076686063
null
null
null
linux
251e22abde21833b3d29577e4d8c7aaccd650eee
1
static int amd_gpio_probe(struct platform_device *pdev) { int ret = 0; int irq_base; struct resource *res; struct amd_gpio *gpio_dev; gpio_dev = devm_kzalloc(&pdev->dev, sizeof(struct amd_gpio), GFP_KERNEL); if (!gpio_dev) return -ENOMEM; spin_lock_init(&gpio_dev->lock); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "Failed to get gpio io resource.\n"); return -EINVAL; } gpio_dev->base = devm_ioremap_nocache(&pdev->dev, res->start, resource_size(res)); if (!gpio_dev->base) return -ENOMEM; irq_base = platform_get_irq(pdev, 0); if (irq_base < 0) { dev_err(&pdev->dev, "Failed to get gpio IRQ.\n"); return -EINVAL; } gpio_dev->pdev = pdev; gpio_dev->gc.direction_input = amd_gpio_direction_input; gpio_dev->gc.direction_output = amd_gpio_direction_output; gpio_dev->gc.get = amd_gpio_get_value; gpio_dev->gc.set = amd_gpio_set_value; gpio_dev->gc.set_debounce = amd_gpio_set_debounce; gpio_dev->gc.dbg_show = amd_gpio_dbg_show; gpio_dev->gc.base = 0; gpio_dev->gc.label = pdev->name; gpio_dev->gc.owner = THIS_MODULE; gpio_dev->gc.parent = &pdev->dev; gpio_dev->gc.ngpio = TOTAL_NUMBER_OF_PINS; #if defined(CONFIG_OF_GPIO) gpio_dev->gc.of_node = pdev->dev.of_node; #endif gpio_dev->groups = kerncz_groups; gpio_dev->ngroups = ARRAY_SIZE(kerncz_groups); amd_pinctrl_desc.name = dev_name(&pdev->dev); gpio_dev->pctrl = pinctrl_register(&amd_pinctrl_desc, &pdev->dev, gpio_dev); if (IS_ERR(gpio_dev->pctrl)) { dev_err(&pdev->dev, "Couldn't register pinctrl driver\n"); return PTR_ERR(gpio_dev->pctrl); } ret = gpiochip_add_data(&gpio_dev->gc, gpio_dev); if (ret) goto out1; ret = gpiochip_add_pin_range(&gpio_dev->gc, dev_name(&pdev->dev), 0, 0, TOTAL_NUMBER_OF_PINS); if (ret) { dev_err(&pdev->dev, "Failed to add pin range\n"); goto out2; } ret = gpiochip_irqchip_add(&gpio_dev->gc, &amd_gpio_irqchip, 0, handle_simple_irq, IRQ_TYPE_NONE); if (ret) { dev_err(&pdev->dev, "could not add irqchip\n"); ret = -ENODEV; goto out2; } gpiochip_set_chained_irqchip(&gpio_dev->gc, &amd_gpio_irqchip, irq_base, amd_gpio_irq_handler); platform_set_drvdata(pdev, gpio_dev); dev_dbg(&pdev->dev, "amd gpio driver loaded\n"); return ret; out2: gpiochip_remove(&gpio_dev->gc); out1: pinctrl_unregister(gpio_dev->pctrl); return ret; }
CWE-415
183,344
9,673
152429198517298717789110595345518101910
null
null
null
jasper
f25486c3d4aa472fec79150f2c41ed4333395d3d
1
static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; }
CWE-125
183,350
9,674
71544139196461255653661758021165209461
null
null
null
ImageMagick6
a77d8d97f5a7bced0468f0b08798c83fb67427bc
1
MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) { mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) mean_image->columns; x++) { PixelInfo mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetPixelInfo(image,&mean_pixel); GetPixelInfoPixel(image,p,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; PixelInfo sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetPixelInfo(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelInfo pixel; status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.alpha+=pixel.alpha; count++; } } } } gamma=1.0/count; mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.alpha=gamma*sum_pixel.alpha; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); p+=GetPixelChannels(image); q+=GetPixelChannels(mean_image); } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); }
CWE-369
183,361
9,676
143092893080934220411000934079975861187
null
null
null
ImageMagick6
e92040ea6ee2a844ebfd2344174076795a4787bd
1
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
CWE-119
183,374
9,677
296982318816803246371742553907326568834
null
null
null
ImageMagick6
29efd648f38b73a64d73f14cd2019d869a585888
1
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
CWE-119
183,375
9,678
29796776391938396370144855802609739630
null
null
null
ImageMagick
bfa3b9610c83227894c92b0d312ad327fceb6241
1
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], format, magick[MaxTextExtent]; const char *value; IndexPacket index; MagickBooleanType status; MagickOffsetType scene; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *pixels, *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ max_value=GetQuantumRange(image->depth); packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MaxTextExtent); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,&image->exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,&image->exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MaxTextExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MaxTextExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,&image->exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MaxTextExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent); if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent); break; } default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MaxTextExtent); break; } } if (image->matte != MagickFalse) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n", type); (void) WriteBlobString(image,buffer); } /* Convert to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToLong(index)); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)), ScaleQuantumToChar(GetPixelGreen(p)), ScaleQuantumToChar(GetPixelBlue(p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)), ScaleQuantumToShort(GetPixelGreen(p)), ScaleQuantumToShort(GetPixelBlue(p))); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)), ScaleQuantumToLong(GetPixelGreen(p)), ScaleQuantumToLong(GetPixelBlue(p))); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 32) pixel=ScaleQuantumToLong(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
CWE-119
183,376
9,679
135724383670322901534041908196575399639
null
null
null
ImageMagick6
35ccb468ee2dcbe8ce9cf1e2f1957acc27f54c34
1
static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox "BoundingBox:" #define BeginDocument "BeginDocument:" #define BeginXMPPacket "<?xpacket begin=" #define EndXMPPacket "<?xpacket end=" #define ICCProfile "BeginICCProfile:" #define CMYKCustomColor "CMYKCustomColor:" #define CMYKProcessColor "CMYKProcessColor:" #define DocumentMedia "DocumentMedia:" #define DocumentCustomColors "DocumentCustomColors:" #define DocumentProcessColors "DocumentProcessColors:" #define EndDocument "EndDocument:" #define HiResBoundingBox "HiResBoundingBox:" #define ImageData "ImageData:" #define PageBoundingBox "PageBoundingBox:" #define LanguageLevel "LanguageLevel:" #define PageMedia "PageMedia:" #define Pages "Pages:" #define PhotoshopProfile "BeginPhotoshop:" #define PostscriptLevel "!PS-" #define RenderPostscriptText " Rendering Postscript... " #define SpotColor "+ " char command[MagickPathExtent], *density, filename[MagickPathExtent], geometry[MagickPathExtent], input_filename[MagickPathExtent], message[MagickPathExtent], *options, postscript_filename[MagickPathExtent]; const char *option; const DelegateInfo *delegate_info; GeometryInfo geometry_info; Image *image, *next, *postscript_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, fitPage, skip, status; MagickStatusType flags; PointInfo delta, resolution; RectangleInfo page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; short int hex_digits[256]; size_t length; ssize_t count, priority; StringInfo *profile; unsigned long columns, extent, language_level, pages, rows, scene, spotcolor; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Initialize hex values. */ (void) memset(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution=image->resolution; page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5); /* Determine page geometry from the Postscript bounding box. */ (void) memset(&bounds,0,sizeof(bounds)); (void) memset(command,0,sizeof(command)); cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; (void) memset(&hires_bounds,0,sizeof(hires_bounds)); columns=0; rows=0; priority=0; rows=0; extent=0; spotcolor=0; language_level=1; pages=(~0UL); skip=MagickFalse; p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0) { (void) SetImageProperty(image,"ps:Level",command+4,exception); if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse) pages=1; } if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0) (void) sscanf(command,LanguageLevel " %lu",&language_level); if (LocaleNCompare(Pages,command,strlen(Pages)) == 0) (void) sscanf(command,Pages " %lu",&pages); if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0) (void) sscanf(command,ImageData " %lu %lu",&columns,&rows); /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (LocaleNCompare(DocumentProcessColors,command,length) == 0) { if ((GlobExpression(command,"*Cyan*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Magenta*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Yellow*",MagickTrue) != MagickFalse)) cmyk=MagickTrue; } if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; length=strlen(DocumentCustomColors); if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) || (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) || (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)) { char property[MagickPathExtent], *value; register char *q; /* Note spot names. */ (void) FormatLocaleString(property,MagickPathExtent, "ps:SpotColor-%.20g",(double) (spotcolor++)); for (q=command; *q != '\0'; q++) if (isspace((int) (unsigned char) *q) != 0) break; value=ConstantString(q); (void) SubstituteString(&value,"(",""); (void) SubstituteString(&value,")",""); (void) StripString(value); if (*value != '\0') (void) SetImageProperty(image,property,value,exception); value=DestroyString(value); continue; } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0) { count=(ssize_t) sscanf(command,BoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0) { count=(ssize_t) sscanf(command,DocumentMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0) { count=(ssize_t) sscanf(command,HiResBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0) { count=(ssize_t) sscanf(command,PageBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0) { count=(ssize_t) sscanf(command,PageMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) if (i == (ssize_t) priority) continue; hires_bounds=bounds; priority=i; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set Postscript render geometry. */ (void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"ps:HiResBoundingBox",geometry,exception); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"eps:fit-page"); if (option != (char *) NULL) { char *page_geometry; page_geometry=GetPageGeometry(option); flags=ParseMetaGeometry(page_geometry,&page.x,&page.y,&page.width, &page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->resolution.y/ delta.y) -0.5); page_geometry=DestroyString(page_geometry); fitPage=MagickTrue; } if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {" "dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n" "<</UseCIEColor true>>setpagedevice\n",MagickPathExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MagickPathExtent]; (void) FormatLocaleString(translate_geometry,MagickPathExtent, "%g %g translate\n",-bounds.x1,-bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MagickPathExtent,"%gx%g",resolution.x, resolution.y); (void) FormatLocaleString(options,MagickPathExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MagickPathExtent]; (void) FormatLocaleString(pages,MagickPathExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g ",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MagickPathExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,"eps:use-cropbox"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,"-dEPSCrop ",MagickPathExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dEPSFitPage ", MagickPathExtent); } (void) CopyMagickString(filename,read_info->filename,MagickPathExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MagickPathExtent); (void) FormatLocaleString(command,MagickPathExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePostscriptDelegate(read_info->verbose,command,message,exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename,exception); if ((status == MagickFalse) || (IsPostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command," -c showpage",MagickPathExtent); status=InvokePostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename,exception); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename,exception); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(), DelegateError,"PostscriptDelegateFailed","`%s'",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } (void) SeekBlob(image,0,SEEK_SET); for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0) { unsigned char *datum; /* Read ICC profile. */ profile=AcquireStringInfo(MagickPathExtent); datum=GetStringInfoDatum(profile); for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(profile)) { SetStringInfoLength(profile,(size_t) i << 1); datum=GetStringInfoDatum(profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(profile,(size_t) i+1); (void) SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); continue; } if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0) { unsigned char *q; /* Read Photoshop profile. */ count=(ssize_t) sscanf(command,PhotoshopProfile " %lu",&extent); if (count != 1) continue; length=extent; if ((MagickSizeType) length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); profile=BlobToStringInfo((const void *) NULL,length); if (profile != (StringInfo *) NULL) { q=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) *q++=(unsigned char) ProfileInteger(image,hex_digits); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); } continue; } if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=(ssize_t) GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,(size_t) (i+1)); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,(size_t) i); (void) SetImageProfile(image,"xmp",profile,exception); profile=DestroyStringInfo(profile); continue; } } (void) CloseBlob(image); if (image_info->number_scenes != 0) { Image *clone_image; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename, MagickPathExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MagickPathExtent); if (columns != 0) postscript_image->magick_columns=columns; if (rows != 0) postscript_image->magick_rows=rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); }
CWE-399
183,380
9,680
175368670304185890355664815111216546110
null
null
null
openjpeg
cbe7384016083eac16078b359acd7a842253d503
1
static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = 0U; while (y < height) { int c = getc(IN); if (c == EOF) { break; } if (c) { /* encoded mode */ int j; OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU)); } } else { /* absolute mode */ c = getc(IN); if (c == EOF) { break; } if (c == 0x00) { /* EOL */ x = 0; y++; pix = pData + y * stride; } else if (c == 0x01) { /* EOP */ break; } else if (c == 0x02) { /* MOVE by dxdy */ c = getc(IN); x += (OPJ_UINT32)c; c = getc(IN); y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else { /* 03 .. 255 : absolute mode */ int j; OPJ_UINT8 c1 = 0U; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { if ((j & 1) == 0) { c1 = (OPJ_UINT8)getc(IN); } *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU)); } if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */ getc(IN); } } } } /* while(y < height) */ return OPJ_TRUE; }
CWE-400
183,382
9,681
107959287325417326672401838052399357450
null
null
null
Chrome
a1ce1b69e269a7e61ea0bf0691b90be0cbe9b4c5
1
bool parseXMLDocumentFragment(const String& chunk, DocumentFragment* fragment, Element* parent) { if (!chunk.length()) return true; XMLTokenizer tokenizer(fragment, parent); tokenizer.initializeParserContext(chunk.utf8().data()); xmlParseContent(tokenizer.m_context); tokenizer.endDocument(); long bytesProcessed = xmlByteConsumed(tokenizer.m_context); if (bytesProcessed == -1 || ((unsigned long)bytesProcessed) == sizeof(UChar) * chunk.length()) return false; return tokenizer.m_context->wellFormed || xmlCtxtGetLastError(tokenizer.m_context) == 0; }
183,423
9,682
327345793910478659635481840932155119678
null
null
null
Chrome
04cca6c05e4923f1b91e0dddf053e088456d8645
1
bool InlineFlowBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, int x, int y, int tx, int ty) { IntRect overflowRect(visualOverflowRect()); flipForWritingMode(overflowRect); overflowRect.move(tx, ty); if (!overflowRect.intersects(result.rectForPoint(x, y))) return false; for (InlineBox* curr = lastChild(); curr; curr = curr->prevOnLine()) { if ((curr->renderer()->isText() || !curr->boxModelObject()->hasSelfPaintingLayer()) && curr->nodeAtPoint(request, result, x, y, tx, ty)) { renderer()->updateHitTestResult(result, IntPoint(x - tx, y - ty)); return true; } } FloatPoint boxOrigin = locationIncludingFlipping(); boxOrigin.move(tx, ty); FloatRect rect(boxOrigin, IntSize(width(), height())); if (visibleToHitTesting() && rect.intersects(result.rectForPoint(x, y))) { renderer()->updateHitTestResult(result, flipForWritingMode(IntPoint(x - tx, y - ty))); // Don't add in m_x or m_y here, we want coords in the containing block's space. if (!result.addNodeToRectBasedTestResult(renderer()->node(), x, y, rect)) return true; } return false; }
183,496
9,690
17255026778268589404378903341664608303
null
null
null
Chrome
99844692ee805d18d5ee7fd9c62f14d2dffa2e06
1
void InterstitialPage::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::NAV_ENTRY_PENDING: Disable(); DCHECK(!resource_dispatcher_host_notified_); TakeActionOnResourceDispatcher(CANCEL); break; case NotificationType::RENDER_WIDGET_HOST_DESTROYED: if (action_taken_ == NO_ACTION) { RenderViewHost* rvh = Source<RenderViewHost>(source).ptr(); DCHECK(rvh->process()->id() == original_child_id_ && rvh->routing_id() == original_rvh_id_); TakeActionOnResourceDispatcher(CANCEL); } break; case NotificationType::TAB_CONTENTS_DESTROYED: case NotificationType::NAV_ENTRY_COMMITTED: if (action_taken_ == NO_ACTION) { DontProceed(); } else { Hide(); } break; default: NOTREACHED(); } }
183,517
9,695
339234853320163838751051011920468311148
null
null
null
Chrome
60c9d8a39e4aa78dd51c236bd1b2c4f17c9d27fe
1
bool TextAutosizer::processSubtree(RenderObject* layoutRoot) { if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->printing() || !m_document->page()) return false; Frame* mainFrame = m_document->page()->mainFrame(); TextAutosizingWindowInfo windowInfo; windowInfo.windowSize = m_document->settings()->textAutosizingWindowSizeOverride(); if (windowInfo.windowSize.isEmpty()) { bool includeScrollbars = !InspectorInstrumentation::shouldApplyScreenWidthOverride(mainFrame); windowInfo.windowSize = mainFrame->view()->visibleContentRect(includeScrollbars).size(); // FIXME: Check that this is always in logical (density-independent) pixels (see wkbug.com/87440). } windowInfo.minLayoutSize = mainFrame->view()->layoutSize(); for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->parent()) { if (!frame->view()->isInChildFrameWithFrameFlattening()) windowInfo.minLayoutSize = windowInfo.minLayoutSize.shrunkTo(frame->view()->layoutSize()); } RenderBlock* container = layoutRoot->isRenderBlock() ? toRenderBlock(layoutRoot) : layoutRoot->containingBlock(); while (container && !isAutosizingContainer(container)) container = container->containingBlock(); RenderBlock* cluster = container; while (cluster && (!isAutosizingContainer(cluster) || !isAutosizingCluster(cluster))) cluster = cluster->containingBlock(); processCluster(cluster, container, layoutRoot, windowInfo); return true; }
CWE-119
183,628
9,710
58579830367491528863193785858549376462
null
null
null
Chrome
08b630e66e042af3fe80015509b3238c2679ea40
1
bool RenderMenuList::multiple() { return toHTMLSelectElement(node())->multiple(); }
CWE-399
183,757
9,726
153962476287418375907692635599539562770
null
null
null
Chrome
9eb1fd426a04adac0906c81ed88f1089969702ba
1
void BeginInstallWithManifestFunction::OnParseSuccess( const SkBitmap& icon, DictionaryValue* parsed_manifest) { CHECK(parsed_manifest); icon_ = icon; parsed_manifest_.reset(parsed_manifest); std::string init_errors; dummy_extension_ = Extension::Create( FilePath(), Extension::INTERNAL, *static_cast<DictionaryValue*>(parsed_manifest_.get()), Extension::NO_FLAGS, &init_errors); if (!dummy_extension_.get()) { OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError)); return; } if (icon_.empty()) icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app()); ShowExtensionInstallDialog(profile(), this, dummy_extension_.get(), &icon_, dummy_extension_->GetPermissionMessageStrings(), ExtensionInstallUI::INSTALL_PROMPT); }
CWE-20
183,862
9,737
31286386419319730761109454010057337527
null
null
null
Chrome
ce891a86763d3540e2612be26938a6163310efe0
1
void ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); RenderThread* thread = RenderThread::current(); thread->AddFilter(new DevToolsAgentFilter()); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); thread->AddObserver(phishing_classifier_.get()); thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); }
CWE-264
183,905
9,744
161105270804386397824982741439965824618
null
null
null
Chrome
bf04ad0dae9f4f479f90fd2b38f634ffbaf434b4
1
bool PPVarToNPVariant(PP_Var var, NPVariant* result) { switch (var.type) { case PP_VARTYPE_UNDEFINED: VOID_TO_NPVARIANT(*result); break; case PP_VARTYPE_NULL: NULL_TO_NPVARIANT(*result); break; case PP_VARTYPE_BOOL: BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result); break; case PP_VARTYPE_INT32: INT32_TO_NPVARIANT(var.value.as_int, *result); break; case PP_VARTYPE_DOUBLE: DOUBLE_TO_NPVARIANT(var.value.as_double, *result); break; case PP_VARTYPE_STRING: { scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); if (!string) { VOID_TO_NPVARIANT(*result); return false; } const std::string& value = string->value(); STRINGN_TO_NPVARIANT(base::strdup(value.c_str()), value.size(), *result); break; } case PP_VARTYPE_OBJECT: { scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); if (!object) { VOID_TO_NPVARIANT(*result); return false; } OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()), *result); break; } case PP_VARTYPE_ARRAY: case PP_VARTYPE_DICTIONARY: VOID_TO_NPVARIANT(*result); break; } return true; }
CWE-119
184,011
9,757
114945807708477055479861990157226132980
null
null
null
Chrome
514f93279494ec4448b34a7aeeff27eccaae983f
1
bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) { wchar_t argument[50]; for (int i = 0; argument_c[i]; ++i) argument[i] = argument_c[i]; int argument_len = lstrlen(argument); int command_line_len = lstrlen(command_line); while (command_line_len > argument_len) { wchar_t first_char = command_line[0]; wchar_t last_char = command_line[argument_len+1]; if ((first_char == L'-' || first_char == L'/') && (last_char == L' ' || last_char == 0 || last_char == L'=')) { command_line[argument_len+1] = 0; if (lstrcmpi(command_line+1, argument) == 0) { command_line[argument_len+1] = last_char; return true; } command_line[argument_len+1] = last_char; } ++command_line; --command_line_len; } return false; }
CWE-399
184,118
9,764
26055336896940780160956708348513099188
null
null
null
Chrome
60907d63ce74cbed893473c4e9bb569f47ca0c01
1
void LoginUtilsImpl::CompleteOffTheRecordLogin(const GURL& start_url) { VLOG(1) << "Completing off the record login"; UserManager::Get()->OffTheRecordUserLoggedIn(); if (CrosLibrary::Get()->EnsureLoaded()) { static const char* kForwardSwitches[] = { switches::kEnableLogging, switches::kUserDataDir, switches::kScrollPixels, switches::kEnableGView, switches::kNoFirstRun, switches::kLoginProfile, switches::kEnableTabbedOptions, switches::kCompressSystemFeedback, #if defined(USE_SECCOMP_SANDBOX) switches::kDisableSeccompSandbox, #endif }; const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); CommandLine command_line(browser_command_line.GetProgram()); command_line.CopySwitchesFrom(browser_command_line, kForwardSwitches, arraysize(kForwardSwitches)); command_line.AppendSwitch(switches::kGuestSession); command_line.AppendSwitch(switches::kIncognito); command_line.AppendSwitchASCII(switches::kLoggingLevel, kGuestModeLoggingLevel); command_line.AppendSwitchASCII( switches::kLoginUser, UserManager::Get()->logged_in_user().email()); if (start_url.is_valid()) command_line.AppendArg(start_url.spec()); CrosLibrary::Get()->GetLoginLibrary()->RestartJob( getpid(), command_line.command_line_string()); } }
184,207
9,780
120795907137336275307450882931874675247
null
null
null
Chrome
21fdcdd977e8ab479dd99c6d0d2f562dda98261d
1
bool ChromotingInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { CHECK(!initialized_); initialized_ = true; VLOG(1) << "Started ChromotingInstance::Init"; if (!media::IsMediaLibraryInitialized()) { LOG(ERROR) << "Media library not initialized."; return false; } net::EnableSSLServerSockets(); context_.Start(); scoped_refptr<FrameConsumerProxy> consumer_proxy = new FrameConsumerProxy(plugin_task_runner_); rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(), context_.decode_task_runner(), consumer_proxy); view_.reset(new PepperView(this, &context_, rectangle_decoder_.get())); consumer_proxy->Attach(view_->AsWeakPtr()); return true; }
184,222
9,783
8850003743927933543108834864180927129
null
null
null
Chrome
ad103a1564365c95f4ee4f10261f9604f91f686a
1
bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) * 4 >= std::numeric_limits<int32>::max()) return false; // Prevent overflow of signed 32-bit ints. format_ = format; width_ = width; height_ = height; return backend_->Init(this, format, width, height, init_to_zero); }
CWE-190
184,223
9,784
310179316202690939742561964102788406775
null
null
null
Chrome
1266ba494530a267ec8a21442ea1b5cae94da4fb
1
bool GrabWindowSnapshot(gfx::NativeWindow window, std::vector<unsigned char>* png_representation, const gfx::Rect& snapshot_bounds) { ui::Compositor* compositor = window->layer()->GetCompositor(); gfx::Rect read_pixels_bounds = snapshot_bounds; read_pixels_bounds.set_origin( snapshot_bounds.origin().Add(window->bounds().origin())); gfx::Rect read_pixels_bounds_in_pixel = ui::ConvertRectToPixel(window->layer(), read_pixels_bounds); DCHECK_GE(compositor->size().width(), read_pixels_bounds_in_pixel.right()); DCHECK_GE(compositor->size().height(), read_pixels_bounds_in_pixel.bottom()); DCHECK_LE(0, read_pixels_bounds.x()); DCHECK_LE(0, read_pixels_bounds.y()); SkBitmap bitmap; if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel)) return false; unsigned char* pixels = reinterpret_cast<unsigned char*>(bitmap.getPixels()); gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA, read_pixels_bounds_in_pixel.size(), bitmap.rowBytes(), true, std::vector<gfx::PNGCodec::Comment>(), png_representation); return true; }
184,334
9,794
179395606435042728747164698559166334668
null
null
null
Chrome
fd4edbad91f65bfab79276390de5db59b079fd3b
1
InternalWebIntentsDispatcherTest() { replied_ = 0; }
184,335
9,795
133460065752429298465052297632363652752
null
null
null
Chrome
9939d35f9827ed0929646607cbdb071af627ac38
1
xsltCompileLocationPathPattern(xsltParserContextPtr ctxt, int novar) { SKIP_BLANKS; if ((CUR == '/') && (NXT(1) == '/')) { /* * since we reverse the query * a leading // can be safely ignored */ NEXT; NEXT; ctxt->comp->priority = 0.5; /* '//' means not 0 priority */ xsltCompileRelativePathPattern(ctxt, NULL, novar); } else if (CUR == '/') { /* * We need to find root as the parent */ NEXT; SKIP_BLANKS; PUSH(XSLT_OP_ROOT, NULL, NULL, novar); if ((CUR != 0) && (CUR != '|')) { PUSH(XSLT_OP_PARENT, NULL, NULL, novar); xsltCompileRelativePathPattern(ctxt, NULL, novar); } } else if (CUR == '*') { xsltCompileRelativePathPattern(ctxt, NULL, novar); } else if (CUR == '@') { xsltCompileRelativePathPattern(ctxt, NULL, novar); } else { xmlChar *name; name = xsltScanNCName(ctxt); if (name == NULL) { xsltTransformError(NULL, NULL, NULL, "xsltCompileLocationPathPattern : Name expected\n"); ctxt->error = 1; return; } SKIP_BLANKS; if ((CUR == '(') && !xmlXPathIsNodeType(name)) { xsltCompileIdKeyPattern(ctxt, name, 1, novar, 0); if ((CUR == '/') && (NXT(1) == '/')) { PUSH(XSLT_OP_ANCESTOR, NULL, NULL, novar); NEXT; NEXT; SKIP_BLANKS; xsltCompileRelativePathPattern(ctxt, NULL, novar); } else if (CUR == '/') { PUSH(XSLT_OP_PARENT, NULL, NULL, novar); NEXT; SKIP_BLANKS; xsltCompileRelativePathPattern(ctxt, NULL, novar); } return; } xsltCompileRelativePathPattern(ctxt, name, novar); } error: return; }
CWE-399
184,490
9,815
156995017980789132302395143559223129360
null
null
null
Chrome
0b74c338bd286e51a004981e746cc212c2d5423c
1
int PpapiPluginMain(const content::MainFunctionParams& parameters) { const CommandLine& command_line = parameters.command_line; #if defined(OS_WIN) g_target_services = parameters.sandbox_info->target_services; #endif if (command_line.HasSwitch(switches::kPpapiStartupDialog)) { if (g_target_services) base::debug::WaitForDebugger(2*60, false); else ChildProcess::WaitForDebugger("Ppapi"); } MessageLoop main_message_loop; base::PlatformThread::SetName("CrPPAPIMain"); #if defined(OS_LINUX) content::InitializeSandbox(); #endif ChildProcess ppapi_process; ppapi_process.set_main_thread( new PpapiThread(parameters.command_line, false)); // Not a broker. main_message_loop.Run(); return 0; }
184,508
9,817
79297633435255954495201343229479802094
null
null
null
Chrome
9b9a9f33f0a26f40d083be85a539dd7963adfc9b
1
MediaStreamImpl::~MediaStreamImpl() { DCHECK(!peer_connection_handler_); if (dependency_factory_.get()) dependency_factory_->ReleasePeerConnectionFactory(); if (network_manager_) { if (chrome_worker_thread_.IsRunning()) { chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &MediaStreamImpl::DeleteIpcNetworkManager, base::Unretained(this))); } else { NOTREACHED() << "Worker thread not running."; } } }
CWE-399
184,584
9,824
149244836860547964928954766916643808872
null
null
null
Chrome
76e6e7c63aaa8e30e4143b8db9fc7d754812e718
1
std::string ProcessRawBytesWithSeparators(const unsigned char* data, size_t data_length, char hex_separator, char line_separator) { static const char kHexChars[] = "0123456789ABCDEF"; std::string ret; size_t kMin = 0U; ret.reserve(std::max(kMin, data_length * 3 - 1)); for (size_t i = 0; i < data_length; ++i) { unsigned char b = data[i]; ret.push_back(kHexChars[(b >> 4) & 0xf]); ret.push_back(kHexChars[b & 0xf]); if (i + 1 < data_length) { if ((i + 1) % 16 == 0) ret.push_back(line_separator); else ret.push_back(hex_separator); } } return ret; }
184,606
9,825
22421597809741221552582833961033465018
null
null
null
Chrome
2953a669ec0a32a25c6250d34bf895ec0eb63d27
1
static HB_Bool myanmar_shape_syllable(HB_Bool openType, HB_ShaperItem *item, HB_Bool invalid) { /* */ #ifndef NO_OPENTYPE const int availableGlyphs = item->num_glyphs; #endif const HB_UChar16 *uc = item->string + item->item.pos; int vowel_e = -1; int kinzi = -1; int medial_ra = -1; int base = -1; int i; int len = 0; unsigned short reordered[32]; unsigned char properties[32]; enum { AboveForm = 0x01, PreForm = 0x02, PostForm = 0x04, BelowForm = 0x08 }; HB_Bool lastWasVirama = FALSE; int basePos = -1; memset(properties, 0, 32*sizeof(unsigned char)); /* according to the table the max length of a syllable should be around 14 chars */ assert(item->item.length < 32); #ifdef MYANMAR_DEBUG printf("original:"); for (i = 0; i < (int)item->item.length; i++) { printf(" %d: %4x", i, uc[i]); } #endif for (i = 0; i < (int)item->item.length; ++i) { HB_UChar16 chr = uc[i]; if (chr == Mymr_C_VOWEL_E) { vowel_e = i; continue; } if (i == 0 && chr == Mymr_C_NGA && i + 2 < (int)item->item.length && uc[i+1] == Mymr_C_VIRAMA) { int mc = getMyanmarCharClass(uc[i+2]); /*MMDEBUG("maybe kinzi: mc=%x", mc);*/ if ((mc & Mymr_CF_CONSONANT) == Mymr_CF_CONSONANT) { kinzi = i; continue; } } if (base >= 0 && chr == Mymr_C_VIRAMA && i + 1 < (int)item->item.length && uc[i+1] == Mymr_C_RA) { medial_ra = i; continue; } if (base < 0) base = i; } MMDEBUG("\n base=%d, vowel_e=%d, kinzi=%d, medial_ra=%d", base, vowel_e, kinzi, medial_ra); /* write vowel_e if found */ if (vowel_e >= 0) { reordered[0] = Mymr_C_VOWEL_E; len = 1; } /* write medial_ra */ if (medial_ra >= 0) { reordered[len] = Mymr_C_VIRAMA; reordered[len+1] = Mymr_C_RA; properties[len] = PreForm; properties[len+1] = PreForm; len += 2; } /* shall we add a dotted circle? If in the position in which the base should be (first char in the string) there is a character that has the Dotted circle flag (a character that cannot be a base) then write a dotted circle */ if (invalid) { reordered[len] = C_DOTTED_CIRCLE; ++len; } /* copy the rest of the syllable to the output, inserting the kinzi at the correct place */ for (i = 0; i < (int)item->item.length; ++i) { hb_uint16 chr = uc[i]; MymrCharClass cc; if (i == vowel_e) continue; if (i == medial_ra || i == kinzi) { ++i; continue; } cc = getMyanmarCharClass(uc[i]); if (kinzi >= 0 && i > base && (cc & Mymr_CF_AFTER_KINZI)) { reordered[len] = Mymr_C_NGA; reordered[len+1] = Mymr_C_VIRAMA; properties[len-1] = AboveForm; properties[len] = AboveForm; len += 2; kinzi = -1; } if (lastWasVirama) { int prop = 0; switch(cc & Mymr_CF_POS_MASK) { case Mymr_CF_POS_BEFORE: prop = PreForm; break; case Mymr_CF_POS_BELOW: prop = BelowForm; break; case Mymr_CF_POS_ABOVE: prop = AboveForm; break; case Mymr_CF_POS_AFTER: prop = PostForm; break; default: break; } properties[len-1] = prop; properties[len] = prop; if(basePos >= 0 && basePos == len-2) properties[len-2] = prop; } lastWasVirama = (chr == Mymr_C_VIRAMA); if(i == base) basePos = len; if ((chr != Mymr_C_SIGN_ZWNJ && chr != Mymr_C_SIGN_ZWJ) || !len) { reordered[len] = chr; ++len; } } if (kinzi >= 0) { reordered[len] = Mymr_C_NGA; reordered[len+1] = Mymr_C_VIRAMA; properties[len] = AboveForm; properties[len+1] = AboveForm; len += 2; } if (!item->font->klass->convertStringToGlyphIndices(item->font, reordered, len, item->glyphs, &item->num_glyphs, item->item.bidiLevel % 2)) return FALSE; MMDEBUG("after shaping: len=%d", len); for (i = 0; i < len; i++) { item->attributes[i].mark = FALSE; item->attributes[i].clusterStart = FALSE; item->attributes[i].justification = 0; item->attributes[i].zeroWidth = FALSE; MMDEBUG(" %d: %4x property=%x", i, reordered[i], properties[i]); } /* now we have the syllable in the right order, and can start running it through open type. */ #ifndef NO_OPENTYPE if (openType) { hb_uint32 where[32]; for (i = 0; i < len; ++i) { where[i] = ~(PreSubstProperty | BelowSubstProperty | AboveSubstProperty | PostSubstProperty | CligProperty | PositioningProperties); if (properties[i] & PreForm) where[i] &= ~PreFormProperty; if (properties[i] & BelowForm) where[i] &= ~BelowFormProperty; if (properties[i] & AboveForm) where[i] &= ~AboveFormProperty; if (properties[i] & PostForm) where[i] &= ~PostFormProperty; } HB_OpenTypeShape(item, where); if (!HB_OpenTypePosition(item, availableGlyphs, /*doLogClusters*/FALSE)) return FALSE; } else #endif { MMDEBUG("Not using openType"); HB_HeuristicPosition(item); } item->attributes[0].clusterStart = TRUE; return TRUE; }
184,669
9,837
330981161693475402015375056890117255135
null
null
null
Chrome
4c46d7a5b0af9b7d320e709291b270ab7cf07e83
1
xmlXPtrEvalXPtrPart(xmlXPathParserContextPtr ctxt, xmlChar *name) { xmlChar *buffer, *cur; int len; int level; if (name == NULL) name = xmlXPathParseName(ctxt); if (name == NULL) XP_ERROR(XPATH_EXPR_ERROR); if (CUR != '(') XP_ERROR(XPATH_EXPR_ERROR); NEXT; level = 1; len = xmlStrlen(ctxt->cur); len++; buffer = (xmlChar *) xmlMallocAtomic(len * sizeof (xmlChar)); if (buffer == NULL) { xmlXPtrErrMemory("allocating buffer"); return; } cur = buffer; while (CUR != 0) { if (CUR == ')') { level--; if (level == 0) { NEXT; break; } *cur++ = CUR; } else if (CUR == '(') { level++; *cur++ = CUR; } else if (CUR == '^') { NEXT; if ((CUR == ')') || (CUR == '(') || (CUR == '^')) { *cur++ = CUR; } else { *cur++ = '^'; *cur++ = CUR; } } else { *cur++ = CUR; } NEXT; } *cur = 0; if ((level != 0) && (CUR == 0)) { xmlFree(buffer); XP_ERROR(XPTR_SYNTAX_ERROR); } if (xmlStrEqual(name, (xmlChar *) "xpointer")) { const xmlChar *left = CUR_PTR; CUR_PTR = buffer; /* * To evaluate an xpointer scheme element (4.3) we need: * context initialized to the root * context position initalized to 1 * context size initialized to 1 */ ctxt->context->node = (xmlNodePtr)ctxt->context->doc; ctxt->context->proximityPosition = 1; ctxt->context->contextSize = 1; xmlXPathEvalExpr(ctxt); CUR_PTR=left; } else if (xmlStrEqual(name, (xmlChar *) "element")) { const xmlChar *left = CUR_PTR; xmlChar *name2; CUR_PTR = buffer; if (buffer[0] == '/') { xmlXPathRoot(ctxt); xmlXPtrEvalChildSeq(ctxt, NULL); } else { name2 = xmlXPathParseName(ctxt); if (name2 == NULL) { CUR_PTR = left; xmlFree(buffer); XP_ERROR(XPATH_EXPR_ERROR); } xmlXPtrEvalChildSeq(ctxt, name2); } CUR_PTR = left; #ifdef XPTR_XMLNS_SCHEME } else if (xmlStrEqual(name, (xmlChar *) "xmlns")) { const xmlChar *left = CUR_PTR; xmlChar *prefix; xmlChar *URI; xmlURIPtr value; CUR_PTR = buffer; prefix = xmlXPathParseNCName(ctxt); if (prefix == NULL) { xmlFree(buffer); xmlFree(name); XP_ERROR(XPTR_SYNTAX_ERROR); } SKIP_BLANKS; if (CUR != '=') { xmlFree(prefix); xmlFree(buffer); xmlFree(name); XP_ERROR(XPTR_SYNTAX_ERROR); } NEXT; SKIP_BLANKS; /* @@ check escaping in the XPointer WD */ value = xmlParseURI((const char *)ctxt->cur); if (value == NULL) { xmlFree(prefix); xmlFree(buffer); xmlFree(name); XP_ERROR(XPTR_SYNTAX_ERROR); } URI = xmlSaveUri(value); xmlFreeURI(value); if (URI == NULL) { xmlFree(prefix); xmlFree(buffer); xmlFree(name); XP_ERROR(XPATH_MEMORY_ERROR); } xmlXPathRegisterNs(ctxt->context, prefix, URI); CUR_PTR = left; xmlFree(URI); xmlFree(prefix); #endif /* XPTR_XMLNS_SCHEME */ } else { xmlXPtrErr(ctxt, XML_XPTR_UNKNOWN_SCHEME, "unsupported scheme '%s'\n", name); } xmlFree(buffer); xmlFree(name); }
CWE-189
184,751
9,842
294708993167079477727006814441143562595
null
null
null
Chrome
4d77eed905ce1d00361282e8822a2a3be61d25c0
1
bool HTMLFormElement::prepareForSubmission(Event* event) { Frame* frame = document().frame(); if (m_isSubmittingOrPreparingForSubmission || !frame) return m_isSubmittingOrPreparingForSubmission; m_isSubmittingOrPreparingForSubmission = true; m_shouldSubmit = false; if (!validateInteractively(event)) { m_isSubmittingOrPreparingForSubmission = false; return false; } StringPairVector controlNamesAndValues; getTextFieldValues(controlNamesAndValues); RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), NotSubmittedByJavaScript); frame->loader()->client()->dispatchWillSendSubmitEvent(formState.release()); if (dispatchEvent(Event::createCancelableBubble(eventNames().submitEvent))) m_shouldSubmit = true; m_isSubmittingOrPreparingForSubmission = false; if (m_shouldSubmit) submit(event, true, true, NotSubmittedByJavaScript); return m_shouldSubmit; }
CWE-399
184,863
9,856
82440017099070623690793303184642183362
null
null
null
Chrome
c4a4dfb26615b5ef5e9dcc730ef43f70ce9202e2
1
void RenderThreadImpl::Shutdown() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); ChildThread::Shutdown(); if (memory_observer_) { message_loop()->RemoveTaskObserver(memory_observer_.get()); memory_observer_.reset(); } if (webkit_platform_support_) { webkit_platform_support_->web_database_observer_impl()-> WaitForAllDatabasesToClose(); } if (devtools_agent_message_filter_.get()) { RemoveFilter(devtools_agent_message_filter_.get()); devtools_agent_message_filter_ = NULL; } RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; #if defined(ENABLE_WEBRTC) RTCPeerConnectionHandler::DestructAllHandlers(); peer_connection_factory_.reset(); #endif RemoveFilter(vc_manager_->video_capture_message_filter()); vc_manager_.reset(); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_) file_thread_->Stop(); if (compositor_output_surface_filter_.get()) { RemoveFilter(compositor_output_surface_filter_.get()); compositor_output_surface_filter_ = NULL; } media_thread_.reset(); compositor_thread_.reset(); input_handler_manager_.reset(); if (input_event_filter_.get()) { RemoveFilter(input_event_filter_.get()); input_event_filter_ = NULL; } embedded_worker_dispatcher_.reset(); main_thread_indexed_db_dispatcher_.reset(); if (webkit_platform_support_) blink::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) NPChannelBase::CleanupChannels(); #endif }
CWE-362
184,868
9,857
237606688755037104963915413298007348243
null
null
null
Chrome
5b998565255a504887c6d2e90d11001a00c9d6da
1
ExtensionBookmarksTest() : client_(NULL), model_(NULL), node_(NULL), folder_(NULL) {}
CWE-399
184,878
9,858
155261079591022439091446323642568310249
null
null
null
Chrome
d57ecffa058b2af3b0678c43dce75f731550bbce
1
void ChangeListLoader::LoadAfterGetAboutResource( const DirectoryFetchInfo& directory_fetch_info, bool is_initial_load, int64 local_changestamp, google_apis::GDataErrorCode status, scoped_ptr<google_apis::AboutResource> about_resource) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FileError error = GDataToFileError(status); if (error != FILE_ERROR_OK) { OnChangeListLoadComplete(error); return; } DCHECK(about_resource); int64 remote_changestamp = about_resource->largest_change_id(); if (local_changestamp >= remote_changestamp) { if (local_changestamp > remote_changestamp) { LOG(WARNING) << "Local resource metadata is fresher than server, local = " << local_changestamp << ", server = " << remote_changestamp; } OnChangeListLoadComplete(FILE_ERROR_OK); return; } int64 start_changestamp = local_changestamp > 0 ? local_changestamp + 1 : 0; if (directory_fetch_info.empty()) { LoadChangeListFromServer(start_changestamp); } else { int64 directory_changestamp = std::max(directory_fetch_info.changestamp(), local_changestamp); util::Log(logging::LOG_INFO, "Fast-fetch start: %s; Server changestamp: %s", directory_fetch_info.ToString().c_str(), base::Int64ToString(remote_changestamp).c_str()); if (directory_changestamp >= remote_changestamp) { LoadAfterLoadDirectory(directory_fetch_info, is_initial_load, start_changestamp, FILE_ERROR_OK); return; } DirectoryFetchInfo new_directory_fetch_info( directory_fetch_info.local_id(), directory_fetch_info.resource_id(), remote_changestamp); LoadDirectoryFromServer( new_directory_fetch_info, base::Bind(&ChangeListLoader::LoadAfterLoadDirectory, weak_ptr_factory_.GetWeakPtr(), directory_fetch_info, is_initial_load, start_changestamp)); } }
185,008
9,872
1355775594347730217390963373267996670
null
null
null
Chrome
0a57375ad73780e61e1770a9d88b0529b0dbd33b
1
WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (request.url() != GURL(kSwappedOutURL) && GetContentClient()->renderer()->HandleNavigation(frame, request, type, default_policy, is_redirect)) { return WebKit::WebNavigationPolicyIgnore; } Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(frame, request)); if (is_swapped_out_) { if (request.url() != GURL(kSwappedOutURL)) { if (frame->parent() == NULL) { OpenURL(frame, request.url(), referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } return WebKit::WebNavigationPolicyIgnore; } return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); bool force_swap_due_to_flag = command_line.HasSwitch(switches::kEnableStrictSiteIsolation) || command_line.HasSwitch(switches::kSitePerProcess); if (force_swap_due_to_flag && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (!net::RegistryControlledDomainService::SameDomainOrHost(frame_url, url) || frame_url.scheme() != url.scheme()) { OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_request = renderer_preferences_.browser_handles_non_local_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (!browser_handles_request) { browser_handles_request = renderer_preferences_.browser_handles_all_top_level_requests && IsTopLevelNavigation(frame); } if (browser_handles_request) { page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool is_initial_navigation = page_id_ == -1; bool should_fork = HasWebUIScheme(url) || (cumulative_bindings & BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || (frame->isViewSourceModeEnabled() && type != WebKit::WebNavigationTypeReload); if (!should_fork && url.SchemeIs(chrome::kFileScheme)) { GURL source_url(old_url); if (is_initial_navigation && source_url.is_empty() && frame->opener()) source_url = frame->opener()->top()->document().url(); DCHECK(!source_url.is_empty()); should_fork = !source_url.SchemeIs(chrome::kFileScheme); } if (!should_fork) { should_fork = GetContentClient()->renderer()->ShouldFork( frame, url, request.httpMethod().utf8(), is_initial_navigation, &send_referrer); } if (should_fork) { OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; }
CWE-264
185,132
9,884
270273416564137113292631733315721720502
null
null
null
Chrome
85f2fcc7b577362dd1def5895d60ea70d6e6b8d0
1
void TabSpecificContentSettings::OnContentBlocked( ContentSettingsType type, const std::string& resource_identifier) { DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION) << "Geolocation settings handled by OnGeolocationPermissionSet"; content_accessed_[type] = true; std::string identifier; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableResourceContentSettings)) { identifier = resource_identifier; } if (!identifier.empty()) AddBlockedResource(type, identifier); #if defined (OS_ANDROID) if (type == CONTENT_SETTINGS_TYPE_POPUPS) { content_blocked_[type] = false; content_blockage_indicated_to_user_[type] = false; } #endif if (!content_blocked_[type]) { content_blocked_[type] = true; content::NotificationService::current()->Notify( chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, content::Source<WebContents>(web_contents()), content::NotificationService::NoDetails()); } }
CWE-20
185,203
9,888
49248163557894232599887386922179744494
null
null
null
Chrome
f96f1f27d9bc16b1a045c4fb5c8a8a82f73ece59
1
bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) { base::AutoLock auto_lock(lock_); DCHECK_EQ(state_, UNINITIALIZED); DCHECK(source); DCHECK(!sink_); DCHECK(!source_); sink_ = AudioDeviceFactory::NewOutputDevice(); DCHECK(sink_); int sample_rate = GetAudioOutputSampleRate(); DVLOG(1) << "Audio output hardware sample rate: " << sample_rate; UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate", sample_rate, media::kUnexpectedAudioSampleRate); if (std::find(&kValidOutputRates[0], &kValidOutputRates[0] + arraysize(kValidOutputRates), sample_rate) == &kValidOutputRates[arraysize(kValidOutputRates)]) { DLOG(ERROR) << sample_rate << " is not a supported output rate."; return false; } media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO; int buffer_size = 0; #if defined(OS_WIN) channel_layout = media::CHANNEL_LAYOUT_STEREO; if (sample_rate == 96000 || sample_rate == 48000) { buffer_size = (sample_rate / 100); } else { buffer_size = 2 * 440; } if (base::win::GetVersion() < base::win::VERSION_VISTA) { buffer_size = 3 * buffer_size; DLOG(WARNING) << "Extending the output buffer size by a factor of three " << "since Windows XP has been detected."; } #elif defined(OS_MACOSX) channel_layout = media::CHANNEL_LAYOUT_MONO; if (sample_rate == 48000) { buffer_size = 480; } else { buffer_size = 440; } #elif defined(OS_LINUX) || defined(OS_OPENBSD) channel_layout = media::CHANNEL_LAYOUT_MONO; buffer_size = 480; #else DLOG(ERROR) << "Unsupported platform"; return false; #endif params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, sample_rate, 16, buffer_size); buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]); source_ = source; source->SetRenderFormat(params_); sink_->Initialize(params_, this); sink_->SetSourceRenderView(source_render_view_id_); sink_->Start(); state_ = PAUSED; UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout", channel_layout, media::CHANNEL_LAYOUT_MAX); UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer", buffer_size, kUnexpectedAudioBufferSize); AddHistogramFramesPerBuffer(buffer_size); return true; }
CWE-119
185,205
9,889
158651565407137832296525074062255890830
null
null
null
Chrome
137458c8680c51fe9d3984ded2ef50a45a667b8b
1
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; }
CWE-119
185,303
9,901
328679834534134321485433283584758560415
null
null
null
Chrome
b2006ac87cec58363090e7d5e10d5d9e3bbda9f9
1
static bool CheckMov(const uint8* buffer, int buffer_size) { RCHECK(buffer_size > 8); int offset = 0; while (offset + 8 < buffer_size) { int atomsize = Read32(buffer + offset); uint32 atomtype = Read32(buffer + offset + 4); switch (atomtype) { case TAG('f','t','y','p'): case TAG('p','d','i','n'): case TAG('m','o','o','v'): case TAG('m','o','o','f'): case TAG('m','f','r','a'): case TAG('m','d','a','t'): case TAG('f','r','e','e'): case TAG('s','k','i','p'): case TAG('m','e','t','a'): case TAG('m','e','c','o'): case TAG('s','t','y','p'): case TAG('s','i','d','x'): case TAG('s','s','i','x'): case TAG('p','r','f','t'): case TAG('b','l','o','c'): break; default: return false; } if (atomsize == 1) { if (offset + 16 > buffer_size) break; if (Read32(buffer + offset + 8) != 0) break; // Offset is way past buffer size. atomsize = Read32(buffer + offset + 12); } if (atomsize <= 0) break; // Indicates the last atom or length too big. offset += atomsize; } return true; }
CWE-189
185,314
9,903
82572215792595663465898448627607146335
null
null
null
Chrome
2327c7044eeabc2e70700ff7f752e4b2e2978657
1
void InitOnIOThread(const std::string& mime_type) { PluginServiceImpl* plugin_service = PluginServiceImpl::GetInstance(); std::vector<WebPluginInfo> plugins; plugin_service->GetPluginInfoArray( GURL(), mime_type, false, &plugins, NULL); base::FilePath plugin_path; if (!plugins.empty()) // May be empty for some tests. plugin_path = plugins[0].path; DCHECK_CURRENTLY_ON(BrowserThread::IO); remove_start_time_ = base::Time::Now(); is_removing_ = true; AddRef(); PepperPluginInfo* pepper_info = plugin_service->GetRegisteredPpapiPluginInfo(plugin_path); if (pepper_info) { plugin_name_ = pepper_info->name; plugin_service->OpenChannelToPpapiBroker(0, plugin_path, this); } else { plugin_service->OpenChannelToNpapiPlugin( 0, 0, GURL(), GURL(), mime_type, this); } }
185,331
9,908
71486441172141781915093084746549933638
null
null
null
Chrome
0b694217046d6b2bfa5814676e8615c18e6a45ff
1
void SystemClipboard::WriteImage(Image* image, const KURL& url, const String& title) { DCHECK(image); PaintImage paint_image = image->PaintImageForCurrentFrame(); SkBitmap bitmap; if (sk_sp<SkImage> sk_image = paint_image.GetSkImage()) sk_image->asLegacyBitmap(&bitmap); if (bitmap.isNull()) return; if (!bitmap.getPixels()) return; clipboard_->WriteImage(mojom::ClipboardBuffer::kStandard, bitmap); if (url.IsValid() && !url.IsEmpty()) { #if !defined(OS_MACOSX) clipboard_->WriteBookmark(mojom::ClipboardBuffer::kStandard, url.GetString(), NonNullString(title)); #endif clipboard_->WriteHtml(mojom::ClipboardBuffer::kStandard, URLToImageMarkup(url, title), KURL()); } clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); }
CWE-119
185,380
9,912
187180540660422685269003296469147490542
null
null
null
Chrome
8f883f2b12f68fed993671dce7fb5fb91f2229aa
1
bool CanRendererHandleEvent(const ui::MouseEvent* event) { if (event->type() == ui::ET_MOUSE_CAPTURE_CHANGED) return false; #if defined(OS_WIN) switch (event->native_event().message) { case WM_XBUTTONDOWN: case WM_XBUTTONUP: case WM_XBUTTONDBLCLK: case WM_NCMOUSELEAVE: case WM_NCMOUSEMOVE: case WM_NCXBUTTONDOWN: case WM_NCXBUTTONUP: case WM_NCXBUTTONDBLCLK: return false; default: break; } #endif return true; }
185,491
9,923
20247975226264262697060852547012614613
null
null
null
Chrome
64bebe14963d4059d2e5fdba3c8879b83acc39d0
1
void XSSAuditor::init(Document* document, XSSAuditorDelegate* auditorDelegate) { const size_t miniumLengthForSuffixTree = 512; // FIXME: Tune this parameter. const int suffixTreeDepth = 5; ASSERT(isMainThread()); if (m_state != Uninitialized) return; m_state = FilteringTokens; if (Settings* settings = document->settings()) m_isEnabled = settings->xssAuditorEnabled(); if (!m_isEnabled) return; m_documentURL = document->url().copy(); if (!document->frame()) { m_isEnabled = false; return; } if (m_documentURL.isEmpty()) { m_isEnabled = false; return; } if (m_documentURL.protocolIsData()) { m_isEnabled = false; return; } if (document->encoding().isValid()) m_encoding = document->encoding(); m_decodedURL = fullyDecodeString(m_documentURL.string(), m_encoding); if (m_decodedURL.find(isRequiredForInjection) == kNotFound) m_decodedURL = String(); String httpBodyAsString; if (DocumentLoader* documentLoader = document->frame()->loader().documentLoader()) { DEFINE_STATIC_LOCAL(const AtomicString, XSSProtectionHeader, ("X-XSS-Protection", AtomicString::ConstructFromLiteral)); const AtomicString& headerValue = documentLoader->response().httpHeaderField(XSSProtectionHeader); String errorDetails; unsigned errorPosition = 0; String reportURL; KURL xssProtectionReportURL; ReflectedXSSDisposition xssProtectionHeader = parseXSSProtectionHeader(headerValue, errorDetails, errorPosition, reportURL); m_didSendValidXSSProtectionHeader = xssProtectionHeader != ReflectedXSSUnset && xssProtectionHeader != ReflectedXSSInvalid; if ((xssProtectionHeader == FilterReflectedXSS || xssProtectionHeader == BlockReflectedXSS) && !reportURL.isEmpty()) { xssProtectionReportURL = document->completeURL(reportURL); if (MixedContentChecker::isMixedContent(document->securityOrigin(), xssProtectionReportURL)) { errorDetails = "insecure reporting URL for secure page"; xssProtectionHeader = ReflectedXSSInvalid; xssProtectionReportURL = KURL(); } } if (xssProtectionHeader == ReflectedXSSInvalid) document->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Error parsing header X-XSS-Protection: " + headerValue + ": " + errorDetails + " at character position " + String::format("%u", errorPosition) + ". The default protections will be applied."); ReflectedXSSDisposition cspHeader = document->contentSecurityPolicy()->reflectedXSSDisposition(); m_didSendValidCSPHeader = cspHeader != ReflectedXSSUnset && cspHeader != ReflectedXSSInvalid; m_xssProtection = combineXSSProtectionHeaderAndCSP(xssProtectionHeader, cspHeader); if (auditorDelegate) auditorDelegate->setReportURL(xssProtectionReportURL.copy()); FormData* httpBody = documentLoader->originalRequest().httpBody(); if (httpBody && !httpBody->isEmpty()) { httpBodyAsString = httpBody->flattenToString(); if (!httpBodyAsString.isEmpty()) { m_decodedHTTPBody = fullyDecodeString(httpBodyAsString, m_encoding); if (m_decodedHTTPBody.find(isRequiredForInjection) == kNotFound) m_decodedHTTPBody = String(); if (m_decodedHTTPBody.length() >= miniumLengthForSuffixTree) m_decodedHTTPBodySuffixTree = adoptPtr(new SuffixTree<ASCIICodebook>(m_decodedHTTPBody, suffixTreeDepth)); } } } if (m_decodedURL.isEmpty() && m_decodedHTTPBody.isEmpty()) { m_isEnabled = false; return; } }
185,538
9,927
81535167366940792596210859069229198822
null
null
null
Chrome
f7b2214a08547e0d28b1a2fef3c19ee0f9febd19
1
bool GetNetworkList(NetworkInterfaceList* networks, int policy) { int s = socket(AF_INET, SOCK_DGRAM, 0); if (s <= 0) { PLOG(ERROR) << "socket"; return false; } uint32_t num_ifs = 0; if (ioctl_netc_get_num_ifs(s, &num_ifs) < 0) { PLOG(ERROR) << "ioctl_netc_get_num_ifs"; PCHECK(close(s) == 0); return false; } for (uint32_t i = 0; i < num_ifs; ++i) { netc_if_info_t interface; if (ioctl_netc_get_if_info_at(s, &i, &interface) < 0) { PLOG(WARNING) << "ioctl_netc_get_if_info_at"; continue; } if (internal::IsLoopbackOrUnspecifiedAddress( reinterpret_cast<sockaddr*>(&(interface.addr)))) { continue; } IPEndPoint address; if (!address.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.addr)), sizeof(interface.addr))) { DLOG(WARNING) << "ioctl_netc_get_if_info returned invalid address."; continue; } int prefix_length = 0; IPEndPoint netmask; if (netmask.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.netmask)), sizeof(interface.netmask))) { prefix_length = MaskPrefixLength(netmask.address()); } int attributes = 0; networks->push_back( NetworkInterface(interface.name, interface.name, interface.index, NetworkChangeNotifier::CONNECTION_UNKNOWN, address.address(), prefix_length, attributes)); } PCHECK(close(s) == 0); return true; }
CWE-119
185,629
9,937
249454725959250347008269104328328368013
null
null
null
Chrome
e1e0c4301aaa8228e362f2409dbde2d4d1896866
1
void Document::open() { ASSERT(!importLoader()); if (m_frame) { if (ScriptableDocumentParser* parser = scriptableDocumentParser()) { if (parser->isParsing()) { if (parser->isExecutingScript()) return; if (!parser->wasCreatedByScript() && parser->hasInsertionPoint()) return; } } if (m_frame->loader().provisionalDocumentLoader()) m_frame->loader().stopAllLoaders(); } removeAllEventListenersRecursively(); implicitOpen(ForceSynchronousParsing); if (ScriptableDocumentParser* parser = scriptableDocumentParser()) parser->setWasCreatedByScript(true); if (m_frame) m_frame->loader().didExplicitOpen(); if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress) m_loadEventProgress = LoadEventNotRun; }
CWE-20
185,660
9,941
33649530546418671728059170920462479785
null
null
null
Chrome
fc81fcf38edd250876cc384a6ed5567e1b2999e4
1
void V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext) { if (!executionContext) return; v8::HandleScope handleScope(toIsolate(executionContext)); v8::Local<v8::Context> v8Context = toV8Context(executionContext, world()); if (v8Context.IsEmpty()) return; ScriptState* scriptState = ScriptState::from(v8Context); if (!scriptState->contextIsValid()) return; if (executionContext->isDocument() && !toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) { clearListenerObject(); return; } if (hasExistingListenerObject()) return; ASSERT(executionContext->isDocument()); ScriptState::Scope scope(scriptState); String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName); String code = "(function() {" "with (this[2]) {" "with (this[1]) {" "with (this[0]) {" "return function(" + m_eventParameterName + ") {" + listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler. "};" "}}}})"; v8::Handle<v8::String> codeExternalString = v8String(isolate(), code); v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position); if (result.IsEmpty()) return; ASSERT(result->IsFunction()); v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>(); HTMLFormElement* formElement = 0; if (m_node && m_node->isHTMLElement()) formElement = toHTMLElement(m_node)->formOwner(); v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState); v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState); v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState); v8::Local<v8::Object> thisObject = v8::Object::New(isolate()); if (thisObject.IsEmpty()) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper)) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper)) return; if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper)) return; v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate()); if (innerValue.IsEmpty() || !innerValue->IsFunction()) return; v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>(); v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString); ASSERT(!toStringFunction.IsEmpty()); String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}"; V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString)); wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction); wrappedFunction->SetName(v8String(isolate(), m_functionName)); setListenerObject(wrappedFunction); }
CWE-17
185,934
9,968
124785778898912592429012677336578824867
null
null
null
Chrome
5472db1c7eca35822219d03be5c817d9a9258c11
1
void PaintLayerScrollableArea::UpdateCompositingLayersAfterScroll() { PaintLayerCompositor* compositor = GetLayoutBox()->View()->Compositor(); if (!compositor->InCompositingMode()) return; if (UsesCompositedScrolling()) { DCHECK(Layer()->HasCompositedLayerMapping()); ScrollingCoordinator* scrolling_coordinator = GetScrollingCoordinator(); bool handled_scroll = Layer()->IsRootLayer() && scrolling_coordinator && scrolling_coordinator->UpdateCompositedScrollOffset(this); if (!handled_scroll) { if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { Layer()->GetCompositedLayerMapping()->SetNeedsGraphicsLayerUpdate( kGraphicsLayerUpdateSubtree); } compositor->SetNeedsCompositingUpdate( kCompositingUpdateAfterGeometryChange); } if (Layer()->IsRootLayer()) { LocalFrame* frame = GetLayoutBox()->GetFrame(); if (frame && frame->View() && frame->View()->HasViewportConstrainedObjects()) { Layer()->SetNeedsCompositingInputsUpdate(); } } } else { Layer()->SetNeedsCompositingInputsUpdate(); } }
CWE-79
185,960
9,972
254694208352117658267046123381058380115
null
null
null
Chrome
0d151e09e13a704e9738ea913d117df7282e6c7d
1
void TestBlinkPlatformSupport::cryptographicallyRandomValues( unsigned char* buffer, size_t length) { }
CWE-310
186,206
9,995
267872989200443510282539074577601903670
null
null
null
Chrome
7c5aa07be11cd63d953fbe66370c5869a52170bf
1
std::string GetUploadData(const std::string& brand) { DCHECK(!brand.empty()); std::string data(kPostXml); const std::string placeholder("__BRANDCODE_PLACEHOLDER__"); size_t placeholder_pos = data.find(placeholder); DCHECK(placeholder_pos != std::string::npos); data.replace(placeholder_pos, placeholder.size(), brand); return data; }
CWE-79
186,246
9,998
208654258749662371915312394708087751912
null
null
null
Chrome
48a13696977c4bd082341ac85d942128ba2638e4
1
const service_manager::Manifest& GetChromeContentBrowserOverlayManifest() { static base::NoDestructor<service_manager::Manifest> manifest { service_manager::ManifestBuilder() .ExposeCapability("gpu", service_manager::Manifest::InterfaceList< metrics::mojom::CallStackProfileCollector>()) .ExposeCapability("renderer", service_manager::Manifest::InterfaceList< chrome::mojom::AvailableOfflineContentProvider, chrome::mojom::CacheStatsRecorder, chrome::mojom::NetBenchmarking, data_reduction_proxy::mojom::DataReductionProxy, metrics::mojom::CallStackProfileCollector, #if defined(OS_WIN) mojom::ModuleEventSink, #endif rappor::mojom::RapporRecorder, safe_browsing::mojom::SafeBrowsing>()) .RequireCapability("ash", "system_ui") .RequireCapability("ash", "test") .RequireCapability("ash", "display") .RequireCapability("assistant", "assistant") .RequireCapability("assistant_audio_decoder", "assistant:audio_decoder") .RequireCapability("chrome", "input_device_controller") .RequireCapability("chrome_printing", "converter") .RequireCapability("cups_ipp_parser", "ipp_parser") .RequireCapability("device", "device:fingerprint") .RequireCapability("device", "device:geolocation_config") .RequireCapability("device", "device:geolocation_control") .RequireCapability("device", "device:ip_geolocator") .RequireCapability("ime", "input_engine") .RequireCapability("mirroring", "mirroring") .RequireCapability("nacl_broker", "browser") .RequireCapability("nacl_loader", "browser") .RequireCapability("noop", "noop") .RequireCapability("patch", "patch_file") .RequireCapability("preferences", "pref_client") .RequireCapability("preferences", "pref_control") .RequireCapability("profile_import", "import") .RequireCapability("removable_storage_writer", "removable_storage_writer") .RequireCapability("secure_channel", "secure_channel") .RequireCapability("ui", "ime_registrar") .RequireCapability("ui", "input_device_controller") .RequireCapability("ui", "window_manager") .RequireCapability("unzip", "unzip_file") .RequireCapability("util_win", "util_win") .RequireCapability("xr_device_service", "xr_device_provider") .RequireCapability("xr_device_service", "xr_device_test_hook") #if defined(OS_CHROMEOS) .RequireCapability("multidevice_setup", "multidevice_setup") #endif .ExposeInterfaceFilterCapability_Deprecated( "navigation:frame", "renderer", service_manager::Manifest::InterfaceList< autofill::mojom::AutofillDriver, autofill::mojom::PasswordManagerDriver, chrome::mojom::OfflinePageAutoFetcher, #if defined(OS_CHROMEOS) chromeos_camera::mojom::CameraAppHelper, chromeos::cellular_setup::mojom::CellularSetup, chromeos::crostini_installer::mojom::PageHandlerFactory, chromeos::crostini_upgrader::mojom::PageHandlerFactory, chromeos::ime::mojom::InputEngineManager, chromeos::machine_learning::mojom::PageHandler, chromeos::media_perception::mojom::MediaPerception, chromeos::multidevice_setup::mojom::MultiDeviceSetup, chromeos::multidevice_setup::mojom::PrivilegedHostDeviceSetter, chromeos::network_config::mojom::CrosNetworkConfig, cros::mojom::CameraAppDeviceProvider, #endif contextual_search::mojom::ContextualSearchJsApiService, #if BUILDFLAG(ENABLE_EXTENSIONS) extensions::KeepAlive, #endif media::mojom::MediaEngagementScoreDetailsProvider, media_router::mojom::MediaRouter, page_load_metrics::mojom::PageLoadMetrics, translate::mojom::ContentTranslateDriver, downloads::mojom::PageHandlerFactory, feed_internals::mojom::PageHandler, new_tab_page::mojom::PageHandlerFactory, #if defined(OS_ANDROID) explore_sites_internals::mojom::PageHandler, #else app_management::mojom::PageHandlerFactory, #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ defined(OS_CHROMEOS) discards::mojom::DetailsProvider, discards::mojom::GraphDump, #endif #if defined(OS_CHROMEOS) add_supervision::mojom::AddSupervisionHandler, #endif mojom::BluetoothInternalsHandler, mojom::InterventionsInternalsPageHandler, mojom::OmniboxPageHandler, mojom::ResetPasswordHandler, mojom::SiteEngagementDetailsProvider, mojom::UsbInternalsPageHandler, snippets_internals::mojom::PageHandlerFactory>()) .PackageService(prefs::GetManifest()) #if defined(OS_CHROMEOS) .PackageService(chromeos::multidevice_setup::GetManifest()) #endif // defined(OS_CHROMEOS) .Build() }; return *manifest; }
CWE-20
186,318
10,007
173432205096925384295979268052436023420
null
null
null
Chrome
ae6f339fba0736224fdca0b96d2bb1cda42d8ad3
1
bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), NULL, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string) && combining_diacritics_exceptions_.containsNone(label_string)) { return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string) && !lgc_letters_n_ascii_.containsAll(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u30ce\u30f3\u30bd\u30be])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)" R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)" R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)" R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)" R"([a-z]\u30fb|\u30fb[a-z]|)" R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)" R"([a-z][\u0585\u0581]+[a-z]|)" R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)" R"([\p{scx=armn}][og]+[\p{scx=armn}]|)" R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)" R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); }
CWE-20
186,331
10,008
331452579950378497862954288034636987658
null
null
null
Chrome
7da6c3419fd172405bcece1ae4ec6ec8316cd345
1
void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) { current_content_source_id_ = next_source_id; did_receive_first_frame_after_navigation_ = false; if (enable_surface_synchronization_) { visual_properties_ack_pending_ = false; viz::LocalSurfaceId old_surface_id = view_->GetLocalSurfaceId(); if (view_) view_->DidNavigate(); viz::LocalSurfaceId new_surface_id = view_->GetLocalSurfaceId(); if (old_surface_id == new_surface_id) return; } else { if (last_received_content_source_id_ >= current_content_source_id_) return; } if (!new_content_rendering_timeout_) return; new_content_rendering_timeout_->Start(new_content_rendering_delay_); }
CWE-20
186,631
10,041
179967799219761087740268236703355368410
null
null
null
Chrome
e89b9003df8c7bd7822e5b6c0a76e726a6ed1505
1
void MimeHandlerViewContainer::OnReady() { if (!render_frame() || !is_embedded_) return; blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); blink::WebAssociatedURLLoaderOptions options; DCHECK(!loader_); loader_.reset(frame->CreateAssociatedURLLoader(options)); blink::WebURLRequest request(original_url_); request.SetRequestContext(blink::WebURLRequest::kRequestContextObject); loader_->LoadAsynchronously(request, this); }
CWE-20
186,679
10,044
136943128534837901677560044867620399235
null
null
null
Chrome
e56aee6473486fdfac0429747284fda7cdd3aae5
1
void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior, UpdateFromElementBehavior update_behavior, const KURL& url, ReferrerPolicy referrer_policy, UpdateType update_type) { pending_task_.reset(); std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter; load_delay_counter.swap(delay_until_do_update_from_element_); Document& document = element_->GetDocument(); if (!document.IsActive()) return; AtomicString image_source_url = element_->ImageSourceURL(); ImageResourceContent* new_image_content = nullptr; if (!url.IsNull() && !url.IsEmpty()) { ResourceLoaderOptions resource_loader_options; resource_loader_options.initiator_info.name = GetElement()->localName(); ResourceRequest resource_request(url); if (update_behavior == kUpdateForcedReload) { resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache); resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform); } if (referrer_policy != kReferrerPolicyDefault) { resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_policy, url, document.OutgoingReferrer())); } if (IsHTMLPictureElement(GetElement()->parentNode()) || !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) resource_request.SetRequestContext( WebURLRequest::kRequestContextImageSet); bool page_is_being_dismissed = document.PageDismissalEventBeingDispatched() != Document::kNoDismissal; if (page_is_being_dismissed) { resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); resource_request.SetKeepalive(true); resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); } FetchParameters params(resource_request, resource_loader_options); ConfigureRequest(params, bypass_behavior, *element_, document.GetClientHintsPreferences()); if (update_behavior != kUpdateForcedReload && document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params); new_image_content = ImageResourceContent::Fetch(params, document.Fetcher()); if (page_is_being_dismissed) new_image_content = nullptr; ClearFailedLoadURL(); } else { if (!image_source_url.IsNull()) { DispatchErrorEvent(); } NoImageResourceToLoad(); } ImageResourceContent* old_image_content = image_content_.Get(); if (old_image_content != new_image_content) RejectPendingDecodes(update_type); if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() && element_->GetLayoutObject()->IsImage() && new_image_content == old_image_content) { ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged(); } else { if (pending_load_event_.IsActive()) pending_load_event_.Cancel(); if (pending_error_event_.IsActive() && new_image_content) pending_error_event_.Cancel(); UpdateImageState(new_image_content); UpdateLayoutObject(); if (new_image_content) { new_image_content->AddObserver(this); } if (old_image_content) { old_image_content->RemoveObserver(this); } } if (LayoutImageResource* image_resource = GetLayoutImageResource()) image_resource->ResetAnimation(); }
CWE-20
186,769
10,057
101908932034635227859505403165505222483
null
null
null
Chrome
9d81094d7b0bfc8be6bba2f5084e790677e527c8
1
ProfilingProcessHost::Mode ProfilingProcessHost::GetCurrentMode() { const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); #if BUILDFLAG(USE_ALLOCATOR_SHIM) if (cmdline->HasSwitch(switches::kMemlog) || base::FeatureList::IsEnabled(kOOPHeapProfilingFeature)) { if (cmdline->HasSwitch(switches::kEnableHeapProfiling)) { LOG(ERROR) << "--" << switches::kEnableHeapProfiling << " specified with --" << switches::kMemlog << "which are not compatible. Memlog will be disabled."; return Mode::kNone; } std::string mode; if (cmdline->HasSwitch(switches::kMemlog)) { mode = cmdline->GetSwitchValueASCII(switches::kMemlog); } else { mode = base::GetFieldTrialParamValueByFeature( kOOPHeapProfilingFeature, kOOPHeapProfilingFeatureMode); } if (mode == switches::kMemlogModeAll) return Mode::kAll; if (mode == switches::kMemlogModeMinimal) return Mode::kMinimal; if (mode == switches::kMemlogModeBrowser) return Mode::kBrowser; if (mode == switches::kMemlogModeGpu) return Mode::kGpu; if (mode == switches::kMemlogModeRendererSampling) return Mode::kRendererSampling; DLOG(ERROR) << "Unsupported value: \"" << mode << "\" passed to --" << switches::kMemlog; } return Mode::kNone; #else LOG_IF(ERROR, cmdline->HasSwitch(switches::kMemlog)) << "--" << switches::kMemlog << " specified but it will have no effect because the use_allocator_shim " << "is not available in this build."; return Mode::kNone; #endif }
CWE-416
186,901
10,067
46622500276925108648433279856841080149
null
null
null
Chrome
965bbf35c6645b47427b236cf49d696faf7d306a
1
InlineBoxPosition ComputeInlineBoxPositionTemplate( const PositionTemplate<Strategy>& position, TextAffinity affinity, TextDirection primary_direction) { int caret_offset = position.ComputeEditingOffset(); Node* const anchor_node = position.AnchorNode(); LayoutObject* layout_object = anchor_node->IsShadowRoot() ? ToShadowRoot(anchor_node)->host().GetLayoutObject() : anchor_node->GetLayoutObject(); DCHECK(layout_object) << position; if (layout_object->IsText()) { return ComputeInlineBoxPositionForTextNode(layout_object, caret_offset, affinity, primary_direction); } if (layout_object->IsLayoutBlockFlow()) { if (CanHaveChildrenForEditing(anchor_node) && HasRenderedNonAnonymousDescendantsWithHeight(layout_object)) { const PositionTemplate<Strategy>& downstream_equivalent = DownstreamIgnoringEditingBoundaries(position); if (downstream_equivalent != position) { return ComputeInlineBoxPosition( downstream_equivalent, TextAffinity::kUpstream, primary_direction); } const PositionTemplate<Strategy>& upstream_equivalent = UpstreamIgnoringEditingBoundaries(position); if (upstream_equivalent == position || DownstreamIgnoringEditingBoundaries(upstream_equivalent) == position) return InlineBoxPosition(); return ComputeInlineBoxPosition( upstream_equivalent, TextAffinity::kUpstream, primary_direction); } } if (!layout_object->IsAtomicInlineLevel()) return InlineBoxPosition(); if (!layout_object->IsBox()) return InlineBoxPosition(); InlineBox* const inline_box = ToLayoutBox(layout_object)->InlineBoxWrapper(); if (!inline_box) return InlineBoxPosition(); if ((caret_offset > inline_box->CaretMinOffset() && caret_offset < inline_box->CaretMaxOffset())) return InlineBoxPosition(inline_box, caret_offset); return AdjustInlineBoxPositionForTextDirection( inline_box, caret_offset, layout_object->Style()->GetUnicodeBidi(), primary_direction); }
186,941
10,072
320355738237550750235563874271493225630
null
null
null
Chrome
cfb022640b5eec337b06f88a485487dc92ca1ac1
1
void MediaStreamDispatcherHost::DoOpenDevice( int32_t page_request_id, const std::string& device_id, blink::MediaStreamType type, OpenDeviceCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(false /* success */, std::string(), blink::MediaStreamDevice()); return; } media_stream_manager_->OpenDevice( render_process_id_, render_frame_id_, page_request_id, requester_id_, device_id, type, std::move(salt_and_origin), std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr())); }
CWE-119
186,993
10,079
16333236676002739922656014474340032294
null
null
null
Chrome
56b512399a5c2221ba4812f5170f3f8dc352cd74
1
void NavigationRequest::OnRequestRedirected( const net::RedirectInfo& redirect_info, const scoped_refptr<network::ResourceResponse>& response) { response_ = response; ssl_info_ = response->head.ssl_info; #if defined(OS_ANDROID) base::WeakPtr<NavigationRequest> this_ptr(weak_factory_.GetWeakPtr()); bool should_override_url_loading = false; if (!GetContentClient()->browser()->ShouldOverrideUrlLoading( frame_tree_node_->frame_tree_node_id(), browser_initiated_, redirect_info.new_url, redirect_info.new_method, false, true, frame_tree_node_->IsMainFrame(), common_params_.transition, &should_override_url_loading)) { return; } if (!this_ptr) return; if (should_override_url_loading) { navigation_handle_->set_net_error_code(net::ERR_ABORTED); common_params_.url = redirect_info.new_url; common_params_.method = redirect_info.new_method; navigation_handle_->UpdateStateFollowingRedirect( GURL(redirect_info.new_referrer), base::Bind(&NavigationRequest::OnRedirectChecksComplete, base::Unretained(this))); frame_tree_node_->ResetNavigationRequest(false, true); return; } #endif if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRedirectToURL( redirect_info.new_url)) { DVLOG(1) << "Denied redirect for " << redirect_info.new_url.possibly_invalid_spec(); navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT); frame_tree_node_->ResetNavigationRequest(false, true); return; } if (!browser_initiated_ && source_site_instance() && !ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL( source_site_instance()->GetProcess()->GetID(), redirect_info.new_url)) { DVLOG(1) << "Denied unauthorized redirect for " << redirect_info.new_url.possibly_invalid_spec(); navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT); frame_tree_node_->ResetNavigationRequest(false, true); return; } if (redirect_info.new_method != "POST") common_params_.post_data = nullptr; if (commit_params_.navigation_timing.redirect_start.is_null()) { commit_params_.navigation_timing.redirect_start = commit_params_.navigation_timing.fetch_start; } commit_params_.navigation_timing.redirect_end = base::TimeTicks::Now(); commit_params_.navigation_timing.fetch_start = base::TimeTicks::Now(); commit_params_.redirect_response.push_back(response->head); commit_params_.redirect_infos.push_back(redirect_info); if (commit_params_.origin_to_commit) commit_params_.origin_to_commit.reset(); commit_params_.redirects.push_back(common_params_.url); common_params_.url = redirect_info.new_url; common_params_.method = redirect_info.new_method; common_params_.referrer.url = GURL(redirect_info.new_referrer); common_params_.referrer = Referrer::SanitizeForRequest(common_params_.url, common_params_.referrer); net::Error net_error = CheckContentSecurityPolicy(true /* has_followed_redirect */, redirect_info.insecure_scheme_was_upgraded, false /* is_response_check */); if (net_error != net::OK) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net_error), false /*skip_throttles*/, base::nullopt /*error_page_content*/, false /*collapse_frame*/); return; } if (CheckCredentialedSubresource() == CredentialedSubresourceCheckResult::BLOCK_REQUEST || CheckLegacyProtocolInSubresource() == LegacyProtocolInSubresourceCheckResult::BLOCK_REQUEST) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net::ERR_ABORTED), false /*skip_throttles*/, base::nullopt /*error_page_content*/, false /*collapse_frame*/); return; } scoped_refptr<SiteInstance> site_instance = frame_tree_node_->render_manager()->GetSiteInstanceForNavigationRequest( *this); speculative_site_instance_ = site_instance->HasProcess() ? site_instance : nullptr; if (!site_instance->HasProcess()) { RenderProcessHostImpl::NotifySpareManagerAboutRecentlyUsedBrowserContext( site_instance->GetBrowserContext()); } common_params_.previews_state = GetContentClient()->browser()->DetermineAllowedPreviews( common_params_.previews_state, navigation_handle_.get(), common_params_.url); RenderProcessHost* expected_process = site_instance->HasProcess() ? site_instance->GetProcess() : nullptr; navigation_handle_->WillRedirectRequest( common_params_.referrer.url, expected_process, base::Bind(&NavigationRequest::OnRedirectChecksComplete, base::Unretained(this))); }
CWE-20
187,014
10,086
215499437441415995003738075799563367043
null
null
null
Chrome
af38308b7112bdfbc0cfcc27f966314accc471d0
1
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8( "[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;" "[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;" "[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;" "[ҫင] > c; ұ > y; [χҳӽӿ] > x;" "ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;" "[зҙӡउওဒვპ] > 3; [บບ] > u"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); }
CWE-20
187,099
10,093
204381263566259570831836573505831035591
null
null
null
Chrome
4d666348de3f67d5cb7b5401f0f69f6b9d3719eb
1
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8( "[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;" "[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;" "[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;" "[ҫင] > c; ұ > y; [χҳӽӿ] > x;" "ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;" "[зҙӡउওဒვპ] > 3; [บບ] > u"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); }
CWE-20
187,100
10,094
115805963185267604690250428753012236536
null
null
null
Chrome
0328261c41b1b7495e1d4d4cf958f41a08aff38b
1
bool BrowserCommandController::ExecuteCommandWithDisposition( int id, WindowOpenDisposition disposition) { if (!SupportsCommand(id) || !IsCommandEnabled(id)) return false; if (browser_->tab_strip_model()->active_index() == TabStripModel::kNoTab) return true; DCHECK(command_updater_.IsCommandEnabled(id)) << "Invalid/disabled command " << id; switch (id) { case IDC_BACK: GoBack(browser_, disposition); break; case IDC_FORWARD: GoForward(browser_, disposition); break; case IDC_RELOAD: Reload(browser_, disposition); break; case IDC_RELOAD_CLEARING_CACHE: ClearCache(browser_); FALLTHROUGH; case IDC_RELOAD_BYPASSING_CACHE: ReloadBypassingCache(browser_, disposition); break; case IDC_HOME: Home(browser_, disposition); break; case IDC_OPEN_CURRENT_URL: OpenCurrentURL(browser_); break; case IDC_STOP: Stop(browser_); break; case IDC_NEW_WINDOW: NewWindow(browser_); break; case IDC_NEW_INCOGNITO_WINDOW: NewIncognitoWindow(profile()); break; case IDC_CLOSE_WINDOW: base::RecordAction(base::UserMetricsAction("CloseWindowByKey")); CloseWindow(browser_); break; case IDC_NEW_TAB: { NewTab(browser_); #if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) auto* new_tab_tracker = feature_engagement::NewTabTrackerFactory::GetInstance() ->GetForProfile(profile()); new_tab_tracker->OnNewTabOpened(); new_tab_tracker->CloseBubble(); #endif break; } case IDC_CLOSE_TAB: base::RecordAction(base::UserMetricsAction("CloseTabByKey")); CloseTab(browser_); break; case IDC_SELECT_NEXT_TAB: base::RecordAction(base::UserMetricsAction("Accel_SelectNextTab")); SelectNextTab(browser_); break; case IDC_SELECT_PREVIOUS_TAB: base::RecordAction(base::UserMetricsAction("Accel_SelectPreviousTab")); SelectPreviousTab(browser_); break; case IDC_MOVE_TAB_NEXT: MoveTabNext(browser_); break; case IDC_MOVE_TAB_PREVIOUS: MoveTabPrevious(browser_); break; case IDC_SELECT_TAB_0: case IDC_SELECT_TAB_1: case IDC_SELECT_TAB_2: case IDC_SELECT_TAB_3: case IDC_SELECT_TAB_4: case IDC_SELECT_TAB_5: case IDC_SELECT_TAB_6: case IDC_SELECT_TAB_7: base::RecordAction(base::UserMetricsAction("Accel_SelectNumberedTab")); SelectNumberedTab(browser_, id - IDC_SELECT_TAB_0); break; case IDC_SELECT_LAST_TAB: base::RecordAction(base::UserMetricsAction("Accel_SelectNumberedTab")); SelectLastTab(browser_); break; case IDC_DUPLICATE_TAB: DuplicateTab(browser_); break; case IDC_RESTORE_TAB: RestoreTab(browser_); break; case IDC_SHOW_AS_TAB: ConvertPopupToTabbedBrowser(browser_); break; case IDC_FULLSCREEN: chrome::ToggleFullscreenMode(browser_); break; case IDC_OPEN_IN_PWA_WINDOW: base::RecordAction(base::UserMetricsAction("OpenActiveTabInPwaWindow")); ReparentSecureActiveTabIntoPwaWindow(browser_); break; #if defined(OS_CHROMEOS) case IDC_VISIT_DESKTOP_OF_LRU_USER_2: case IDC_VISIT_DESKTOP_OF_LRU_USER_3: ExecuteVisitDesktopCommand(id, window()->GetNativeWindow()); break; #endif #if defined(OS_LINUX) && !defined(OS_CHROMEOS) case IDC_MINIMIZE_WINDOW: browser_->window()->Minimize(); break; case IDC_MAXIMIZE_WINDOW: browser_->window()->Maximize(); break; case IDC_RESTORE_WINDOW: browser_->window()->Restore(); break; case IDC_USE_SYSTEM_TITLE_BAR: { PrefService* prefs = profile()->GetPrefs(); prefs->SetBoolean(prefs::kUseCustomChromeFrame, !prefs->GetBoolean(prefs::kUseCustomChromeFrame)); break; } #endif #if defined(OS_MACOSX) case IDC_TOGGLE_FULLSCREEN_TOOLBAR: chrome::ToggleFullscreenToolbar(browser_); break; case IDC_TOGGLE_JAVASCRIPT_APPLE_EVENTS: { PrefService* prefs = profile()->GetPrefs(); prefs->SetBoolean(prefs::kAllowJavascriptAppleEvents, !prefs->GetBoolean(prefs::kAllowJavascriptAppleEvents)); break; } #endif case IDC_EXIT: Exit(); break; case IDC_SAVE_PAGE: SavePage(browser_); break; case IDC_BOOKMARK_PAGE: #if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) feature_engagement::BookmarkTrackerFactory::GetInstance() ->GetForProfile(profile()) ->OnBookmarkAdded(); #endif BookmarkCurrentPageAllowingExtensionOverrides(browser_); break; case IDC_BOOKMARK_ALL_TABS: #if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) feature_engagement::BookmarkTrackerFactory::GetInstance() ->GetForProfile(profile()) ->OnBookmarkAdded(); #endif BookmarkAllTabs(browser_); break; case IDC_VIEW_SOURCE: browser_->tab_strip_model() ->GetActiveWebContents() ->GetMainFrame() ->ViewSource(); break; case IDC_EMAIL_PAGE_LOCATION: EmailPageLocation(browser_); break; case IDC_PRINT: Print(browser_); break; #if BUILDFLAG(ENABLE_PRINTING) case IDC_BASIC_PRINT: base::RecordAction(base::UserMetricsAction("Accel_Advanced_Print")); BasicPrint(browser_); break; #endif // ENABLE_PRINTING case IDC_SAVE_CREDIT_CARD_FOR_PAGE: SaveCreditCard(browser_); break; case IDC_MIGRATE_LOCAL_CREDIT_CARD_FOR_PAGE: MigrateLocalCards(browser_); break; case IDC_TRANSLATE_PAGE: Translate(browser_); break; case IDC_MANAGE_PASSWORDS_FOR_PAGE: ManagePasswordsForPage(browser_); break; case IDC_CUT: case IDC_COPY: case IDC_PASTE: CutCopyPaste(browser_, id); break; case IDC_FIND: Find(browser_); break; case IDC_FIND_NEXT: FindNext(browser_); break; case IDC_FIND_PREVIOUS: FindPrevious(browser_); break; case IDC_ZOOM_PLUS: Zoom(browser_, content::PAGE_ZOOM_IN); break; case IDC_ZOOM_NORMAL: Zoom(browser_, content::PAGE_ZOOM_RESET); break; case IDC_ZOOM_MINUS: Zoom(browser_, content::PAGE_ZOOM_OUT); break; case IDC_FOCUS_TOOLBAR: base::RecordAction(base::UserMetricsAction("Accel_Focus_Toolbar")); FocusToolbar(browser_); break; case IDC_FOCUS_LOCATION: base::RecordAction(base::UserMetricsAction("Accel_Focus_Location")); FocusLocationBar(browser_); break; case IDC_FOCUS_SEARCH: base::RecordAction(base::UserMetricsAction("Accel_Focus_Search")); FocusSearch(browser_); break; case IDC_FOCUS_MENU_BAR: FocusAppMenu(browser_); break; case IDC_FOCUS_BOOKMARKS: base::RecordAction(base::UserMetricsAction("Accel_Focus_Bookmarks")); FocusBookmarksToolbar(browser_); break; case IDC_FOCUS_INACTIVE_POPUP_FOR_ACCESSIBILITY: FocusInactivePopupForAccessibility(browser_); break; case IDC_FOCUS_NEXT_PANE: FocusNextPane(browser_); break; case IDC_FOCUS_PREVIOUS_PANE: FocusPreviousPane(browser_); break; case IDC_OPEN_FILE: browser_->OpenFile(); break; case IDC_CREATE_SHORTCUT: CreateBookmarkAppFromCurrentWebContents(browser_, true /* force_shortcut_app */); break; case IDC_INSTALL_PWA: CreateBookmarkAppFromCurrentWebContents(browser_, false /* force_shortcut_app */); break; case IDC_DEV_TOOLS: ToggleDevToolsWindow(browser_, DevToolsToggleAction::Show()); break; case IDC_DEV_TOOLS_CONSOLE: ToggleDevToolsWindow(browser_, DevToolsToggleAction::ShowConsolePanel()); break; case IDC_DEV_TOOLS_DEVICES: InspectUI::InspectDevices(browser_); break; case IDC_DEV_TOOLS_INSPECT: ToggleDevToolsWindow(browser_, DevToolsToggleAction::Inspect()); break; case IDC_DEV_TOOLS_TOGGLE: ToggleDevToolsWindow(browser_, DevToolsToggleAction::Toggle()); break; case IDC_TASK_MANAGER: OpenTaskManager(browser_); break; #if defined(OS_CHROMEOS) case IDC_TAKE_SCREENSHOT: TakeScreenshot(); break; #endif #if defined(GOOGLE_CHROME_BUILD) case IDC_FEEDBACK: OpenFeedbackDialog(browser_, kFeedbackSourceBrowserCommand); break; #endif case IDC_SHOW_BOOKMARK_BAR: ToggleBookmarkBar(browser_); break; case IDC_PROFILING_ENABLED: Profiling::Toggle(); break; case IDC_SHOW_BOOKMARK_MANAGER: ShowBookmarkManager(browser_); break; case IDC_SHOW_APP_MENU: base::RecordAction(base::UserMetricsAction("Accel_Show_App_Menu")); ShowAppMenu(browser_); break; case IDC_SHOW_AVATAR_MENU: ShowAvatarMenu(browser_); break; case IDC_SHOW_HISTORY: ShowHistory(browser_); break; case IDC_SHOW_DOWNLOADS: ShowDownloads(browser_); break; case IDC_MANAGE_EXTENSIONS: ShowExtensions(browser_, std::string()); break; case IDC_OPTIONS: ShowSettings(browser_); break; case IDC_EDIT_SEARCH_ENGINES: ShowSearchEngineSettings(browser_); break; case IDC_VIEW_PASSWORDS: ShowPasswordManager(browser_); break; case IDC_CLEAR_BROWSING_DATA: ShowClearBrowsingDataDialog(browser_); break; case IDC_IMPORT_SETTINGS: ShowImportDialog(browser_); break; case IDC_TOGGLE_REQUEST_TABLET_SITE: ToggleRequestTabletSite(browser_); break; case IDC_ABOUT: ShowAboutChrome(browser_); break; case IDC_UPGRADE_DIALOG: OpenUpdateChromeDialog(browser_); break; case IDC_HELP_PAGE_VIA_KEYBOARD: ShowHelp(browser_, HELP_SOURCE_KEYBOARD); break; case IDC_HELP_PAGE_VIA_MENU: ShowHelp(browser_, HELP_SOURCE_MENU); break; case IDC_SHOW_BETA_FORUM: ShowBetaForum(browser_); break; case IDC_SHOW_SIGNIN: ShowBrowserSigninOrSettings( browser_, signin_metrics::AccessPoint::ACCESS_POINT_MENU); break; case IDC_DISTILL_PAGE: DistillCurrentPage(browser_); break; case IDC_ROUTE_MEDIA: RouteMedia(browser_); break; case IDC_WINDOW_MUTE_SITE: MuteSite(browser_); break; case IDC_WINDOW_PIN_TAB: PinTab(browser_); break; case IDC_COPY_URL: CopyURL(browser_); break; case IDC_OPEN_IN_CHROME: OpenInChrome(browser_); break; case IDC_SITE_SETTINGS: ShowSiteSettings( browser_, browser_->tab_strip_model()->GetActiveWebContents()->GetVisibleURL()); break; case IDC_HOSTED_APP_MENU_APP_INFO: ShowPageInfoDialog(browser_->tab_strip_model()->GetActiveWebContents(), bubble_anchor_util::kAppMenuButton); break; default: LOG(WARNING) << "Received Unimplemented Command: " << id; break; } return true; }
CWE-20
187,105
10,095
331955434778726968331563125082280060272
null
null
null
Chrome
d616695bd68610e75b90d734d72d42534bf01b82
1
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8( "[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;" "[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;" "[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;" "[ҫင] > c; ұ > y; [χҳӽӿ] > x;" "ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;" "[зҙӡ] > 3; [บບ] > u"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); }
187,136
10,101
311811786541766429389630450682080518236
null
null
null
Chrome
b276d0570cc816bfe25b431f2ee9bc265a6ad478
1
std::string TestURLLoader::TestUntendedLoad() { pp::URLRequestInfo request(instance_); request.SetURL("test_url_loader_data/hello.txt"); request.SetRecordDownloadProgress(true); TestCompletionCallback callback(instance_->pp_instance(), callback_type()); pp::URLLoader loader(instance_); callback.WaitForResult(loader.Open(request, callback.GetCallback())); CHECK_CALLBACK_BEHAVIOR(callback); ASSERT_EQ(PP_OK, callback.result()); int64_t bytes_received = 0; int64_t total_bytes_to_be_received = 0; while (true) { loader.GetDownloadProgress(&bytes_received, &total_bytes_to_be_received); if (total_bytes_to_be_received <= 0) return ReportError("URLLoader::GetDownloadProgress total size", total_bytes_to_be_received); if (bytes_received == total_bytes_to_be_received) break; if (pp::Module::Get()->core()->IsMainThread()) { NestedEvent event(instance_->pp_instance()); event.PostSignal(10); event.Wait(); } } std::string body; std::string error = ReadEntireResponseBody(&loader, &body); if (!error.empty()) return error; if (body != "hello\n") return ReportError("Couldn't read data", callback.result()); PASS(); }
CWE-284
187,301
10,116
59372771345167268090977733615288514689
null
null
null
Chrome
96dbafe288dbe2f0cc45fa3c39daf6d0c37acbab
1
xsltDocumentFunctionLoadDocument(xmlXPathParserContextPtr ctxt, xmlChar* URI) { xsltTransformContextPtr tctxt; xmlURIPtr uri; xmlChar *fragment; xsltDocumentPtr idoc; /* document info */ xmlDocPtr doc; xmlXPathContextPtr xptrctxt = NULL; xmlXPathObjectPtr resObj = NULL; tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltTransformError(NULL, NULL, NULL, "document() : internal error tctxt == NULL\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } uri = xmlParseURI((const char *) URI); if (uri == NULL) { xsltTransformError(tctxt, NULL, NULL, "document() : failed to parse URI\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } /* * check for and remove fragment identifier */ fragment = (xmlChar *)uri->fragment; if (fragment != NULL) { xmlChar *newURI; uri->fragment = NULL; newURI = xmlSaveUri(uri); idoc = xsltLoadDocument(tctxt, newURI); xmlFree(newURI); } else idoc = xsltLoadDocument(tctxt, URI); xmlFreeURI(uri); if (idoc == NULL) { if ((URI == NULL) || (URI[0] == '#') || ((tctxt->style->doc != NULL) && (xmlStrEqual(tctxt->style->doc->URL, URI)))) { /* * This selects the stylesheet's doc itself. */ doc = tctxt->style->doc; } else { valuePush(ctxt, xmlXPathNewNodeSet(NULL)); if (fragment != NULL) xmlFree(fragment); return; } } else doc = idoc->doc; if (fragment == NULL) { valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr) doc)); return; } /* use XPointer of HTML location for fragment ID */ #ifdef LIBXML_XPTR_ENABLED xptrctxt = xmlXPtrNewContext(doc, NULL, NULL); if (xptrctxt == NULL) { xsltTransformError(tctxt, NULL, NULL, "document() : internal error xptrctxt == NULL\n"); goto out_fragment; } resObj = xmlXPtrEval(fragment, xptrctxt); xmlXPathFreeContext(xptrctxt); #endif xmlFree(fragment); if (resObj == NULL) goto out_fragment; switch (resObj->type) { case XPATH_NODESET: break; case XPATH_UNDEFINED: case XPATH_BOOLEAN: case XPATH_NUMBER: case XPATH_STRING: case XPATH_POINT: case XPATH_USERS: case XPATH_XSLT_TREE: case XPATH_RANGE: case XPATH_LOCATIONSET: xsltTransformError(tctxt, NULL, NULL, "document() : XPointer does not select a node set: #%s\n", fragment); goto out_object; } valuePush(ctxt, resObj); return; out_object: xmlXPathFreeObject(resObj); out_fragment: valuePush(ctxt, xmlXPathNewNodeSet(NULL)); }
CWE-119
187,323
10,121
163222908297183902912800375301240011859
null
null
null
Android
6fe85f7e15203e48df2cc3e8e1c4bc6ad49dc968
1
status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { ALOGV("entering parseChunk %lld/%d", *offset, depth); uint32_t hdr[2]; if (mDataSource->readAt(*offset, hdr, 8) < 8) { return ERROR_IO; } uint64_t chunk_size = ntohl(hdr[0]); uint32_t chunk_type = ntohl(hdr[1]); off64_t data_offset = *offset + 8; if (chunk_size == 1) { if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { return ERROR_IO; } chunk_size = ntoh64(chunk_size); data_offset += 8; if (chunk_size < 16) { return ERROR_MALFORMED; } } else if (chunk_size == 0) { if (depth == 0) { off64_t sourceSize; if (mDataSource->getSize(&sourceSize) == OK) { chunk_size = (sourceSize - *offset); } else { ALOGE("atom size is 0, and data source has no size"); return ERROR_MALFORMED; } } else { *offset += 4; return OK; } } else if (chunk_size < 8) { ALOGE("invalid chunk size: %" PRIu64, chunk_size); return ERROR_MALFORMED; } char chunk[5]; MakeFourCCString(chunk_type, chunk); ALOGV("chunk: %s @ %lld, %d", chunk, *offset, depth); #if 0 static const char kWhitespace[] = " "; const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size); char buffer[256]; size_t n = chunk_size; if (n > sizeof(buffer)) { n = sizeof(buffer); } if (mDataSource->readAt(*offset, buffer, n) < (ssize_t)n) { return ERROR_IO; } hexdump(buffer, n); #endif PathAdder autoAdder(&mPath, chunk_type); off64_t chunk_data_size = *offset + chunk_size - data_offset; if (chunk_type != FOURCC('c', 'p', 'r', 't') && chunk_type != FOURCC('c', 'o', 'v', 'r') && mPath.size() == 5 && underMetaDataPath(mPath)) { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } return OK; } switch(chunk_type) { case FOURCC('m', 'o', 'o', 'v'): case FOURCC('t', 'r', 'a', 'k'): case FOURCC('m', 'd', 'i', 'a'): case FOURCC('m', 'i', 'n', 'f'): case FOURCC('d', 'i', 'n', 'f'): case FOURCC('s', 't', 'b', 'l'): case FOURCC('m', 'v', 'e', 'x'): case FOURCC('m', 'o', 'o', 'f'): case FOURCC('t', 'r', 'a', 'f'): case FOURCC('m', 'f', 'r', 'a'): case FOURCC('u', 'd', 't', 'a'): case FOURCC('i', 'l', 's', 't'): case FOURCC('s', 'i', 'n', 'f'): case FOURCC('s', 'c', 'h', 'i'): case FOURCC('e', 'd', 't', 's'): { if (chunk_type == FOURCC('s', 't', 'b', 'l')) { ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size); if (mDataSource->flags() & (DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) { sp<MPEG4DataSource> cachedSource = new MPEG4DataSource(mDataSource); if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { mDataSource = cachedSource; } } mLastTrack->sampleTable = new SampleTable(mDataSource); } bool isTrack = false; if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { isTrack = true; Track *track = new Track; track->next = NULL; if (mLastTrack) { mLastTrack->next = track; } else { mFirstTrack = track; } mLastTrack = track; track->meta = new MetaData; track->includes_expensive_metadata = false; track->skipTrack = false; track->timescale = 0; track->meta->setCString(kKeyMIMEType, "application/octet-stream"); } off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } if (isTrack) { if (mLastTrack->skipTrack) { Track *cur = mFirstTrack; if (cur == mLastTrack) { delete cur; mFirstTrack = mLastTrack = NULL; } else { while (cur && cur->next != mLastTrack) { cur = cur->next; } cur->next = NULL; delete mLastTrack; mLastTrack = cur; } return OK; } status_t err = verifyTrack(mLastTrack); if (err != OK) { return err; } } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { mInitCheck = OK; if (!mIsDrm) { return UNKNOWN_ERROR; // Return a dummy error. } else { return OK; } } break; } case FOURCC('e', 'l', 's', 't'): { *offset += chunk_size; uint8_t version; if (mDataSource->readAt(data_offset, &version, 1) < 1) { return ERROR_IO; } uint32_t entry_count; if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { return ERROR_IO; } if (entry_count != 1) { ALOGW("ignoring edit list with %d entries", entry_count); } else if (mHeaderTimescale == 0) { ALOGW("ignoring edit list because timescale is 0"); } else { off64_t entriesoffset = data_offset + 8; uint64_t segment_duration; int64_t media_time; if (version == 1) { if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { return ERROR_IO; } } else if (version == 0) { uint32_t sd; int32_t mt; if (!mDataSource->getUInt32(entriesoffset, &sd) || !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { return ERROR_IO; } segment_duration = sd; media_time = mt; } else { return ERROR_IO; } uint64_t halfscale = mHeaderTimescale / 2; segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; int64_t duration; int32_t samplerate; if (!mLastTrack) { return ERROR_MALFORMED; } if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { int64_t delay = (media_time * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); int64_t paddingus = duration - (segment_duration + media_time); if (paddingus < 0) { paddingus = 0; } int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); } } break; } case FOURCC('f', 'r', 'm', 'a'): { *offset += chunk_size; uint32_t original_fourcc; if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { return ERROR_IO; } original_fourcc = ntohl(original_fourcc); ALOGV("read original format: %d", original_fourcc); mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); uint32_t num_channels = 0; uint32_t sample_rate = 0; if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); } break; } case FOURCC('t', 'e', 'n', 'c'): { *offset += chunk_size; if (chunk_size < 32) { return ERROR_MALFORMED; } char buf[4]; memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { return ERROR_IO; } uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); if (defaultAlgorithmId > 1) { return ERROR_MALFORMED; } memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { return ERROR_IO; } uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || (defaultAlgorithmId != 0 && defaultIVSize == 0)) { return ERROR_MALFORMED; } else if (defaultIVSize != 0 && defaultIVSize != 8 && defaultIVSize != 16) { return ERROR_MALFORMED; } uint8_t defaultKeyId[16]; if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { return ERROR_IO; } mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); break; } case FOURCC('t', 'k', 'h', 'd'): { *offset += chunk_size; status_t err; if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { return err; } break; } case FOURCC('p', 's', 's', 'h'): { *offset += chunk_size; PsshInfo pssh; if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { return ERROR_IO; } uint32_t psshdatalen = 0; if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { return ERROR_IO; } pssh.datalen = ntohl(psshdatalen); ALOGV("pssh data size: %d", pssh.datalen); if (pssh.datalen + 20 > chunk_size) { return ERROR_MALFORMED; } pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; if (pssh.data == NULL) { return ERROR_MALFORMED; } ALOGV("allocated pssh @ %p", pssh.data); ssize_t requested = (ssize_t) pssh.datalen; if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { return ERROR_IO; } mPssh.push_back(pssh); break; } case FOURCC('m', 'd', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 4 || mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t version; if (mDataSource->readAt( data_offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } off64_t timescale_offset; if (version == 1) { timescale_offset = data_offset + 4 + 16; } else if (version == 0) { timescale_offset = data_offset + 4 + 8; } else { return ERROR_IO; } uint32_t timescale; if (mDataSource->readAt( timescale_offset, &timescale, sizeof(timescale)) < (ssize_t)sizeof(timescale)) { return ERROR_IO; } mLastTrack->timescale = ntohl(timescale); int64_t duration = 0; if (version == 1) { if (mDataSource->readAt( timescale_offset + 4, &duration, sizeof(duration)) < (ssize_t)sizeof(duration)) { return ERROR_IO; } if (duration != -1) { duration = ntoh64(duration); } } else { uint32_t duration32; if (mDataSource->readAt( timescale_offset + 4, &duration32, sizeof(duration32)) < (ssize_t)sizeof(duration32)) { return ERROR_IO; } if (duration32 != 0xffffffff) { duration = ntohl(duration32); } } if (duration != 0) { mLastTrack->meta->setInt64( kKeyDuration, (duration * 1000000) / mLastTrack->timescale); } uint8_t lang[2]; off64_t lang_offset; if (version == 1) { lang_offset = timescale_offset + 4 + 8; } else if (version == 0) { lang_offset = timescale_offset + 4 + 4; } else { return ERROR_IO; } if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) < (ssize_t)sizeof(lang)) { return ERROR_IO; } char lang_code[4]; lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; lang_code[2] = (lang[1] & 0x1f) + 0x60; lang_code[3] = '\0'; mLastTrack->meta->setCString( kKeyMediaLanguage, lang_code); break; } case FOURCC('s', 't', 's', 'd'): { if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t buffer[8]; if (chunk_data_size < (off64_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 8) < 8) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } uint32_t entry_count = U32_AT(&buffer[4]); if (entry_count > 1) { const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && strcasecmp(mime, "application/octet-stream")) { mLastTrack->skipTrack = true; *offset += chunk_size; break; } } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + 8; for (uint32_t i = 0; i < entry_count; ++i) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'a'): case FOURCC('e', 'n', 'c', 'a'): case FOURCC('s', 'a', 'm', 'r'): case FOURCC('s', 'a', 'w', 'b'): { uint8_t buffer[8 + 20]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint32_t num_channels = U16_AT(&buffer[16]); uint16_t sample_size = U16_AT(&buffer[18]); uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); } ALOGV("*** coding='%s' %d channels, size %d, rate %d\n", chunk, num_channels, sample_size, sample_rate); mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'v'): case FOURCC('e', 'n', 'c', 'v'): case FOURCC('s', '2', '6', '3'): case FOURCC('H', '2', '6', '3'): case FOURCC('h', '2', '6', '3'): case FOURCC('a', 'v', 'c', '1'): case FOURCC('h', 'v', 'c', '1'): case FOURCC('h', 'e', 'v', '1'): { mHasVideo = true; uint8_t buffer[78]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index = U16_AT(&buffer[6]); uint16_t width = U16_AT(&buffer[6 + 18]); uint16_t height = U16_AT(&buffer[6 + 20]); if (width == 0) width = 352; if (height == 0) height = 288; if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); } mLastTrack->meta->setInt32(kKeyWidth, width); mLastTrack->meta->setInt32(kKeyHeight, height); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('s', 't', 'c', 'o'): case FOURCC('c', 'o', '6', '4'): { status_t err = mLastTrack->sampleTable->setChunkOffsetParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'c'): { status_t err = mLastTrack->sampleTable->setSampleToChunkParams( data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'z'): case FOURCC('s', 't', 'z', '2'): { status_t err = mLastTrack->sampleTable->setSampleSizeParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } size_t max_size; err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); if (err != OK) { return err; } if (max_size != 0) { mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); } else { int32_t width, height; if (!mLastTrack->meta->findInt32(kKeyWidth, &width) || !mLastTrack->meta->findInt32(kKeyHeight, &height)) { ALOGE("No width or height, assuming worst case 1080p"); width = 1920; height = 1080; } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) { max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; } else { max_size = width * height * 3 / 2; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp("video/", mime, 6)) { size_t nSamples = mLastTrack->sampleTable->countSamples(); int64_t durationUs; if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > 0) { int32_t frameRate = (nSamples * 1000000LL + (durationUs >> 1)) / durationUs; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } } } break; } case FOURCC('s', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('c', 't', 't', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setCompositionTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 's'): { *offset += chunk_size; status_t err = mLastTrack->sampleTable->setSyncSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('\xA9', 'x', 'y', 'z'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } char buffer[18]; off64_t location_length = chunk_data_size - 5; if (location_length >= (off64_t) sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset + 4, buffer, location_length) < location_length) { return ERROR_IO; } buffer[location_length] = '\0'; mFileMetaData->setCString(kKeyLocation, buffer); break; } case FOURCC('e', 's', 'd', 's'): { *offset += chunk_size; if (chunk_data_size < 4) { return ERROR_MALFORMED; } uint8_t buffer[256]; if (chunk_data_size > (off64_t)sizeof(buffer)) { return ERROR_BUFFER_TOO_SMALL; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } mLastTrack->meta->setData( kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( &buffer[4], chunk_data_size - 4); if (err != OK) { return err; } } break; } case FOURCC('a', 'v', 'c', 'C'): { *offset += chunk_size; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); break; } case FOURCC('h', 'v', 'c', 'C'): { sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData( kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); *offset += chunk_size; break; } case FOURCC('d', '2', '6', '3'): { *offset += chunk_size; /* * d263 contains a fixed 7 bytes part: * vendor - 4 bytes * version - 1 byte * level - 1 byte * profile - 1 byte * optionally, "d263" box itself may contain a 16-byte * bit rate box (bitr) * average bit rate - 4 bytes * max bit rate - 4 bytes */ char buffer[23]; if (chunk_data_size != 7 && chunk_data_size != 23) { ALOGE("Incorrect D263 box size %lld", chunk_data_size); return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); break; } case FOURCC('m', 'e', 't', 'a'): { uint8_t buffer[4]; if (chunk_data_size < (off64_t)sizeof(buffer)) { *offset += chunk_size; return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 4) < 4) { *offset += chunk_size; return ERROR_IO; } if (U32_AT(buffer) != 0) { *offset += chunk_size; return OK; } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 'a', 'n'): case FOURCC('n', 'a', 'm', 'e'): case FOURCC('d', 'a', 't', 'a'): { *offset += chunk_size; if (mPath.size() == 6 && underMetaDataPath(mPath)) { status_t err = parseITunesMetaData(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('m', 'v', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 32) { return ERROR_MALFORMED; } uint8_t header[32]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } uint64_t creationTime; uint64_t duration = 0; if (header[0] == 1) { creationTime = U64_AT(&header[4]); mHeaderTimescale = U32_AT(&header[20]); duration = U64_AT(&header[24]); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (header[0] != 0) { return ERROR_MALFORMED; } else { creationTime = U32_AT(&header[4]); mHeaderTimescale = U32_AT(&header[12]); uint32_t d32 = U32_AT(&header[16]); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } String8 s; convertTimeToDate(creationTime, &s); mFileMetaData->setCString(kKeyDate, s.string()); break; } case FOURCC('m', 'e', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t flags[4]; if (mDataSource->readAt( data_offset, flags, sizeof(flags)) < (ssize_t)sizeof(flags)) { return ERROR_IO; } uint64_t duration = 0; if (flags[0] == 1) { if (chunk_data_size < 12) { return ERROR_MALFORMED; } mDataSource->getUInt64(data_offset + 4, &duration); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (flags[0] == 0) { uint32_t d32; mDataSource->getUInt32(data_offset + 4, &d32); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } else { return ERROR_MALFORMED; } if (duration != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } break; } case FOURCC('m', 'd', 'a', 't'): { ALOGV("mdat chunk, drm: %d", mIsDrm); if (!mIsDrm) { *offset += chunk_size; break; } if (chunk_size < 8) { return ERROR_MALFORMED; } return parseDrmSINF(offset, data_offset); } case FOURCC('h', 'd', 'l', 'r'): { *offset += chunk_size; uint32_t buffer; if (mDataSource->readAt( data_offset + 8, &buffer, 4) < 4) { return ERROR_IO; } uint32_t type = ntohl(buffer); if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); } break; } case FOURCC('t', 'r', 'e', 'x'): { *offset += chunk_size; if (chunk_data_size < 24) { return ERROR_IO; } uint32_t duration; Trex trex; if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { return ERROR_IO; } mTrex.add(trex); break; } case FOURCC('t', 'x', '3', 'g'): { uint32_t type; const void *data; size_t size = 0; if (!mLastTrack->meta->findData( kKeyTextFormatData, &type, &data, &size)) { size = 0; } if (SIZE_MAX - chunk_size <= size) { return ERROR_MALFORMED; } uint8_t *buffer = new uint8_t[size + chunk_size]; if (buffer == NULL) { return ERROR_MALFORMED; } if (size > 0) { memcpy(buffer, data, size); } if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) < chunk_size) { delete[] buffer; buffer = NULL; *offset += chunk_size; return ERROR_IO; } mLastTrack->meta->setData( kKeyTextFormatData, 0, buffer, size + chunk_size); delete[] buffer; *offset += chunk_size; break; } case FOURCC('c', 'o', 'v', 'r'): { *offset += chunk_size; if (mFileMetaData != NULL) { ALOGV("chunk_data_size = %lld and data_offset = %lld", chunk_data_size, data_offset); if (chunk_data_size >= SIZE_MAX - 1) { return ERROR_MALFORMED; } sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1); if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { return ERROR_IO; } const int kSkipBytesOfDataBox = 16; if (chunk_data_size <= kSkipBytesOfDataBox) { return ERROR_MALFORMED; } mFileMetaData->setData( kKeyAlbumArt, MetaData::TYPE_NONE, buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); } break; } case FOURCC('t', 'i', 't', 'l'): case FOURCC('p', 'e', 'r', 'f'): case FOURCC('a', 'u', 't', 'h'): case FOURCC('g', 'n', 'r', 'e'): case FOURCC('a', 'l', 'b', 'm'): case FOURCC('y', 'r', 'r', 'c'): { *offset += chunk_size; status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); if (err != OK) { return err; } break; } case FOURCC('I', 'D', '3', '2'): { *offset += chunk_size; if (chunk_data_size < 6) { return ERROR_MALFORMED; } parseID3v2MetaData(data_offset + 6); break; } case FOURCC('-', '-', '-', '-'): { mLastCommentMean.clear(); mLastCommentName.clear(); mLastCommentData.clear(); *offset += chunk_size; break; } case FOURCC('s', 'i', 'd', 'x'): { parseSegmentIndex(data_offset, chunk_data_size); *offset += chunk_size; return UNKNOWN_ERROR; // stop parsing after sidx } default: { *offset += chunk_size; break; } } return OK; }
CWE-189
187,362
10,125
36800442274222177665926713351411195962
null
null
null
Android
4cff1f49ff95d990d6c2614da5d5a23d02145885
1
static jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel) { if (parcel == NULL) { return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); SkRegion* region = new SkRegion; size_t size = p->readInt32(); region->readFromMemory(p->readInplace(size), size); return reinterpret_cast<jlong>(region); }
CWE-264
187,363
10,126
242302747094976072509343488030943659679
null
null
null
Android
2434839bbd168469f80dd9a22f1328bc81046398
1
status_t SampleTable::setSampleToChunkParams( off64_t data_offset, size_t data_size) { if (mSampleToChunkOffset >= 0) { return ERROR_MALFORMED; } mSampleToChunkOffset = data_offset; if (data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mNumSampleToChunkOffsets = U32_AT(&header[4]); if (data_size < 8 + mNumSampleToChunkOffsets * 12) { return ERROR_MALFORMED; } mSampleToChunkEntries = new SampleToChunkEntry[mNumSampleToChunkOffsets]; for (uint32_t i = 0; i < mNumSampleToChunkOffsets; ++i) { uint8_t buffer[12]; if (mDataSource->readAt( mSampleToChunkOffset + 8 + i * 12, buffer, sizeof(buffer)) != (ssize_t)sizeof(buffer)) { return ERROR_IO; } CHECK(U32_AT(buffer) >= 1); // chunk index is 1 based in the spec. mSampleToChunkEntries[i].startChunk = U32_AT(buffer) - 1; mSampleToChunkEntries[i].samplesPerChunk = U32_AT(&buffer[4]); mSampleToChunkEntries[i].chunkDesc = U32_AT(&buffer[8]); } return OK; }
CWE-189
187,393
10,127
257356045235322350872661029709383949189
null
null
null
Android
38803268570f90e97452cd9a30ac831661829091
1
status_t GraphicBuffer::unflatten( void const*& buffer, size_t& size, int const*& fds, size_t& count) { if (size < 8*sizeof(int)) return NO_MEMORY; int const* buf = static_cast<int const*>(buffer); if (buf[0] != 'GBFR') return BAD_TYPE; const size_t numFds = buf[8]; const size_t numInts = buf[9]; const size_t sizeNeeded = (10 + numInts) * sizeof(int); if (size < sizeNeeded) return NO_MEMORY; size_t fdCountNeeded = 0; if (count < fdCountNeeded) return NO_MEMORY; if (handle) { free_handle(); } if (numFds || numInts) { width = buf[1]; height = buf[2]; stride = buf[3]; format = buf[4]; usage = buf[5]; native_handle* h = native_handle_create(numFds, numInts); memcpy(h->data, fds, numFds*sizeof(int)); memcpy(h->data + numFds, &buf[10], numInts*sizeof(int)); handle = h; } else { width = height = stride = format = usage = 0; handle = NULL; } mId = static_cast<uint64_t>(buf[6]) << 32; mId |= static_cast<uint32_t>(buf[7]); mOwner = ownHandle; if (handle != 0) { status_t err = mBufferMapper.registerBuffer(handle); if (err != NO_ERROR) { width = height = stride = format = usage = 0; handle = NULL; ALOGE("unflatten: registerBuffer failed: %s (%d)", strerror(-err), err); return err; } } buffer = reinterpret_cast<void const*>(static_cast<int const*>(buffer) + sizeNeeded); size -= sizeNeeded; fds += numFds; count -= numFds; return NO_ERROR; }
CWE-189
187,396
10,128
340179419665331346744432113173670639202
null
null
null
Android
a583270e1c96d307469c83dc42bd3c5f1b9ef63f
1
WORD32 ih264d_process_intra_mb(dec_struct_t * ps_dec, dec_mb_info_t * ps_cur_mb_info, UWORD8 u1_mb_num) { UWORD8 u1_mb_type = ps_cur_mb_info->u1_mb_type; UWORD8 uc_temp = ps_cur_mb_info->u1_mb_ngbr_availablity; UWORD8 u1_top_available = BOOLEAN(uc_temp & TOP_MB_AVAILABLE_MASK); UWORD8 u1_left_available = BOOLEAN(uc_temp & LEFT_MB_AVAILABLE_MASK); UWORD8 u1_use_top_right_mb = BOOLEAN(uc_temp & TOP_RIGHT_MB_AVAILABLE_MASK); UWORD8 u1_use_top_left_mb = BOOLEAN(uc_temp & TOP_LEFT_MB_AVAILABLE_MASK); UWORD8 uc_useTopMB = u1_top_available; UWORD16 u2_use_left_mb = u1_left_available; UWORD16 u2_use_left_mb_pack; UWORD8 *pu1_luma_pred_buffer; /* CHANGED CODE */ UWORD8 *pu1_luma_rec_buffer; UWORD8 *puc_top; mb_neigbour_params_t *ps_left_mb; mb_neigbour_params_t *ps_top_mb; mb_neigbour_params_t *ps_top_right_mb; mb_neigbour_params_t *ps_curmb; UWORD16 u2_mbx = ps_cur_mb_info->u2_mbx; UWORD32 ui_pred_width, ui_rec_width; WORD16 *pi2_y_coeff; UWORD8 u1_mbaff, u1_topmb, u1_mb_field_decoding_flag; UWORD32 u4_num_pmbair; UWORD16 ui2_luma_csbp = ps_cur_mb_info->u2_luma_csbp; UWORD8 *pu1_yleft, *pu1_ytop_left; /* Chroma variables*/ UWORD8 *pu1_top_u; UWORD8 *pu1_uleft; UWORD8 *pu1_u_top_left; /* CHANGED CODE */ UWORD8 *pu1_mb_cb_rei1_buffer, *pu1_mb_cr_rei1_buffer; UWORD32 u4_recwidth_cr; /* CHANGED CODE */ tfr_ctxt_t *ps_frame_buf = ps_dec->ps_frame_buf_ip_recon; UWORD32 u4_luma_dc_only_csbp = 0; UWORD32 u4_luma_dc_only_cbp = 0; UWORD8 *pu1_prev_intra4x4_pred_mode_data = (UWORD8 *)ps_dec->pv_proc_tu_coeff_data; //Pointer to keep track of intra4x4_pred_mode data in pv_proc_tu_coeff_data buffer u1_mbaff = ps_dec->ps_cur_slice->u1_mbaff_frame_flag; u1_topmb = ps_cur_mb_info->u1_topmb; u4_num_pmbair = (u1_mb_num >> u1_mbaff); /*--------------------------------------------------------------------*/ /* Find the current MB's mb params */ /*--------------------------------------------------------------------*/ u1_mb_field_decoding_flag = ps_cur_mb_info->u1_mb_field_decodingflag; ps_curmb = ps_cur_mb_info->ps_curmb; ps_top_mb = ps_cur_mb_info->ps_top_mb; ps_left_mb = ps_cur_mb_info->ps_left_mb; ps_top_right_mb = ps_cur_mb_info->ps_top_right_mb; /*--------------------------------------------------------------------*/ /* Check whether neighbouring MB is Inter MB and */ /* constrained intra pred is 1. */ /*--------------------------------------------------------------------*/ u2_use_left_mb_pack = (u2_use_left_mb << 8) + u2_use_left_mb; if(ps_dec->ps_cur_pps->u1_constrained_intra_pred_flag) { UWORD8 u1_left = (UWORD8)u2_use_left_mb; uc_useTopMB = uc_useTopMB && ((ps_top_mb->u1_mb_type != P_MB) && (ps_top_mb->u1_mb_type != B_MB)); u2_use_left_mb = u2_use_left_mb && ((ps_left_mb->u1_mb_type != P_MB) && (ps_left_mb->u1_mb_type != B_MB)); u2_use_left_mb_pack = (u2_use_left_mb << 8) + u2_use_left_mb; if(u1_mbaff) { if(u1_mb_field_decoding_flag ^ ps_left_mb->u1_mb_fld) { u1_left = u1_left && (((ps_left_mb + 1)->u1_mb_type != P_MB) && ((ps_left_mb + 1)->u1_mb_type != B_MB)); u2_use_left_mb = u2_use_left_mb && u1_left; if(u1_mb_field_decoding_flag) u2_use_left_mb_pack = (u1_left << 8) + (u2_use_left_mb_pack & 0xff); else u2_use_left_mb_pack = (u2_use_left_mb << 8) + (u2_use_left_mb); } } u1_use_top_right_mb = u1_use_top_right_mb && ((ps_top_right_mb->u1_mb_type != P_MB) && (ps_top_right_mb->u1_mb_type != B_MB)); u1_use_top_left_mb = u1_use_top_left_mb && ((ps_cur_mb_info->u1_topleft_mbtype != P_MB) && (ps_cur_mb_info->u1_topleft_mbtype != B_MB)); } /*********************Common pointer calculations *************************/ /* CHANGED CODE */ pu1_luma_pred_buffer = ps_dec->pu1_y; pu1_luma_rec_buffer = ps_frame_buf->pu1_dest_y + (u4_num_pmbair << 4); pu1_mb_cb_rei1_buffer = ps_frame_buf->pu1_dest_u + (u4_num_pmbair << 3) * YUV420SP_FACTOR; pu1_mb_cr_rei1_buffer = ps_frame_buf->pu1_dest_v + (u4_num_pmbair << 3); ui_pred_width = MB_SIZE; ui_rec_width = ps_dec->u2_frm_wd_y << u1_mb_field_decoding_flag; u4_recwidth_cr = ps_dec->u2_frm_wd_uv << u1_mb_field_decoding_flag; /************* Current and top luma pointer *****************/ if(u1_mbaff) { if(u1_topmb == 0) { pu1_luma_rec_buffer += ( u1_mb_field_decoding_flag ? (ui_rec_width >> 1) : (ui_rec_width << 4)); pu1_mb_cb_rei1_buffer += ( u1_mb_field_decoding_flag ? (u4_recwidth_cr >> 1) : (u4_recwidth_cr << 3)); pu1_mb_cr_rei1_buffer += ( u1_mb_field_decoding_flag ? (u4_recwidth_cr >> 1) : (u4_recwidth_cr << 3)); } } /* CHANGED CODE */ if(ps_dec->u4_use_intrapred_line_copy == 1) { puc_top = ps_dec->pu1_prev_y_intra_pred_line + (ps_cur_mb_info->u2_mbx << 4); pu1_top_u = ps_dec->pu1_prev_u_intra_pred_line + (ps_cur_mb_info->u2_mbx << 3) * YUV420SP_FACTOR; } else { puc_top = pu1_luma_rec_buffer - ui_rec_width; pu1_top_u = pu1_mb_cb_rei1_buffer - u4_recwidth_cr; } /* CHANGED CODE */ /************* Left pointer *****************/ pu1_yleft = pu1_luma_rec_buffer - 1; pu1_uleft = pu1_mb_cb_rei1_buffer - 1 * YUV420SP_FACTOR; /**************Top Left pointer calculation**********/ pu1_ytop_left = puc_top - 1; pu1_u_top_left = pu1_top_u - 1 * YUV420SP_FACTOR; /* CHANGED CODE */ PROFILE_DISABLE_INTRA_PRED() { pu1_prev_intra4x4_pred_mode_data = (UWORD8 *)ps_dec->pv_proc_tu_coeff_data; if(u1_mb_type == I_4x4_MB && ps_cur_mb_info->u1_tran_form8x8 == 0) { ps_dec->pv_proc_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_proc_tu_coeff_data + 32); } else if (u1_mb_type == I_4x4_MB && ps_cur_mb_info->u1_tran_form8x8 == 1) { ps_dec->pv_proc_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_proc_tu_coeff_data + 8); } } if(!ps_cur_mb_info->u1_tran_form8x8) { u4_luma_dc_only_csbp = ih264d_unpack_luma_coeff4x4_mb(ps_dec, ps_cur_mb_info, 1); } else { if(!ps_dec->ps_cur_pps->u1_entropy_coding_mode) { u4_luma_dc_only_cbp = ih264d_unpack_luma_coeff4x4_mb(ps_dec, ps_cur_mb_info, 1); } else { u4_luma_dc_only_cbp = ih264d_unpack_luma_coeff8x8_mb(ps_dec, ps_cur_mb_info); } } pi2_y_coeff = ps_dec->pi2_coeff_data; if(u1_mb_type != I_4x4_MB) { UWORD8 u1_intrapred_mode = MB_TYPE_TO_INTRA_16x16_MODE(u1_mb_type); /*--------------------------------------------------------------------*/ /* 16x16 IntraPrediction */ /*--------------------------------------------------------------------*/ { UWORD8 u1_packed_modes = (u1_top_available << 1) + u1_left_available; UWORD8 u1_err_code = (u1_intrapred_mode & 1) ? u1_intrapred_mode : (u1_intrapred_mode ^ 2); if((u1_err_code & u1_packed_modes) ^ u1_err_code) { u1_intrapred_mode = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } { UWORD8 au1_ngbr_pels[33]; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb) { WORD32 i; for(i = 0; i < 16; i++) au1_ngbr_pels[16 - 1 - i] = pu1_yleft[i * ui_rec_width]; } else { memset(au1_ngbr_pels, 0, 16); } /* top left pels */ au1_ngbr_pels[16] = *pu1_ytop_left; /* top pels */ if(uc_useTopMB) { memcpy(au1_ngbr_pels + 16 + 1, puc_top, 16); } else { memset(au1_ngbr_pels + 16 + 1, 0, 16); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_luma_16x16[u1_intrapred_mode]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((uc_useTopMB << 2) | u2_use_left_mb)); } { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 16; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_luma_rec_buffer + ((i & 0x3) * BLK_SIZE) + (i >> 2) * (ui_rec_width << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(ps_cur_mb_info->u2_luma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_luma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 1, pi2_level); } else if((CHECKBIT(u4_luma_dc_only_csbp, i)) && pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_luma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 1, pi2_level); } } } } } else if(!ps_cur_mb_info->u1_tran_form8x8) { UWORD8 u1_is_left_sub_block, u1_is_top_sub_block = uc_useTopMB; UWORD8 u1_sub_blk_x, u1_sub_blk_y, u1_sub_mb_num; WORD8 i1_top_pred_mode; WORD8 i1_left_pred_mode; UWORD8 *pu1_top, *pu1_left, *pu1_top_left, *pu1_top_right; WORD8 *pi1_cur_pred_mode, *pi1_left_pred_mode, *pc_topPredMode; UWORD16 ui2_left_pred_buf_width = 0xffff; WORD8 i1_intra_pred; UWORD8 *pu1_prev_intra4x4_pred_mode_flag = pu1_prev_intra4x4_pred_mode_data; UWORD8 *pu1_rem_intra4x4_pred_mode = pu1_prev_intra4x4_pred_mode_data + 16; WORD16 *pi2_y_coeff1; UWORD8 u1_cur_sub_block; UWORD16 ui2_top_rt_mask; /*--------------------------------------------------------------------*/ /* 4x4 IntraPrediction */ /*--------------------------------------------------------------------*/ /* Calculation of Top Right subblock mask */ /* */ /* (a) Set it to default mask */ /* [It has 0 for sublocks which will never have top-right sub block] */ /* */ /* (b) If top MB is not available */ /* Clear the bits of the first row sub blocks */ /* */ /* (c) Set/Clear bit for top-right sublock of MB */ /* [5 sub-block in decoding order] based on TOP RIGHT MB availablity */ /*--------------------------------------------------------------------*/ pu1_top = puc_top; ui2_top_rt_mask = (u1_use_top_right_mb << 3) | (0x5750); if(uc_useTopMB) ui2_top_rt_mask |= 0x7; /*Top Related initialisations*/ pi1_cur_pred_mode = ps_cur_mb_info->ps_curmb->pi1_intrapredmodes; pc_topPredMode = ps_cur_mb_info->ps_top_mb->pi1_intrapredmodes; /*-------------------------------------- if(u1_mbaff) { pi1_cur_pred_mode += (u2_mbx << 2); pc_topPredMode = pi1_cur_pred_mode + ps_cur_mb_info->i1_offset; pi1_cur_pred_mode += (u1_topmb) ? 0: 4; }*/ if(u1_top_available) { if(ps_top_mb->u1_mb_type == I_4x4_MB) *(WORD32*)pi1_cur_pred_mode = *(WORD32*)pc_topPredMode; else *(WORD32*)pi1_cur_pred_mode = (uc_useTopMB) ? DC_DC_DC_DC : NOT_VALID; } else *(WORD32*)pi1_cur_pred_mode = NOT_VALID; /* CHANGED CODE */ /* CHANGED CODE */ /*Left Related initialisations*/ pi1_left_pred_mode = ps_dec->pi1_left_pred_mode; if(!u1_mbaff) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } else { UWORD8 u1_curMbfld = ps_cur_mb_info->u1_mb_field_decodingflag; UWORD8 u1_leftMbfld = ps_left_mb->u1_mb_fld; if(u1_curMbfld ^ u1_leftMbfld) { if(u1_topmb | ((u1_topmb == 0) && ((ps_curmb - 1)->u1_mb_type != I_4x4_MB))) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { if(CHECKBIT(u2_use_left_mb_pack,0) == 0) *(WORD32*)pi1_left_pred_mode = NOT_VALID; else *(WORD32*)pi1_left_pred_mode = DC_DC_DC_DC; } } else *(WORD32*)pi1_left_pred_mode = NOT_VALID; if(u1_curMbfld) { if(u1_left_available) { if((ps_left_mb + 1)->u1_mb_type != I_4x4_MB) { if(u2_use_left_mb_pack >> 8) *(WORD32*)(pi1_left_pred_mode + 4) = DC_DC_DC_DC; else *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } } else *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; pi1_left_pred_mode[1] = pi1_left_pred_mode[2]; pi1_left_pred_mode[2] = pi1_left_pred_mode[4]; pi1_left_pred_mode[3] = pi1_left_pred_mode[6]; *(WORD32*)(pi1_left_pred_mode + 4) = *(WORD32*)pi1_left_pred_mode; } else { pi1_left_pred_mode[7] = pi1_left_pred_mode[3]; pi1_left_pred_mode[6] = pi1_left_pred_mode[3]; pi1_left_pred_mode[5] = pi1_left_pred_mode[2]; pi1_left_pred_mode[4] = pi1_left_pred_mode[2]; pi1_left_pred_mode[3] = pi1_left_pred_mode[1]; pi1_left_pred_mode[2] = pi1_left_pred_mode[1]; pi1_left_pred_mode[1] = pi1_left_pred_mode[0]; } } pi1_left_pred_mode += (u1_topmb) ? 0 : 4; } else { pi1_left_pred_mode += (u1_topmb) ? 0 : 4; if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } else *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } /* One time pointer initialisations*/ pi2_y_coeff1 = pi2_y_coeff; pu1_top_left = pu1_ytop_left; /* Scan the sub-blocks in Raster Scan Order */ for(u1_sub_mb_num = 0; u1_sub_mb_num < 16; u1_sub_mb_num++) { UWORD8 au1_ngbr_pels[13]; u1_sub_blk_x = u1_sub_mb_num & 0x3; u1_sub_blk_y = u1_sub_mb_num >> 2; i1_top_pred_mode = pi1_cur_pred_mode[u1_sub_blk_x]; i1_left_pred_mode = pi1_left_pred_mode[u1_sub_blk_y]; u1_use_top_right_mb = (!!CHECKBIT(ui2_top_rt_mask, u1_sub_mb_num)); /*********** left subblock availability**********/ if(u1_sub_blk_x) u1_is_left_sub_block = 1; else u1_is_left_sub_block = (u1_sub_blk_y < 2) ? (CHECKBIT(u2_use_left_mb_pack, 0)) : (u2_use_left_mb_pack >> 8); /* CHANGED CODE */ if(u1_sub_blk_y) u1_is_top_sub_block = 1; /* CHANGED CODE */ /***************** Top *********************/ if(ps_dec->u4_use_intrapred_line_copy == 1) { if(u1_sub_blk_y) pu1_top = pu1_luma_rec_buffer - ui_rec_width; else pu1_top = puc_top + (u1_sub_blk_x << 2); } else { pu1_top = pu1_luma_rec_buffer - ui_rec_width; } /***************** Top Right *********************/ pu1_top_right = pu1_top + 4; /***************** Top Left *********************/ pu1_top_left = pu1_top - 1; /***************** Left *********************/ pu1_left = pu1_luma_rec_buffer - 1; /* CHANGED CODE */ /*---------------------------------------------------------------*/ /* Calculation of Intra prediction mode */ /*---------------------------------------------------------------*/ i1_intra_pred = ((i1_left_pred_mode < 0) | (i1_top_pred_mode < 0)) ? DC : MIN(i1_left_pred_mode, i1_top_pred_mode); { UWORD8 u1_packed_modes = (u1_is_top_sub_block << 1) + u1_is_left_sub_block; UWORD8 *pu1_intra_err_codes = (UWORD8 *)gau1_ih264d_intra_pred_err_code; UWORD8 uc_b2b0 = ((u1_sub_mb_num & 4) >> 1) | (u1_sub_mb_num & 1); UWORD8 uc_b3b1 = ((u1_sub_mb_num & 8) >> 2) | ((u1_sub_mb_num & 2) >> 1); u1_cur_sub_block = (uc_b3b1 << 2) + uc_b2b0; PROFILE_DISABLE_INTRA_PRED() if(!pu1_prev_intra4x4_pred_mode_flag[u1_cur_sub_block]) { i1_intra_pred = pu1_rem_intra4x4_pred_mode[u1_cur_sub_block] + (pu1_rem_intra4x4_pred_mode[u1_cur_sub_block] >= i1_intra_pred); } { UWORD8 u1_err_code = pu1_intra_err_codes[i1_intra_pred]; if((u1_err_code & u1_packed_modes) ^ u1_err_code) { i1_intra_pred = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } } { /* Get neighbour pixels */ /* left pels */ if(u1_is_left_sub_block) { WORD32 i; for(i = 0; i < 4; i++) au1_ngbr_pels[4 - 1 - i] = pu1_left[i * ui_rec_width]; } else { memset(au1_ngbr_pels, 0, 4); } /* top left pels */ au1_ngbr_pels[4] = *pu1_top_left; /* top pels */ if(u1_is_top_sub_block) { memcpy(au1_ngbr_pels + 4 + 1, pu1_top, 4); } else { memset(au1_ngbr_pels + 4 + 1, 0, 4); } /* top right pels */ if(u1_use_top_right_mb) { memcpy(au1_ngbr_pels + 4 * 2 + 1, pu1_top_right, 4); } else if(u1_is_top_sub_block) { memset(au1_ngbr_pels + 4 * 2 + 1, au1_ngbr_pels[4 * 2], 4); } } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_luma_4x4[i1_intra_pred]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((u1_is_top_sub_block << 2) | u1_is_left_sub_block)); /* CHANGED CODE */ if(CHECKBIT(ui2_luma_csbp, u1_sub_mb_num)) { WORD16 ai2_tmp[16]; PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u4_luma_dc_only_csbp, u1_sub_mb_num)) { ps_dec->pf_iquant_itrans_recon_luma_4x4_dc( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } else { ps_dec->pf_iquant_itrans_recon_luma_4x4( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } } } /*---------------------------------------------------------------*/ /* Update sub block number */ /*---------------------------------------------------------------*/ pi2_y_coeff1 += 16; pu1_luma_rec_buffer += (u1_sub_blk_x == 3) ? (ui_rec_width << 2) - 12 : 4; pu1_luma_pred_buffer += (u1_sub_blk_x == 3) ? (ui_pred_width << 2) - 12 : 4; /* CHANGED CODE */ pi1_cur_pred_mode[u1_sub_blk_x] = i1_intra_pred; pi1_left_pred_mode[u1_sub_blk_y] = i1_intra_pred; } } else if((u1_mb_type == I_4x4_MB) && (ps_cur_mb_info->u1_tran_form8x8 == 1)) { UWORD8 u1_is_left_sub_block, u1_is_top_sub_block = uc_useTopMB; UWORD8 u1_sub_blk_x, u1_sub_blk_y, u1_sub_mb_num; WORD8 i1_top_pred_mode; WORD8 i1_left_pred_mode; UWORD8 *pu1_top, *pu1_left, *pu1_top_left; WORD8 *pi1_cur_pred_mode, *pi1_left_pred_mode, *pc_topPredMode; UWORD16 ui2_left_pred_buf_width = 0xffff; WORD8 i1_intra_pred; UWORD8 *pu1_prev_intra4x4_pred_mode_flag = pu1_prev_intra4x4_pred_mode_data; UWORD8 *pu1_rem_intra4x4_pred_mode = pu1_prev_intra4x4_pred_mode_data + 4; WORD16 *pi2_y_coeff1; UWORD16 ui2_top_rt_mask; UWORD32 u4_4x4_left_offset = 0; /*--------------------------------------------------------------------*/ /* 8x8 IntraPrediction */ /*--------------------------------------------------------------------*/ /* Calculation of Top Right subblock mask */ /* */ /* (a) Set it to default mask */ /* [It has 0 for sublocks which will never have top-right sub block] */ /* */ /* (b) If top MB is not available */ /* Clear the bits of the first row sub blocks */ /* */ /* (c) Set/Clear bit for top-right sublock of MB */ /* [5 sub-block in decoding order] based on TOP RIGHT MB availablity */ /* */ /* ui2_top_rt_mask: marks availibility of top right(neighbour) */ /* in the 8x8 Block ordering */ /* */ /* tr0 tr1 */ /* 0 1 tr3 */ /* 2 3 */ /* */ /* Top rights for 0 is in top MB */ /* top right of 1 will be in top right MB */ /* top right of 3 in right MB and hence not available */ /* This corresponds to ui2_top_rt_mask having default value 0x4 */ /*--------------------------------------------------------------------*/ ui2_top_rt_mask = (u1_use_top_right_mb << 1) | (0x4); if(uc_useTopMB) { ui2_top_rt_mask |= 0x1; } /* Top Related initialisations */ pi1_cur_pred_mode = ps_cur_mb_info->ps_curmb->pi1_intrapredmodes; pc_topPredMode = ps_cur_mb_info->ps_top_mb->pi1_intrapredmodes; /* if(u1_mbaff) { pi1_cur_pred_mode += (u2_mbx << 2); pc_topPredMode = pi1_cur_pred_mode + ps_cur_mb_info->i1_offset; pi1_cur_pred_mode += (u1_topmb) ? 0: 4; } */ if(u1_top_available) { if(ps_top_mb->u1_mb_type == I_4x4_MB) { *(WORD32*)pi1_cur_pred_mode = *(WORD32*)pc_topPredMode; } else { *(WORD32*)pi1_cur_pred_mode = (uc_useTopMB) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_cur_pred_mode = NOT_VALID; } pu1_top = puc_top - 8; /*Left Related initialisations*/ pi1_left_pred_mode = ps_dec->pi1_left_pred_mode; if(!u1_mbaff) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } else { UWORD8 u1_curMbfld = ps_cur_mb_info->u1_mb_field_decodingflag; UWORD8 u1_leftMbfld = ps_left_mb->u1_mb_fld; if((!u1_curMbfld) && (u1_leftMbfld)) { u4_4x4_left_offset = 1; } if(u1_curMbfld ^ u1_leftMbfld) { if(u1_topmb | ((u1_topmb == 0) && ((ps_curmb - 1)->u1_mb_type != I_4x4_MB))) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { if(CHECKBIT(u2_use_left_mb_pack,0) == 0) { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } else { *(WORD32*)pi1_left_pred_mode = DC_DC_DC_DC; } } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } if(u1_curMbfld) { if(u1_left_available) { if((ps_left_mb + 1)->u1_mb_type != I_4x4_MB) { if(u2_use_left_mb_pack >> 8) { *(WORD32*)(pi1_left_pred_mode + 4) = DC_DC_DC_DC; } else { *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } } } else { *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } pi1_left_pred_mode[1] = pi1_left_pred_mode[2]; pi1_left_pred_mode[2] = pi1_left_pred_mode[4]; pi1_left_pred_mode[3] = pi1_left_pred_mode[6]; *(WORD32*)(pi1_left_pred_mode + 4) = *(WORD32*)pi1_left_pred_mode; } else { pi1_left_pred_mode[7] = pi1_left_pred_mode[3]; pi1_left_pred_mode[6] = pi1_left_pred_mode[3]; pi1_left_pred_mode[5] = pi1_left_pred_mode[2]; pi1_left_pred_mode[4] = pi1_left_pred_mode[2]; pi1_left_pred_mode[3] = pi1_left_pred_mode[1]; pi1_left_pred_mode[2] = pi1_left_pred_mode[1]; pi1_left_pred_mode[1] = pi1_left_pred_mode[0]; } } pi1_left_pred_mode += (u1_topmb) ? 0 : 4; } else { pi1_left_pred_mode += (u1_topmb) ? 0 : 4; if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } } /* One time pointer initialisations*/ pi2_y_coeff1 = pi2_y_coeff; if(u1_use_top_left_mb) { pu1_top_left = pu1_ytop_left; } else { pu1_top_left = NULL; } /* Scan the sub-blocks in Raster Scan Order */ for(u1_sub_mb_num = 0; u1_sub_mb_num < 4; u1_sub_mb_num++) { u1_sub_blk_x = (u1_sub_mb_num & 0x1); u1_sub_blk_y = (u1_sub_mb_num >> 1); i1_top_pred_mode = pi1_cur_pred_mode[u1_sub_blk_x << 1]; i1_left_pred_mode = pi1_left_pred_mode[u1_sub_blk_y << 1]; if(2 == u1_sub_mb_num) { i1_left_pred_mode = pi1_left_pred_mode[(u1_sub_blk_y << 1) + u4_4x4_left_offset]; } u1_use_top_right_mb = (!!CHECKBIT(ui2_top_rt_mask, u1_sub_mb_num)); /*********** left subblock availability**********/ if(u1_sub_blk_x) { u1_is_left_sub_block = 1; } else { u1_is_left_sub_block = (u1_sub_blk_y < 1) ? (CHECKBIT(u2_use_left_mb_pack, 0)) : (u2_use_left_mb_pack >> 8); } /***************** Top *********************/ if(u1_sub_blk_y) { u1_is_top_sub_block = 1; pu1_top = /*pu1_luma_pred_buffer*/pu1_luma_rec_buffer - ui_rec_width; } else { pu1_top += 8; } /***************** Left *********************/ if((u1_sub_blk_x) | (u4_num_pmbair != 0)) { pu1_left = /*pu1_luma_pred_buffer*/pu1_luma_rec_buffer - 1; ui2_left_pred_buf_width = ui_rec_width; } else { pu1_left = pu1_yleft; pu1_yleft += (ui_rec_width << 3); ui2_left_pred_buf_width = ui_rec_width; } /***************** Top Left *********************/ if(u1_sub_mb_num) { pu1_top_left = (u1_sub_blk_x) ? pu1_top - 1 : pu1_left - ui_rec_width; if((u1_sub_blk_x && (!u1_is_top_sub_block)) || ((!u1_sub_blk_x) && (!u1_is_left_sub_block))) { pu1_top_left = NULL; } } /*---------------------------------------------------------------*/ /* Calculation of Intra prediction mode */ /*---------------------------------------------------------------*/ i1_intra_pred = ((i1_left_pred_mode < 0) | (i1_top_pred_mode < 0)) ? DC : MIN(i1_left_pred_mode, i1_top_pred_mode); { UWORD8 u1_packed_modes = (u1_is_top_sub_block << 1) + u1_is_left_sub_block; UWORD8 *pu1_intra_err_codes = (UWORD8 *)gau1_ih264d_intra_pred_err_code; /********************************************************************/ /* Same intra4x4_pred_mode array is filled with intra4x4_pred_mode */ /* for a MB with 8x8 intrapredicition */ /********************************************************************/ PROFILE_DISABLE_INTRA_PRED() if(!pu1_prev_intra4x4_pred_mode_flag[u1_sub_mb_num]) { i1_intra_pred = pu1_rem_intra4x4_pred_mode[u1_sub_mb_num] + (pu1_rem_intra4x4_pred_mode[u1_sub_mb_num] >= i1_intra_pred); } { UWORD8 u1_err_code = pu1_intra_err_codes[i1_intra_pred]; if((u1_err_code & u1_packed_modes) ^ u1_err_code) { i1_intra_pred = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } } { UWORD8 au1_ngbr_pels[25]; WORD32 ngbr_avail; ngbr_avail = u1_is_left_sub_block << 0; ngbr_avail |= u1_is_top_sub_block << 2; if(pu1_top_left) ngbr_avail |= 1 << 1; ngbr_avail |= u1_use_top_right_mb << 3; PROFILE_DISABLE_INTRA_PRED() { ps_dec->pf_intra_pred_ref_filtering(pu1_left, pu1_top_left, pu1_top, au1_ngbr_pels, ui2_left_pred_buf_width, ngbr_avail); ps_dec->apf_intra_pred_luma_8x8[i1_intra_pred]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((u1_is_top_sub_block << 2) | u1_is_left_sub_block)); } } /* Inverse Transform and Reconstruction */ if(CHECKBIT(ps_cur_mb_info->u1_cbp, u1_sub_mb_num)) { WORD16 *pi2_scale_matrix_ptr; WORD16 ai2_tmp[64]; pi2_scale_matrix_ptr = ps_dec->s_high_profile.i2_scalinglist8x8[0]; PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u4_luma_dc_only_cbp, u1_sub_mb_num)) { ps_dec->pf_iquant_itrans_recon_luma_8x8_dc( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau1_ih264d_dequant8x8_cavlc[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)pi2_scale_matrix_ptr, ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } else { ps_dec->pf_iquant_itrans_recon_luma_8x8( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau1_ih264d_dequant8x8_cavlc[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)pi2_scale_matrix_ptr, ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } } } /*---------------------------------------------------------------*/ /* Update sub block number */ /*---------------------------------------------------------------*/ pi2_y_coeff1 += 64; pu1_luma_rec_buffer += (u1_sub_blk_x == 1) ? (ui_rec_width << 3) - (8 * 1) : 8; /*---------------------------------------------------------------*/ /* Pred mode filled in terms of 4x4 block so replicated in 2 */ /* locations. */ /*---------------------------------------------------------------*/ pi1_cur_pred_mode[u1_sub_blk_x << 1] = i1_intra_pred; pi1_cur_pred_mode[(u1_sub_blk_x << 1) + 1] = i1_intra_pred; pi1_left_pred_mode[u1_sub_blk_y << 1] = i1_intra_pred; pi1_left_pred_mode[(u1_sub_blk_y << 1) + 1] = i1_intra_pred; } } /* Decode Chroma Block */ ih264d_unpack_chroma_coeff4x4_mb(ps_dec, ps_cur_mb_info); /*--------------------------------------------------------------------*/ /* Chroma Blocks decoding */ /*--------------------------------------------------------------------*/ { UWORD8 u1_intra_chrom_pred_mode; UWORD8 u1_chroma_cbp = (UWORD8)(ps_cur_mb_info->u1_cbp >> 4); /*--------------------------------------------------------------------*/ /* Perform Chroma intra prediction */ /*--------------------------------------------------------------------*/ u1_intra_chrom_pred_mode = CHROMA_TO_LUMA_INTRA_MODE( ps_cur_mb_info->u1_chroma_pred_mode); { UWORD8 u1_packed_modes = (u1_top_available << 1) + u1_left_available; UWORD8 u1_err_code = (u1_intra_chrom_pred_mode & 1) ? u1_intra_chrom_pred_mode : (u1_intra_chrom_pred_mode ^ 2); if((u1_err_code & u1_packed_modes) ^ u1_err_code) { u1_intra_chrom_pred_mode = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } /* CHANGED CODE */ if(u1_chroma_cbp != CBPC_ALLZERO) { UWORD16 u2_chroma_csbp = (u1_chroma_cbp == CBPC_ACZERO) ? 0 : ps_cur_mb_info->u2_chroma_csbp; UWORD32 u4_scale_u; UWORD32 u4_scale_v; { UWORD16 au2_ngbr_pels[33]; UWORD8 *pu1_ngbr_pels = (UWORD8 *)au2_ngbr_pels; UWORD16 *pu2_left_uv; UWORD16 *pu2_topleft_uv; WORD32 use_left1 = (u2_use_left_mb_pack & 0x0ff); WORD32 use_left2 = (u2_use_left_mb_pack & 0xff00) >> 8; pu2_left_uv = (UWORD16 *)pu1_uleft; pu2_topleft_uv = (UWORD16 *)pu1_u_top_left; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb_pack) { WORD32 i; if(use_left1) { for(i = 0; i < 4; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels + 4, 0, 4 * sizeof(UWORD16)); } if(use_left2) { for(i = 4; i < 8; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels, 0, 4 * sizeof(UWORD16)); } } else { memset(au2_ngbr_pels, 0, 8 * sizeof(UWORD16)); } /* top left pels */ au2_ngbr_pels[8] = *pu2_topleft_uv; /* top pels */ if(uc_useTopMB) { memcpy(au2_ngbr_pels + 8 + 1, pu1_top_u, 8 * sizeof(UWORD16)); } else { memset(au2_ngbr_pels + 8 + 1, 0, 8 * sizeof(UWORD16)); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_chroma[u1_intra_chrom_pred_mode]( pu1_ngbr_pels, pu1_mb_cb_rei1_buffer, 1, u4_recwidth_cr, ((uc_useTopMB << 2) | (use_left2 << 4) | use_left1)); } u4_scale_u = ps_cur_mb_info->u1_qpc_div6; u4_scale_v = ps_cur_mb_info->u1_qpcr_div6; pi2_y_coeff = ps_dec->pi2_coeff_data; { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 4; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_mb_cb_rei1_buffer + ((i & 0x1) * BLK_SIZE * YUV420SP_FACTOR) + (i >> 1) * (u4_recwidth_cr << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u2_chroma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_chroma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpc_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[1], u4_scale_u, ai2_tmp, pi2_level); } else if(pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_chroma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpc_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[1], u4_scale_u, ai2_tmp, pi2_level); } } } } pi2_y_coeff += MB_CHROM_SIZE; u2_chroma_csbp = u2_chroma_csbp >> 4; { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 4; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_mb_cb_rei1_buffer + 1 + ((i & 0x1) * BLK_SIZE * YUV420SP_FACTOR) + (i >> 1) * (u4_recwidth_cr << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u2_chroma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_chroma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpcr_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[2], u4_scale_v, ai2_tmp, pi2_level); } else if(pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_chroma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpcr_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[2], u4_scale_v, ai2_tmp, pi2_level); } } } } } else { /* If no inverse transform is needed, pass recon buffer pointer */ /* to Intraprediction module instead of pred buffer pointer */ { UWORD16 au2_ngbr_pels[33]; UWORD8 *pu1_ngbr_pels = (UWORD8 *)au2_ngbr_pels; UWORD16 *pu2_left_uv; UWORD16 *pu2_topleft_uv; WORD32 use_left1 = (u2_use_left_mb_pack & 0x0ff); WORD32 use_left2 = (u2_use_left_mb_pack & 0xff00) >> 8; pu2_topleft_uv = (UWORD16 *)pu1_u_top_left; pu2_left_uv = (UWORD16 *)pu1_uleft; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb_pack) { WORD32 i; if(use_left1) { for(i = 0; i < 4; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels + 4, 0, 4 * sizeof(UWORD16)); } if(use_left2) { for(i = 4; i < 8; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels, 0, 4 * sizeof(UWORD16)); } } else { memset(au2_ngbr_pels, 0, 8 * sizeof(UWORD16)); } /* top left pels */ au2_ngbr_pels[8] = *pu2_topleft_uv; /* top pels */ if(uc_useTopMB) { memcpy(au2_ngbr_pels + 8 + 1, pu1_top_u, 8 * sizeof(UWORD16)); } else { memset(au2_ngbr_pels + 8 + 1, 0, 8 * sizeof(UWORD16)); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_chroma[u1_intra_chrom_pred_mode]( pu1_ngbr_pels, pu1_mb_cb_rei1_buffer, 1, u4_recwidth_cr, ((uc_useTopMB << 2) | (use_left2 << 4) | use_left1)); } } } return OK; }
CWE-20
187,781
10,168
83408354466152657604837431098487982473
null
null
null
Android
e248db02fbab2ee9162940bc19f087fd7d96cb9d
1
status_t DRMSource::read(MediaBuffer **buffer, const ReadOptions *options) { Mutex::Autolock autoLock(mDRMLock); status_t err; if ((err = mOriginalMediaSource->read(buffer, options)) != OK) { return err; } size_t len = (*buffer)->range_length(); char *src = (char *)(*buffer)->data() + (*buffer)->range_offset(); DrmBuffer encryptedDrmBuffer(src, len); DrmBuffer decryptedDrmBuffer; decryptedDrmBuffer.length = len; decryptedDrmBuffer.data = new char[len]; DrmBuffer *pDecryptedDrmBuffer = &decryptedDrmBuffer; if ((err = mDrmManagerClient->decrypt(mDecryptHandle, mTrackId, &encryptedDrmBuffer, &pDecryptedDrmBuffer)) != NO_ERROR) { if (decryptedDrmBuffer.data) { delete [] decryptedDrmBuffer.data; decryptedDrmBuffer.data = NULL; } return err; } CHECK(pDecryptedDrmBuffer == &decryptedDrmBuffer); const char *mime; CHECK(getFormat()->findCString(kKeyMIMEType, &mime)); if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) && !mWantsNALFragments) { uint8_t *dstData = (uint8_t*)src; size_t srcOffset = 0; size_t dstOffset = 0; len = decryptedDrmBuffer.length; while (srcOffset < len) { CHECK(srcOffset + mNALLengthSize <= len); size_t nalLength = 0; const uint8_t* data = (const uint8_t*)(&decryptedDrmBuffer.data[srcOffset]); switch (mNALLengthSize) { case 1: nalLength = *data; break; case 2: nalLength = U16_AT(data); break; case 3: nalLength = ((size_t)data[0] << 16) | U16_AT(&data[1]); break; case 4: nalLength = U32_AT(data); break; default: CHECK(!"Should not be here."); break; } srcOffset += mNALLengthSize; size_t end = srcOffset + nalLength; if (end > len || end < srcOffset) { if (decryptedDrmBuffer.data) { delete [] decryptedDrmBuffer.data; decryptedDrmBuffer.data = NULL; } return ERROR_MALFORMED; } if (nalLength == 0) { continue; } CHECK(dstOffset + 4 <= (*buffer)->size()); dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 1; memcpy(&dstData[dstOffset], &decryptedDrmBuffer.data[srcOffset], nalLength); srcOffset += nalLength; dstOffset += nalLength; } CHECK_EQ(srcOffset, len); (*buffer)->set_range((*buffer)->range_offset(), dstOffset); } else { memcpy(src, decryptedDrmBuffer.data, decryptedDrmBuffer.length); (*buffer)->set_range((*buffer)->range_offset(), decryptedDrmBuffer.length); } if (decryptedDrmBuffer.data) { delete [] decryptedDrmBuffer.data; decryptedDrmBuffer.data = NULL; } return OK; }
CWE-119
187,790
10,169
317110456785772854468203829422091660246
null
null
null
Android
a2d1d85726aa2a3126e9c331a8e00a8c319c9e2b
1
ssize_t NuPlayer::NuPlayerStreamListener::read( void *data, size_t size, sp<AMessage> *extra) { CHECK_GT(size, 0u); extra->clear(); Mutex::Autolock autoLock(mLock); if (mEOS) { return 0; } if (mQueue.empty()) { mSendDataNotification = true; return -EWOULDBLOCK; } QueueEntry *entry = &*mQueue.begin(); if (entry->mIsCommand) { switch (entry->mCommand) { case EOS: { mQueue.erase(mQueue.begin()); entry = NULL; mEOS = true; return 0; } case DISCONTINUITY: { *extra = entry->mExtra; mQueue.erase(mQueue.begin()); entry = NULL; return INFO_DISCONTINUITY; } default: TRESPASS(); break; } } size_t copy = entry->mSize; if (copy > size) { copy = size; } memcpy(data, (const uint8_t *)mBuffers.editItemAt(entry->mIndex)->pointer() + entry->mOffset, copy); entry->mOffset += copy; entry->mSize -= copy; if (entry->mSize == 0) { mSource->onBufferAvailable(entry->mIndex); mQueue.erase(mQueue.begin()); entry = NULL; } return copy; }
CWE-264
187,906
10,185
3147867885793061729274046843481592792
null
null
null
Android
ad54cfed4516292654c997910839153264ae00a0
1
std::string Backtrace::GetFunctionName(uintptr_t pc, uintptr_t* offset) { std::string func_name = GetFunctionNameRaw(pc, offset); if (!func_name.empty()) { #if defined(__APPLE__) if (func_name[0] != '_') { return func_name; } #endif char* name = __cxa_demangle(func_name.c_str(), 0, 0, 0); if (name) { func_name = name; free(name); } } return func_name; }
CWE-264
187,909
10,186
70660019768018670786879504075594494581
null
null
null
Android
d834160d9759f1098df692b34e6eeb548f9e317b
1
OMX_ERRORTYPE SimpleSoftOMXComponent::useBuffer( OMX_BUFFERHEADERTYPE **header, OMX_U32 portIndex, OMX_PTR appPrivate, OMX_U32 size, OMX_U8 *ptr) { Mutex::Autolock autoLock(mLock); CHECK_LT(portIndex, mPorts.size()); *header = new OMX_BUFFERHEADERTYPE; (*header)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*header)->nVersion.s.nVersionMajor = 1; (*header)->nVersion.s.nVersionMinor = 0; (*header)->nVersion.s.nRevision = 0; (*header)->nVersion.s.nStep = 0; (*header)->pBuffer = ptr; (*header)->nAllocLen = size; (*header)->nFilledLen = 0; (*header)->nOffset = 0; (*header)->pAppPrivate = appPrivate; (*header)->pPlatformPrivate = NULL; (*header)->pInputPortPrivate = NULL; (*header)->pOutputPortPrivate = NULL; (*header)->hMarkTargetComponent = NULL; (*header)->pMarkData = NULL; (*header)->nTickCount = 0; (*header)->nTimeStamp = 0; (*header)->nFlags = 0; (*header)->nOutputPortIndex = portIndex; (*header)->nInputPortIndex = portIndex; PortInfo *port = &mPorts.editItemAt(portIndex); CHECK(mState == OMX_StateLoaded || port->mDef.bEnabled == OMX_FALSE); CHECK_LT(port->mBuffers.size(), port->mDef.nBufferCountActual); port->mBuffers.push(); BufferInfo *buffer = &port->mBuffers.editItemAt(port->mBuffers.size() - 1); buffer->mHeader = *header; buffer->mOwnedByUs = false; if (port->mBuffers.size() == port->mDef.nBufferCountActual) { port->mDef.bPopulated = OMX_TRUE; checkTransitions(); } return OMX_ErrorNone; }
CWE-200
187,999
10,194
242578536736749983750901260388700936649
null
null
null
Android
552a3b5df2a6876d10da20f72e4cc0d44ac2c790
1
sp<ABuffer> decodeBase64(const AString &s) { size_t n = s.size(); if ((n % 4) != 0) { return NULL; } size_t padding = 0; if (n >= 1 && s.c_str()[n - 1] == '=') { padding = 1; if (n >= 2 && s.c_str()[n - 2] == '=') { padding = 2; if (n >= 3 && s.c_str()[n - 3] == '=') { padding = 3; } } } size_t outLen = (n / 4) * 3 - padding; sp<ABuffer> buffer = new ABuffer(outLen); uint8_t *out = buffer->data(); if (out == NULL || buffer->size() < outLen) { return NULL; } size_t j = 0; uint32_t accum = 0; for (size_t i = 0; i < n; ++i) { char c = s.c_str()[i]; unsigned value; if (c >= 'A' && c <= 'Z') { value = c - 'A'; } else if (c >= 'a' && c <= 'z') { value = 26 + c - 'a'; } else if (c >= '0' && c <= '9') { value = 52 + c - '0'; } else if (c == '+') { value = 62; } else if (c == '/') { value = 63; } else if (c != '=') { return NULL; } else { if (i < n - padding) { return NULL; } value = 0; } accum = (accum << 6) | value; if (((i + 1) % 4) == 0) { out[j++] = (accum >> 16); if (j < outLen) { out[j++] = (accum >> 8) & 0xff; } if (j < outLen) { out[j++] = accum & 0xff; } accum = 0; } } return buffer; }
CWE-119
188,018
10,196
307431912424634082653269216329510536742
null
null
null
Android
0d052d64480a30e83fcdda80f4774624e044beb7
1
void silk_NLSF_stabilize( opus_int16 *NLSF_Q15, /* I/O Unstable/stabilized normalized LSF vector in Q15 [L] */ const opus_int16 *NDeltaMin_Q15, /* I Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1] */ const opus_int L /* I Number of NLSF parameters in the input vector */ ) { opus_int i, I=0, k, loops; opus_int16 center_freq_Q15; opus_int32 diff_Q15, min_diff_Q15, min_center_Q15, max_center_Q15; /* This is necessary to ensure an output within range of a opus_int16 */ silk_assert( NDeltaMin_Q15[L] >= 1 ); for( loops = 0; loops < MAX_LOOPS; loops++ ) { /**************************/ /* Find smallest distance */ /**************************/ /* First element */ min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0]; I = 0; /* Middle elements */ for( i = 1; i <= L-1; i++ ) { diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = i; } } /* Last element */ diff_Q15 = ( 1 << 15 ) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = L; } /***************************************************/ /* Now check if the smallest distance non-negative */ /***************************************************/ if( min_diff_Q15 >= 0 ) { return; } if( I == 0 ) { /* Move away from lower limit */ NLSF_Q15[0] = NDeltaMin_Q15[0]; } else if( I == L) { /* Move away from higher limit */ NLSF_Q15[L-1] = ( 1 << 15 ) - NDeltaMin_Q15[L]; } else { /* Find the lower extreme for the location of the current center frequency */ min_center_Q15 = 0; for( k = 0; k < I; k++ ) { min_center_Q15 += NDeltaMin_Q15[k]; } min_center_Q15 += silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Find the upper extreme for the location of the current center frequency */ max_center_Q15 = 1 << 15; for( k = L; k > I; k-- ) { max_center_Q15 -= NDeltaMin_Q15[k]; } max_center_Q15 -= silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Move apart, sorted by value, keeping the same center frequency */ center_freq_Q15 = (opus_int16)silk_LIMIT_32( silk_RSHIFT_ROUND( (opus_int32)NLSF_Q15[I-1] + (opus_int32)NLSF_Q15[I], 1 ), min_center_Q15, max_center_Q15 ); NLSF_Q15[I-1] = center_freq_Q15 - silk_RSHIFT( NDeltaMin_Q15[I], 1 ); NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I]; } } /* Safe and simple fall back method, which is less ideal than the above */ if( loops == MAX_LOOPS ) { /* Insertion sort (fast for already almost sorted arrays): */ /* Best case: O(n) for an already sorted array */ /* Worst case: O(n^2) for an inversely sorted array */ silk_insertion_sort_increasing_all_values_int16( &NLSF_Q15[0], L ); /* First NLSF should be no less than NDeltaMin[0] */ NLSF_Q15[0] = silk_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] ); /* Keep delta_min distance between the NLSFs */ for( i = 1; i < L; i++ ) NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); /* Last NLSF should be no higher than 1 - NDeltaMin[L] */ NLSF_Q15[L-1] = silk_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] ); /* Keep NDeltaMin distance between the NLSFs */ for( i = L-2; i >= 0; i-- ) NLSF_Q15[i] = silk_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] ); } }
CWE-190
188,093
10,204
136339802244031656780085809632999665046
null
null
null
Android
b9096dc
1
status_t BnSoundTriggerHwService::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case LIST_MODULES: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); unsigned int numModulesReq = data.readInt32(); unsigned int numModules = numModulesReq; struct sound_trigger_module_descriptor *modules = (struct sound_trigger_module_descriptor *)calloc(numModulesReq, sizeof(struct sound_trigger_module_descriptor)); status_t status = listModules(modules, &numModules); reply->writeInt32(status); reply->writeInt32(numModules); ALOGV("LIST_MODULES status %d got numModules %d", status, numModules); if (status == NO_ERROR) { if (numModulesReq > numModules) { numModulesReq = numModules; } reply->write(modules, numModulesReq * sizeof(struct sound_trigger_module_descriptor)); } free(modules); return NO_ERROR; } case ATTACH: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); sound_trigger_module_handle_t handle; data.read(&handle, sizeof(sound_trigger_module_handle_t)); sp<ISoundTriggerClient> client = interface_cast<ISoundTriggerClient>(data.readStrongBinder()); sp<ISoundTrigger> module; status_t status = attach(handle, client, module); reply->writeInt32(status); if (module != 0) { reply->writeInt32(1); reply->writeStrongBinder(IInterface::asBinder(module)); } else { reply->writeInt32(0); } return NO_ERROR; } break; case SET_CAPTURE_STATE: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); reply->writeInt32(setCaptureState((bool)data.readInt32())); return NO_ERROR; } break; default: return BBinder::onTransact(code, data, reply, flags); } }
CWE-190
188,094
10,205
192776366035545804128789424709211770692
null
null
null
Android
931418b16c7197ca2df34c2a5609e49791125abe
1
netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket, int newUid, uid_t callerUid) { ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__); const int fd = socket.get(); struct stat info; if (fstat(fd, &info)) { return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor"); } if (info.st_uid != callerUid) { return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls"); } if (S_ISSOCK(info.st_mode) == 0) { return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket"); } int optval; socklen_t optlen; netdutils::Status status = getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen); if (status != netdutils::status::ok) { return status; } if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) { return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set"); } if (fchown(fd, newUid, -1)) { return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor"); } return netdutils::status::ok; }
CWE-909
188,095
10,206
130669169359316218910591141508258143857
null
null
null
Android
830cb39cb2a0f1bf6704d264e2a5c5029c175dd7
1
static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_pkt) { uint8_t opcode; tAVRC_MSG msg; uint8_t* p_data; uint8_t* p_begin; bool drop = false; bool do_free = true; BT_HDR* p_rsp = NULL; uint8_t* p_rsp_data; int xx; bool reject = false; const char* p_drop_msg = "dropped"; tAVRC_MSG_VENDOR* p_msg = &msg.vendor; if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL && AVRC_PACKET_LEN < sizeof(p_pkt->len))) { /* Ignore the invalid AV/C command frame */ p_drop_msg = "dropped - too long AV/C cmd frame size"; osi_free(p_pkt); return; } if (cr == AVCT_REJ) { /* The peer thinks that this PID is no longer open - remove this handle */ /* */ osi_free(p_pkt); AVCT_RemoveConn(handle); return; } else if (cr == AVCT_RSP) { /* Received response. Stop command timeout timer */ AVRC_TRACE_DEBUG("AVRC: stopping timer (handle=0x%02x)", handle); alarm_cancel(avrc_cb.ccb_int[handle].tle); } p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; memset(&msg, 0, sizeof(tAVRC_MSG)); if (p_pkt->layer_specific == AVCT_DATA_BROWSE) { opcode = AVRC_OP_BROWSE; msg.browse.hdr.ctype = cr; msg.browse.p_browse_data = p_data; msg.browse.browse_len = p_pkt->len; msg.browse.p_browse_pkt = p_pkt; } else { msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK; AVRC_TRACE_DEBUG("%s handle:%d, ctype:%d, offset:%d, len: %d", __func__, handle, msg.hdr.ctype, p_pkt->offset, p_pkt->len); msg.hdr.subunit_type = (p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK; opcode = p_data[2]; } if (((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) || ((avrc_cb.ccb[handle].control & AVRC_CT_CONTROL) && (cr == AVCT_RSP))) { switch (opcode) { case AVRC_OP_UNIT_INFO: if (cr == AVCT_CMD) { /* send the response to the peer */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_UNIT_INFO_RSP_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_IMPL_STBL; /* check & set the offset. set response code, set subunit_type & subunit_id, set AVRC_OP_UNIT_INFO */ /* 3 bytes: ctype, subunit*, opcode */ p_rsp_data += AVRC_AVC_HDR_SIZE; *p_rsp_data++ = 7; /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); AVRC_CO_ID_TO_BE_STREAM(p_rsp_data, avrc_cb.ccb[handle].company_id); p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = "auto respond"; } else { /* parse response */ p_data += 4; /* 3 bytes: ctype, subunit*, opcode + octet 3 (is 7)*/ msg.unit.unit_type = (*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.unit.unit = *p_data & AVRC_SUBID_MASK; p_data++; AVRC_BE_STREAM_TO_CO_ID(msg.unit.company_id, p_data); } break; case AVRC_OP_SUB_INFO: if (cr == AVCT_CMD) { /* send the response to the peer */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_SUB_UNIT_INFO_RSP_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_IMPL_STBL; /* check & set the offset. set response code, set (subunit_type & subunit_id), set AVRC_OP_SUB_INFO, set (page & extention code) */ p_rsp_data += 4; /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); memset(p_rsp_data, AVRC_CMD_OPRND_PAD, AVRC_SUBRSP_OPRND_BYTES); p_rsp_data += AVRC_SUBRSP_OPRND_BYTES; p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = "auto responded"; } else { /* parse response */ p_data += AVRC_AVC_HDR_SIZE; /* 3 bytes: ctype, subunit*, opcode */ msg.sub.page = (*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK; xx = 0; while (*p_data != AVRC_CMD_OPRND_PAD && xx < AVRC_SUB_TYPE_LEN) { msg.sub.subunit_type[xx] = *p_data++ >> AVRC_SUBTYPE_SHIFT; if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL) msg.sub.panel = true; xx++; } } break; case AVRC_OP_VENDOR: { p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_begin = p_data; if (p_pkt->len < AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */ { if (cr == AVCT_CMD) reject = true; else drop = true; break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ AVRC_BE_STREAM_TO_CO_ID(p_msg->company_id, p_data); p_msg->p_vendor_data = p_data; p_msg->vendor_len = p_pkt->len - (p_data - p_begin); uint8_t drop_code = 0; if (p_msg->company_id == AVRC_CO_METADATA) { /* Validate length for metadata message */ if (p_pkt->len < (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE)) { if (cr == AVCT_CMD) reject = true; else drop = true; break; } /* Check+handle fragmented messages */ drop_code = avrc_proc_far_msg(handle, label, cr, &p_pkt, p_msg); if (drop_code > 0) drop = true; } if (drop_code > 0) { if (drop_code != 4) do_free = false; switch (drop_code) { case 1: p_drop_msg = "sent_frag"; break; case 2: p_drop_msg = "req_cont"; break; case 3: p_drop_msg = "sent_frag3"; break; case 4: p_drop_msg = "sent_frag_free"; break; default: p_drop_msg = "sent_fragd"; } } /* If vendor response received, and did not ask for continuation */ /* then check queue for addition commands to send */ if ((cr == AVCT_RSP) && (drop_code != 2)) { avrc_send_next_vendor_cmd(handle); } } break; case AVRC_OP_PASS_THRU: if (p_pkt->len < 5) /* 3 bytes: ctype, subunit*, opcode & op_id & len */ { if (cr == AVCT_CMD) reject = true; else drop = true; break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ msg.pass.op_id = (AVRC_PASS_OP_ID_MASK & *p_data); if (AVRC_PASS_STATE_MASK & *p_data) msg.pass.state = true; else msg.pass.state = false; p_data++; msg.pass.pass_len = *p_data++; if (msg.pass.pass_len != p_pkt->len - 5) msg.pass.pass_len = p_pkt->len - 5; if (msg.pass.pass_len) msg.pass.p_pass_data = p_data; else msg.pass.p_pass_data = NULL; break; case AVRC_OP_BROWSE: /* If browse response received, then check queue for addition commands * to send */ if (cr == AVCT_RSP) { avrc_send_next_vendor_cmd(handle); } break; default: if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) { /* reject unsupported opcode */ reject = true; } drop = true; break; } } else /* drop the event */ { if (opcode != AVRC_OP_BROWSE) drop = true; } if (reject) { /* reject unsupported opcode */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_REJ_MSG_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_REJ; p_drop_msg = "rejected"; cr = AVCT_RSP; drop = true; } if (p_rsp) { /* set to send response right away */ AVCT_MsgReq(handle, label, cr, p_rsp); drop = true; } if (!drop) { msg.hdr.opcode = opcode; avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg); } else { AVRC_TRACE_WARNING("%s %s msg handle:%d, control:%d, cr:%d, opcode:x%x", __func__, p_drop_msg, handle, avrc_cb.ccb[handle].control, cr, opcode); } if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) { do_free = false; } if (do_free) osi_free(p_pkt); }
CWE-125
188,101
10,207
236312995652713894784297813269326126054
null
null
null
Android
42cf02965b11c397dd37a0063e683cef005bc0ae
1
WORD32 ih264d_parse_sps(dec_struct_t *ps_dec, dec_bit_stream_t *ps_bitstrm) { UWORD8 i; dec_seq_params_t *ps_seq = NULL; UWORD8 u1_profile_idc, u1_level_idc, u1_seq_parameter_set_id; UWORD16 i2_max_frm_num; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD8 u1_frm, uc_constraint_set0_flag, uc_constraint_set1_flag; WORD32 i4_cropped_ht, i4_cropped_wd; UWORD32 u4_temp; WORD32 pic_height_in_map_units_minus1 = 0; UWORD32 u2_pic_wd = 0; UWORD32 u2_pic_ht = 0; UWORD32 u2_frm_wd_y = 0; UWORD32 u2_frm_ht_y = 0; UWORD32 u2_frm_wd_uv = 0; UWORD32 u2_frm_ht_uv = 0; UWORD32 u2_crop_offset_y = 0; UWORD32 u2_crop_offset_uv = 0; WORD32 ret; UWORD32 u4_num_reorder_frames; /* High profile related syntax element */ WORD32 i4_i; /* G050 */ UWORD8 u1_frame_cropping_flag, u1_frame_cropping_rect_left_ofst, u1_frame_cropping_rect_right_ofst, u1_frame_cropping_rect_top_ofst, u1_frame_cropping_rect_bottom_ofst; /* G050 */ /*--------------------------------------------------------------------*/ /* Decode seq_parameter_set_id and profile and level values */ /*--------------------------------------------------------------------*/ SWITCHONTRACE; u1_profile_idc = ih264d_get_bits_h264(ps_bitstrm, 8); COPYTHECONTEXT("SPS: profile_idc",u1_profile_idc); /* G050 */ uc_constraint_set0_flag = ih264d_get_bit_h264(ps_bitstrm); uc_constraint_set1_flag = ih264d_get_bit_h264(ps_bitstrm); ih264d_get_bit_h264(ps_bitstrm); /*****************************************************/ /* Read 5 bits for uc_constraint_set3_flag (1 bit) */ /* and reserved_zero_4bits (4 bits) - Sushant */ /*****************************************************/ ih264d_get_bits_h264(ps_bitstrm, 5); /* G050 */ /* Check whether particular profile is suported or not */ /* Check whether particular profile is suported or not */ if((u1_profile_idc != MAIN_PROFILE_IDC) && (u1_profile_idc != BASE_PROFILE_IDC) && (u1_profile_idc != HIGH_PROFILE_IDC) ) { /* Apart from Baseline, main and high profile, * only extended profile is supported provided * uc_constraint_set0_flag or uc_constraint_set1_flag are set to 1 */ if((u1_profile_idc != EXTENDED_PROFILE_IDC) || ((uc_constraint_set1_flag != 1) && (uc_constraint_set0_flag != 1))) { return (ERROR_FEATURE_UNAVAIL); } } u1_level_idc = ih264d_get_bits_h264(ps_bitstrm, 8); COPYTHECONTEXT("SPS: u4_level_idc",u1_level_idc); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp & MASK_ERR_SEQ_SET_ID) return ERROR_INV_SPS_PPS_T; u1_seq_parameter_set_id = u4_temp; COPYTHECONTEXT("SPS: seq_parameter_set_id", u1_seq_parameter_set_id); /*--------------------------------------------------------------------*/ /* Find an seq param entry in seqparam array of decStruct */ /*--------------------------------------------------------------------*/ ps_seq = ps_dec->pv_scratch_sps_pps; if(ps_dec->i4_header_decoded & 1) { *ps_seq = *ps_dec->ps_cur_sps; } if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_profile_idc != u1_profile_idc)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_level_idc != u1_level_idc)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_profile_idc = u1_profile_idc; ps_seq->u1_level_idc = u1_level_idc; ps_seq->u1_seq_parameter_set_id = u1_seq_parameter_set_id; /*******************************************************************/ /* Initializations for high profile - Sushant */ /*******************************************************************/ ps_seq->i4_chroma_format_idc = 1; ps_seq->i4_bit_depth_luma_minus8 = 0; ps_seq->i4_bit_depth_chroma_minus8 = 0; ps_seq->i4_qpprime_y_zero_transform_bypass_flag = 0; ps_seq->i4_seq_scaling_matrix_present_flag = 0; if(u1_profile_idc == HIGH_PROFILE_IDC) { /* reading chroma_format_idc */ ps_seq->i4_chroma_format_idc = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); /* Monochrome is not supported */ if(ps_seq->i4_chroma_format_idc != 1) { return ERROR_INV_SPS_PPS_T; } /* reading bit_depth_luma_minus8 */ ps_seq->i4_bit_depth_luma_minus8 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(ps_seq->i4_bit_depth_luma_minus8 != 0) { return ERROR_INV_SPS_PPS_T; } /* reading bit_depth_chroma_minus8 */ ps_seq->i4_bit_depth_chroma_minus8 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(ps_seq->i4_bit_depth_chroma_minus8 != 0) { return ERROR_INV_SPS_PPS_T; } /* reading qpprime_y_zero_transform_bypass_flag */ ps_seq->i4_qpprime_y_zero_transform_bypass_flag = (WORD32)ih264d_get_bit_h264(ps_bitstrm); if(ps_seq->i4_qpprime_y_zero_transform_bypass_flag != 0) { return ERROR_INV_SPS_PPS_T; } /* reading seq_scaling_matrix_present_flag */ ps_seq->i4_seq_scaling_matrix_present_flag = (WORD32)ih264d_get_bit_h264(ps_bitstrm); if(ps_seq->i4_seq_scaling_matrix_present_flag) { for(i4_i = 0; i4_i < 8; i4_i++) { ps_seq->u1_seq_scaling_list_present_flag[i4_i] = ih264d_get_bit_h264(ps_bitstrm); /* initialize u1_use_default_scaling_matrix_flag[i4_i] to zero */ /* before calling scaling list */ ps_seq->u1_use_default_scaling_matrix_flag[i4_i] = 0; if(ps_seq->u1_seq_scaling_list_present_flag[i4_i]) { if(i4_i < 6) { ih264d_scaling_list( ps_seq->i2_scalinglist4x4[i4_i], 16, &ps_seq->u1_use_default_scaling_matrix_flag[i4_i], ps_bitstrm); } else { ih264d_scaling_list( ps_seq->i2_scalinglist8x8[i4_i - 6], 64, &ps_seq->u1_use_default_scaling_matrix_flag[i4_i], ps_bitstrm); } } } } } /*--------------------------------------------------------------------*/ /* Decode MaxFrameNum */ /*--------------------------------------------------------------------*/ u4_temp = 4 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_BITS_IN_FRAME_NUM) { return ERROR_INV_SPS_PPS_T; } ps_seq->u1_bits_in_frm_num = u4_temp; COPYTHECONTEXT("SPS: log2_max_frame_num_minus4", (ps_seq->u1_bits_in_frm_num - 4)); i2_max_frm_num = (1 << (ps_seq->u1_bits_in_frm_num)); ps_seq->u2_u4_max_pic_num_minus1 = i2_max_frm_num - 1; /*--------------------------------------------------------------------*/ /* Decode picture order count and related values */ /*--------------------------------------------------------------------*/ u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_PIC_ORDER_CNT_TYPE) { return ERROR_INV_POC_TYPE_T; } ps_seq->u1_pic_order_cnt_type = u4_temp; COPYTHECONTEXT("SPS: pic_order_cnt_type",ps_seq->u1_pic_order_cnt_type); ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle = 1; if(ps_seq->u1_pic_order_cnt_type == 0) { u4_temp = 4 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_BITS_IN_POC_LSB) { return ERROR_INV_SPS_PPS_T; } ps_seq->u1_log2_max_pic_order_cnt_lsb_minus = u4_temp; ps_seq->i4_max_pic_order_cntLsb = (1 << u4_temp); COPYTHECONTEXT("SPS: log2_max_pic_order_cnt_lsb_minus4",(u4_temp - 4)); } else if(ps_seq->u1_pic_order_cnt_type == 1) { ps_seq->u1_delta_pic_order_always_zero_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SPS: delta_pic_order_always_zero_flag", ps_seq->u1_delta_pic_order_always_zero_flag); ps_seq->i4_ofst_for_non_ref_pic = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_non_ref_pic", ps_seq->i4_ofst_for_non_ref_pic); ps_seq->i4_ofst_for_top_to_bottom_field = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_top_to_bottom_field", ps_seq->i4_ofst_for_top_to_bottom_field); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > 255) return ERROR_INV_SPS_PPS_T; ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle = u4_temp; COPYTHECONTEXT("SPS: num_ref_frames_in_pic_order_cnt_cycle", ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle); for(i = 0; i < ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle; i++) { ps_seq->i4_ofst_for_ref_frame[i] = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_ref_frame", ps_seq->i4_ofst_for_ref_frame[i]); } } u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if((u4_temp > H264_MAX_REF_PICS)) { return ERROR_NUM_REF; } /* Compare with older num_ref_frames is header is already once */ if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_num_ref_frames != u4_temp)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_num_ref_frames = u4_temp; COPYTHECONTEXT("SPS: num_ref_frames",ps_seq->u1_num_ref_frames); ps_seq->u1_gaps_in_frame_num_value_allowed_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SPS: gaps_in_frame_num_value_allowed_flag", ps_seq->u1_gaps_in_frame_num_value_allowed_flag); /*--------------------------------------------------------------------*/ /* Decode FrameWidth and FrameHeight and related values */ /*--------------------------------------------------------------------*/ ps_seq->u2_frm_wd_in_mbs = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: pic_width_in_mbs_minus1", ps_seq->u2_frm_wd_in_mbs - 1); u2_pic_wd = (ps_seq->u2_frm_wd_in_mbs << 4); pic_height_in_map_units_minus1 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_seq->u2_frm_ht_in_mbs = 1 + pic_height_in_map_units_minus1; u2_pic_ht = (ps_seq->u2_frm_ht_in_mbs << 4); /*--------------------------------------------------------------------*/ /* Get the value of MaxMbAddress and Number of bits needed for it */ /*--------------------------------------------------------------------*/ ps_seq->u2_max_mb_addr = (ps_seq->u2_frm_wd_in_mbs * ps_seq->u2_frm_ht_in_mbs) - 1; ps_seq->u2_total_num_of_mbs = ps_seq->u2_max_mb_addr + 1; ps_seq->u1_level_idc = ih264d_correct_level_idc( u1_level_idc, ps_seq->u2_total_num_of_mbs); u1_frm = ih264d_get_bit_h264(ps_bitstrm); if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_frame_mbs_only_flag != u1_frm)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_frame_mbs_only_flag = u1_frm; COPYTHECONTEXT("SPS: frame_mbs_only_flag", u1_frm); if(!u1_frm) { u2_pic_ht <<= 1; ps_seq->u1_mb_aff_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: mb_adaptive_frame_field_flag", ps_seq->u1_mb_aff_flag); } else ps_seq->u1_mb_aff_flag = 0; ps_seq->u1_direct_8x8_inference_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: direct_8x8_inference_flag", ps_seq->u1_direct_8x8_inference_flag); /* G050 */ u1_frame_cropping_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: frame_cropping_flag",u1_frame_cropping_flag); if(u1_frame_cropping_flag) { u1_frame_cropping_rect_left_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_left_offset", u1_frame_cropping_rect_left_ofst); u1_frame_cropping_rect_right_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_right_offset", u1_frame_cropping_rect_right_ofst); u1_frame_cropping_rect_top_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_top_offset", u1_frame_cropping_rect_top_ofst); u1_frame_cropping_rect_bottom_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_bottom_offset", u1_frame_cropping_rect_bottom_ofst); } /* G050 */ ps_seq->u1_vui_parameters_present_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: vui_parameters_present_flag", ps_seq->u1_vui_parameters_present_flag); u2_frm_wd_y = u2_pic_wd + (UWORD8)(PAD_LEN_Y_H << 1); if(1 == ps_dec->u4_share_disp_buf) { if(ps_dec->u4_app_disp_width > u2_frm_wd_y) u2_frm_wd_y = ps_dec->u4_app_disp_width; } u2_frm_ht_y = u2_pic_ht + (UWORD8)(PAD_LEN_Y_V << 2); u2_frm_wd_uv = u2_pic_wd + (UWORD8)(PAD_LEN_UV_H << 2); u2_frm_wd_uv = MAX(u2_frm_wd_uv, u2_frm_wd_y); u2_frm_ht_uv = (u2_pic_ht >> 1) + (UWORD8)(PAD_LEN_UV_V << 2); u2_frm_ht_uv = MAX(u2_frm_ht_uv, (u2_frm_ht_y >> 1)); /* Calculate display picture width, height and start u4_ofst from YUV420 */ /* pictute buffers as per cropping information parsed above */ { UWORD16 u2_rgt_ofst = 0; UWORD16 u2_lft_ofst = 0; UWORD16 u2_top_ofst = 0; UWORD16 u2_btm_ofst = 0; UWORD8 u1_frm_mbs_flag; UWORD8 u1_vert_mult_factor; if(u1_frame_cropping_flag) { /* Calculate right and left u4_ofst for cropped picture */ u2_rgt_ofst = u1_frame_cropping_rect_right_ofst << 1; u2_lft_ofst = u1_frame_cropping_rect_left_ofst << 1; /* Know frame MBs only u4_flag */ u1_frm_mbs_flag = (1 == ps_seq->u1_frame_mbs_only_flag); /* Simplify the vertical u4_ofst calculation from field/frame */ u1_vert_mult_factor = (2 - u1_frm_mbs_flag); /* Calculate bottom and top u4_ofst for cropped picture */ u2_btm_ofst = (u1_frame_cropping_rect_bottom_ofst << u1_vert_mult_factor); u2_top_ofst = (u1_frame_cropping_rect_top_ofst << u1_vert_mult_factor); } /* Calculate u4_ofst from start of YUV 420 picture buffer to start of*/ /* cropped picture buffer */ u2_crop_offset_y = (u2_frm_wd_y * u2_top_ofst) + (u2_lft_ofst); u2_crop_offset_uv = (u2_frm_wd_uv * (u2_top_ofst >> 1)) + (u2_lft_ofst >> 1) * YUV420SP_FACTOR; /* Calculate the display picture width and height based on crop */ /* information */ i4_cropped_ht = u2_pic_ht - (u2_btm_ofst + u2_top_ofst); i4_cropped_wd = u2_pic_wd - (u2_rgt_ofst + u2_lft_ofst); if((i4_cropped_ht < MB_SIZE) || (i4_cropped_wd < MB_SIZE)) { return ERROR_INV_SPS_PPS_T; } if((ps_dec->i4_header_decoded & 1) && (ps_dec->u2_pic_wd != u2_pic_wd)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } if((ps_dec->i4_header_decoded & 1) && (ps_dec->u2_pic_ht != u2_pic_ht)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } /* Check for unsupported resolutions */ if((u2_pic_wd > H264_MAX_FRAME_WIDTH) || (u2_pic_ht > H264_MAX_FRAME_HEIGHT) || (u2_pic_wd < H264_MIN_FRAME_WIDTH) || (u2_pic_ht < H264_MIN_FRAME_HEIGHT) || (u2_pic_wd * (UWORD32)u2_pic_ht > H264_MAX_FRAME_SIZE)) { return IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED; } /* If MBAff is enabled, decoder support is limited to streams with * width less than half of H264_MAX_FRAME_WIDTH. * In case of MBAff decoder processes two rows at a time */ if((u2_pic_wd << ps_seq->u1_mb_aff_flag) > H264_MAX_FRAME_WIDTH) { return IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED; } } /* Backup u4_num_reorder_frames if header is already decoded */ if((ps_dec->i4_header_decoded & 1) && (1 == ps_seq->u1_vui_parameters_present_flag) && (1 == ps_seq->s_vui.u1_bitstream_restriction_flag)) { u4_num_reorder_frames = ps_seq->s_vui.u4_num_reorder_frames; } else { u4_num_reorder_frames = -1; } if(1 == ps_seq->u1_vui_parameters_present_flag) { ret = ih264d_parse_vui_parametres(&ps_seq->s_vui, ps_bitstrm); if(ret != OK) return ret; } /* Compare older u4_num_reorder_frames with the new one if header is already decoded */ if((ps_dec->i4_header_decoded & 1) && (-1 != (WORD32)u4_num_reorder_frames) && (1 == ps_seq->u1_vui_parameters_present_flag) && (1 == ps_seq->s_vui.u1_bitstream_restriction_flag) && (ps_seq->s_vui.u4_num_reorder_frames != u4_num_reorder_frames)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } /* In case bitstream read has exceeded the filled size, then return an error */ if (ps_bitstrm->u4_ofst > ps_bitstrm->u4_max_ofst) { return ERROR_INV_SPS_PPS_T; } /*--------------------------------------------------------------------*/ /* All initializations to ps_dec are beyond this point */ /*--------------------------------------------------------------------*/ ps_dec->u2_disp_height = i4_cropped_ht; ps_dec->u2_disp_width = i4_cropped_wd; ps_dec->u2_pic_wd = u2_pic_wd; ps_dec->u2_pic_ht = u2_pic_ht; /* Determining the Width and Height of Frame from that of Picture */ ps_dec->u2_frm_wd_y = u2_frm_wd_y; ps_dec->u2_frm_ht_y = u2_frm_ht_y; ps_dec->u2_frm_wd_uv = u2_frm_wd_uv; ps_dec->u2_frm_ht_uv = u2_frm_ht_uv; ps_dec->s_pad_mgr.u1_pad_len_y_v = (UWORD8)(PAD_LEN_Y_V << (1 - u1_frm)); ps_dec->s_pad_mgr.u1_pad_len_cr_v = (UWORD8)(PAD_LEN_UV_V << (1 - u1_frm)); ps_dec->u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; ps_dec->u2_frm_ht_in_mbs = ps_seq->u2_frm_ht_in_mbs; ps_dec->u2_crop_offset_y = u2_crop_offset_y; ps_dec->u2_crop_offset_uv = u2_crop_offset_uv; ps_seq->u1_is_valid = TRUE; ps_dec->ps_sps[u1_seq_parameter_set_id] = *ps_seq; ps_dec->ps_cur_sps = &ps_dec->ps_sps[u1_seq_parameter_set_id]; return OK; }
CWE-200
188,127
10,209
152275460707939225838004820212876758473
null
null
null
php
c351b47ce85a3a147cfa801fa9f0149ab4160834
1
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; } }
CWE-119
177,737
10,257
12931410984739733148384395008576936463
null
null
null
php
12fe4e90be7bfa2a763197079f68f5568a14e071
1
static int scan(Scanner *s) { uchar *cursor = s->cur; char *str, *ptr = NULL; std: s->tok = cursor; s->len = 0; #line 311 "ext/date/lib/parse_iso_intervals.re" #line 291 "ext/date/lib/parse_iso_intervals.c" { YYCTYPE yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); if ((YYLIMIT - YYCURSOR) < 20) YYFILL(20); yych = *YYCURSOR; if (yych <= ',') { if (yych <= '\n') { if (yych <= 0x00) goto yy9; if (yych <= 0x08) goto yy11; if (yych <= '\t') goto yy7; goto yy9; } else { if (yych == ' ') goto yy7; if (yych <= '+') goto yy11; goto yy7; } } else { if (yych <= 'O') { if (yych <= '-') goto yy11; if (yych <= '/') goto yy7; if (yych <= '9') goto yy4; goto yy11; } else { if (yych <= 'P') goto yy5; if (yych != 'R') goto yy11; } } YYDEBUG(2, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '/') goto yy3; if (yych <= '9') goto yy98; yy3: YYDEBUG(3, *YYCURSOR); #line 424 "ext/date/lib/parse_iso_intervals.re" { add_error(s, "Unexpected character"); goto std; } #line 366 "ext/date/lib/parse_iso_intervals.c" yy4: YYDEBUG(4, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy3; if (yych <= '9') goto yy59; goto yy3; yy5: YYDEBUG(5, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy12; if (yych == 'T') goto yy14; yy6: YYDEBUG(6, *YYCURSOR); #line 351 "ext/date/lib/parse_iso_intervals.re" { timelib_sll nr; int in_time = 0; DEBUG_OUTPUT("period"); TIMELIB_INIT; ptr++; do { if ( *ptr == 'T' ) { in_time = 1; ptr++; } if ( *ptr == '\0' ) { add_error(s, "Missing expected time part"); break; } nr = timelib_get_unsigned_nr((char **) &ptr, 12); switch (*ptr) { case 'Y': s->period->y = nr; break; case 'W': s->period->d = nr * 7; break; case 'D': s->period->d = nr; break; case 'H': s->period->h = nr; break; case 'S': s->period->s = nr; break; case 'M': if (in_time) { s->period->i = nr; } else { s->period->m = nr; } break; default: add_error(s, "Undefined period specifier"); break; } ptr++; } while (*ptr); s->have_period = 1; TIMELIB_DEINIT; return TIMELIB_PERIOD; } #line 424 "ext/date/lib/parse_iso_intervals.c" yy7: YYDEBUG(7, *YYCURSOR); ++YYCURSOR; YYDEBUG(8, *YYCURSOR); #line 413 "ext/date/lib/parse_iso_intervals.re" { goto std; } #line 433 "ext/date/lib/parse_iso_intervals.c" yy9: YYDEBUG(9, *YYCURSOR); ++YYCURSOR; YYDEBUG(10, *YYCURSOR); #line 418 "ext/date/lib/parse_iso_intervals.re" { s->pos = cursor; s->line++; goto std; } #line 443 "ext/date/lib/parse_iso_intervals.c" yy11: YYDEBUG(11, *YYCURSOR); yych = *++YYCURSOR; goto yy3; yy12: YYDEBUG(12, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '9') { if (yych >= '0') goto yy25; } else { if (yych == 'D') goto yy24; } } else { if (yych <= 'W') { if (yych <= 'M') goto yy27; if (yych >= 'W') goto yy26; } else { if (yych == 'Y') goto yy28; } } yy13: YYDEBUG(13, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 0) { goto yy3; } else { goto yy6; } yy14: YYDEBUG(14, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 128) { goto yy15; } goto yy6; yy15: YYDEBUG(15, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; YYDEBUG(16, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy15; } if (yych <= 'L') { if (yych == 'H') goto yy19; goto yy13; } else { if (yych <= 'M') goto yy18; if (yych != 'S') goto yy13; } yy17: YYDEBUG(17, *YYCURSOR); yych = *++YYCURSOR; goto yy6; yy18: YYDEBUG(18, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy22; goto yy6; yy19: YYDEBUG(19, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych >= ':') goto yy6; yy20: YYDEBUG(20, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; YYDEBUG(21, *YYCURSOR); if (yych <= 'L') { if (yych <= '/') goto yy13; if (yych <= '9') goto yy20; goto yy13; } else { if (yych <= 'M') goto yy18; if (yych == 'S') goto yy17; goto yy13; } yy22: YYDEBUG(22, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(23, *YYCURSOR); if (yych <= '/') goto yy13; if (yych <= '9') goto yy22; if (yych == 'S') goto yy17; goto yy13; yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy14; goto yy6; yy25: YYDEBUG(25, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '9') { if (yych <= '/') goto yy13; goto yy35; } else { if (yych == 'D') goto yy24; goto yy13; } } else { if (yych <= 'W') { if (yych <= 'M') goto yy27; if (yych <= 'V') goto yy13; } else { if (yych == 'Y') goto yy28; goto yy13; } } yy26: YYDEBUG(26, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy33; if (yych == 'T') goto yy14; goto yy6; yy27: YYDEBUG(27, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy31; if (yych == 'T') goto yy14; goto yy6; yy28: YYDEBUG(28, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy29; if (yych == 'T') goto yy14; goto yy6; yy29: YYDEBUG(29, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; YYDEBUG(30, *YYCURSOR); if (yych <= 'D') { if (yych <= '/') goto yy13; if (yych <= '9') goto yy29; if (yych <= 'C') goto yy13; goto yy24; } else { if (yych <= 'M') { if (yych <= 'L') goto yy13; goto yy27; } else { if (yych == 'W') goto yy26; goto yy13; } } yy31: YYDEBUG(31, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; YYDEBUG(32, *YYCURSOR); if (yych <= 'C') { if (yych <= '/') goto yy13; if (yych <= '9') goto yy31; goto yy13; } else { if (yych <= 'D') goto yy24; if (yych == 'W') goto yy26; goto yy13; } yy33: YYDEBUG(33, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; YYDEBUG(34, *YYCURSOR); if (yych <= '/') goto yy13; if (yych <= '9') goto yy33; if (yych == 'D') goto yy24; goto yy13; yy35: YYDEBUG(35, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '9') { if (yych <= '/') goto yy13; } else { if (yych == 'D') goto yy24; goto yy13; } } else { if (yych <= 'W') { if (yych <= 'M') goto yy27; if (yych <= 'V') goto yy13; goto yy26; } else { if (yych == 'Y') goto yy28; goto yy13; } } YYDEBUG(36, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy39; YYDEBUG(37, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy40; if (yych <= '1') goto yy41; goto yy13; yy38: YYDEBUG(38, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; yy39: YYDEBUG(39, *YYCURSOR); if (yych <= 'L') { if (yych <= '9') { if (yych <= '/') goto yy13; goto yy38; } else { if (yych == 'D') goto yy24; goto yy13; } } else { if (yych <= 'W') { if (yych <= 'M') goto yy27; if (yych <= 'V') goto yy13; goto yy26; } else { if (yych == 'Y') goto yy28; goto yy13; } } yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy42; goto yy13; yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '3') goto yy13; yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy13; YYDEBUG(43, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy44; if (yych <= '2') goto yy45; if (yych <= '3') goto yy46; goto yy13; yy44: YYDEBUG(44, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy47; goto yy13; yy45: YYDEBUG(45, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy47; goto yy13; yy46: YYDEBUG(46, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '2') goto yy13; yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy13; YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '1') goto yy49; if (yych <= '2') goto yy50; goto yy13; yy49: YYDEBUG(49, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy51; goto yy13; yy50: YYDEBUG(50, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '5') goto yy13; yy51: YYDEBUG(51, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy13; YYDEBUG(52, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(53, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(54, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy13; YYDEBUG(55, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(56, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(57, *YYCURSOR); ++YYCURSOR; YYDEBUG(58, *YYCURSOR); #line 393 "ext/date/lib/parse_iso_intervals.re" { DEBUG_OUTPUT("combinedrep"); TIMELIB_INIT; s->period->y = timelib_get_unsigned_nr((char **) &ptr, 4); ptr++; s->period->m = timelib_get_unsigned_nr((char **) &ptr, 2); ptr++; s->period->d = timelib_get_unsigned_nr((char **) &ptr, 2); ptr++; s->period->h = timelib_get_unsigned_nr((char **) &ptr, 2); ptr++; s->period->i = timelib_get_unsigned_nr((char **) &ptr, 2); ptr++; s->period->s = timelib_get_unsigned_nr((char **) &ptr, 2); s->have_period = 1; TIMELIB_DEINIT; return TIMELIB_PERIOD; } #line 792 "ext/date/lib/parse_iso_intervals.c" yy59: YYDEBUG(59, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(60, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(61, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '-') goto yy64; goto yy13; } else { if (yych <= '0') goto yy62; if (yych <= '1') goto yy63; goto yy13; } yy62: YYDEBUG(62, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy13; if (yych <= '9') goto yy85; goto yy13; yy63: YYDEBUG(63, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '2') goto yy85; goto yy13; yy64: YYDEBUG(64, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy65; if (yych <= '1') goto yy66; goto yy13; yy65: YYDEBUG(65, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy13; if (yych <= '9') goto yy67; goto yy13; yy66: YYDEBUG(66, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '3') goto yy13; yy67: YYDEBUG(67, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy13; YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy69; if (yych <= '2') goto yy70; if (yych <= '3') goto yy71; goto yy13; yy69: YYDEBUG(69, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy13; if (yych <= '9') goto yy72; goto yy13; yy70: YYDEBUG(70, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy72; goto yy13; yy71: YYDEBUG(71, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '2') goto yy13; yy72: YYDEBUG(72, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy13; YYDEBUG(73, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '1') goto yy74; if (yych <= '2') goto yy75; goto yy13; yy74: YYDEBUG(74, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy76; goto yy13; yy75: YYDEBUG(75, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '5') goto yy13; yy76: YYDEBUG(76, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy13; YYDEBUG(77, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(78, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy13; YYDEBUG(80, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(81, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'Z') goto yy13; yy83: YYDEBUG(83, *YYCURSOR); ++YYCURSOR; YYDEBUG(84, *YYCURSOR); #line 327 "ext/date/lib/parse_iso_intervals.re" { timelib_time *current; if (s->have_date || s->have_period) { current = s->end; s->have_end_date = 1; } else { current = s->begin; s->have_begin_date = 1; } DEBUG_OUTPUT("datetimebasic | datetimeextended"); TIMELIB_INIT; current->y = timelib_get_nr((char **) &ptr, 4); current->m = timelib_get_nr((char **) &ptr, 2); current->d = timelib_get_nr((char **) &ptr, 2); current->h = timelib_get_nr((char **) &ptr, 2); current->i = timelib_get_nr((char **) &ptr, 2); current->s = timelib_get_nr((char **) &ptr, 2); s->have_date = 1; TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 944 "ext/date/lib/parse_iso_intervals.c" yy85: YYDEBUG(85, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy86; if (yych <= '2') goto yy87; if (yych <= '3') goto yy88; goto yy13; yy86: YYDEBUG(86, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy13; if (yych <= '9') goto yy89; goto yy13; yy87: YYDEBUG(87, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy89; goto yy13; yy88: YYDEBUG(88, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '2') goto yy13; yy89: YYDEBUG(89, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy13; YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '1') goto yy91; if (yych <= '2') goto yy92; goto yy13; yy91: YYDEBUG(91, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy93; goto yy13; yy92: YYDEBUG(92, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '5') goto yy13; yy93: YYDEBUG(93, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(95, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(96, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(97, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Z') goto yy83; goto yy13; yy98: YYDEBUG(98, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(99, *YYCURSOR); if (yych <= '/') goto yy100; if (yych <= '9') goto yy98; yy100: YYDEBUG(100, *YYCURSOR); #line 316 "ext/date/lib/parse_iso_intervals.re" { DEBUG_OUTPUT("recurrences"); TIMELIB_INIT; ptr++; s->recurrences = timelib_get_unsigned_nr((char **) &ptr, 9); TIMELIB_DEINIT; s->have_recurrences = 1; return TIMELIB_PERIOD; } #line 1032 "ext/date/lib/parse_iso_intervals.c" } #line 428 "ext/date/lib/parse_iso_intervals.re" }
CWE-119
177,738
10,258
15441167986489398405925562744980156713
null
null
null
php
c1224573c773b6845e83505f717fbf820fc18415
1
static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ { /* This is how the time string is formatted: snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ time_t ret; struct tm thetime; char * strbuf; char * thestr; long gmadjust = 0; if (timestr->length < 13) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "extension author too lazy to parse %s correctly", timestr->data); return (time_t)-1; } strbuf = estrdup((char *)timestr->data); memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ thestr = strbuf + timestr->length - 3; thetime.tm_sec = atoi(thestr); *thestr = '\0'; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } thetime.tm_isdst = -1; ret = mktime(&thetime); #if HAVE_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #else /* ** If correcting for daylight savings time, we set the adjustment to ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and ** set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600); #endif ret += gmadjust; efree(strbuf); return ret; } /* }}} */
CWE-119
177,740
10,259
313253356362298262746583588257006144055
null
null
null
php
1ddf72180a52d247db88ea42a3e35f824a8fbda1
1
static php_stream *phar_make_dirstream(char *dir, HashTable *manifest TSRMLS_DC) /* {{{ */ { HashTable *data; int dirlen = strlen(dir); phar_zstr key; char *entry, *found, *save, *str_key; uint keylen; ulong unused; ALLOC_HASHTABLE(data); zend_hash_init(data, 64, zend_get_hash_value, NULL, 0); if ((*dir == '/' && dirlen == 1 && (manifest->nNumOfElements == 0)) || (dirlen >= sizeof(".phar")-1 && !memcmp(dir, ".phar", sizeof(".phar")-1))) { /* make empty root directory for empty phar */ /* make empty directory for .phar magic directory */ efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } zend_hash_internal_pointer_reset(manifest); while (FAILURE != zend_hash_has_more_elements(manifest)) { if (HASH_KEY_IS_STRING != zend_hash_get_current_key_ex(manifest, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen <= (uint)dirlen) { if (keylen < (uint)dirlen || !strncmp(str_key, dir, dirlen)) { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } if (*dir == '/') { /* root directory */ if (keylen >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { PHAR_STR_FREE(str_key); /* do not add any magic entries to this directory */ if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } if (NULL != (found = (char *) memchr(str_key, '/', keylen))) { /* the entry has a path separator and is a subdirectory */ entry = (char *) safe_emalloc(found - str_key, 1, 1); memcpy(entry, str_key, found - str_key); keylen = found - str_key; entry[keylen] = '\0'; } else { entry = (char *) safe_emalloc(keylen, 1, 1); memcpy(entry, str_key, keylen); entry[keylen] = '\0'; } PHAR_STR_FREE(str_key); goto PHAR_ADD_ENTRY; } else { if (0 != memcmp(str_key, dir, dirlen)) { /* entry in directory not found */ PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } else { if (str_key[dirlen] != '/') { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } } save = str_key; save += dirlen + 1; /* seek to just past the path separator */ if (NULL != (found = (char *) memchr(save, '/', keylen - dirlen - 1))) { /* is subdirectory */ save -= dirlen + 1; entry = (char *) safe_emalloc(found - save + dirlen, 1, 1); memcpy(entry, save + dirlen + 1, found - save - dirlen - 1); keylen = found - save - dirlen - 1; entry[keylen] = '\0'; } else { /* is file */ save -= dirlen + 1; entry = (char *) safe_emalloc(keylen - dirlen, 1, 1); memcpy(entry, save + dirlen + 1, keylen - dirlen - 1); entry[keylen - dirlen - 1] = '\0'; keylen = keylen - dirlen - 1; } PHAR_STR_FREE(str_key); PHAR_ADD_ENTRY: if (keylen) { phar_add_empty(data, entry, keylen); } efree(entry); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } } if (FAILURE != zend_hash_has_more_elements(data)) { efree(dir); if (zend_hash_sort(data, zend_qsort, phar_compare_dir_name, 0 TSRMLS_CC) == FAILURE) { FREE_HASHTABLE(data); return NULL; } return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } else { efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } } /* }}}*/
CWE-189
177,743
10,260
196906810819803117252167181256778455219
null
null
null
php
1ddf72180a52d247db88ea42a3e35f824a8fbda2
1
void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */ { const char *s; while ((s = zend_memrchr(filename, '/', filename_len))) { filename_len = s - filename; if (FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) { break; } } } /* }}} */
CWE-189
177,744
10,261
191317651340703261586509443599515973094
null
null
null
php
d698f0ae51f67c9cce870b09c59df3d6ba959244
1
int phar_get_entry_data(phar_entry_data **ret, char *fname, int fname_len, char *path, int path_len, char *mode, char allow_dir, char **error, int security TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar_entry_info *entry; int for_write = mode[0] != 'r' || mode[1] == '+'; int for_append = mode[0] == 'a'; int for_create = mode[0] != 'r'; int for_trunc = mode[0] == 'w'; if (!ret) { return FAILURE; } *ret = NULL; if (error) { *error = NULL; } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, error TSRMLS_CC)) { return FAILURE; } if (for_write && PHAR_G(readonly) && !phar->is_data) { if (error) { spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, disabled by ini setting", path, fname); } return FAILURE; } if (!path_len) { if (error) { spprintf(error, 4096, "phar error: file \"\" in phar \"%s\" cannot be empty", fname); } return FAILURE; } really_get_entry: if (allow_dir) { if ((entry = phar_get_entry_info_dir(phar, path, path_len, allow_dir, for_create && !PHAR_G(readonly) && !phar->is_data ? NULL : error, security TSRMLS_CC)) == NULL) { if (for_create && (!PHAR_G(readonly) || phar->is_data)) { return SUCCESS; } return FAILURE; } } else { if ((entry = phar_get_entry_info(phar, path, path_len, for_create && !PHAR_G(readonly) && !phar->is_data ? NULL : error, security TSRMLS_CC)) == NULL) { if (for_create && (!PHAR_G(readonly) || phar->is_data)) { return SUCCESS; } return FAILURE; } } if (for_write && phar->is_persistent) { if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, could not make cached phar writeable", path, fname); } return FAILURE; } else { goto really_get_entry; } } if (entry->is_modified && !for_write) { if (error) { spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for reading, writable file pointers are open", path, fname); } return FAILURE; } if (entry->fp_refcount && for_write) { if (error) { spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, readable file pointers are open", path, fname); } return FAILURE; } if (entry->is_deleted) { if (!for_create) { return FAILURE; } entry->is_deleted = 0; } if (entry->is_dir) { *ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data)); (*ret)->position = 0; (*ret)->fp = NULL; (*ret)->phar = phar; (*ret)->for_write = for_write; (*ret)->internal_file = entry; (*ret)->is_zip = entry->is_zip; (*ret)->is_tar = entry->is_tar; if (!phar->is_persistent) { ++(entry->phar->refcount); ++(entry->fp_refcount); } return SUCCESS; } if (entry->fp_type == PHAR_MOD) { if (for_trunc) { if (FAILURE == phar_create_writeable_entry(phar, entry, error TSRMLS_CC)) { return FAILURE; } } else if (for_append) { phar_seek_efp(entry, 0, SEEK_END, 0, 0 TSRMLS_CC); } } else { if (for_write) { if (entry->link) { efree(entry->link); entry->link = NULL; entry->tar_type = (entry->is_tar ? TAR_FILE : '\0'); } if (for_trunc) { if (FAILURE == phar_create_writeable_entry(phar, entry, error TSRMLS_CC)) { return FAILURE; } } else { if (FAILURE == phar_separate_entry_fp(entry, error TSRMLS_CC)) { return FAILURE; } } } else { if (FAILURE == phar_open_entry_fp(entry, error, 1 TSRMLS_CC)) { return FAILURE; } } } *ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data)); (*ret)->position = 0; (*ret)->phar = phar; (*ret)->for_write = for_write; (*ret)->internal_file = entry; (*ret)->is_zip = entry->is_zip; (*ret)->is_tar = entry->is_tar; (*ret)->fp = phar_get_efp(entry, 1 TSRMLS_CC); if (entry->link) { (*ret)->zero = phar_get_fp_offset(phar_get_link_source(entry TSRMLS_CC) TSRMLS_CC); } else { (*ret)->zero = phar_get_fp_offset(entry TSRMLS_CC); } } return SUCCESS; } /* }}} */ /** * Create a new dummy file slot within a writeable phar for a newly created file */ phar_entry_data *phar_get_or_create_entry_data(char *fname, int fname_len, char *path, int path_len, char *mode, char allow_dir, char **error, int security TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar_entry_info *entry, etemp; phar_entry_data *ret; const char *pcr_error; char is_dir; #ifdef PHP_WIN32 phar_unixify_path_separators(path, path_len); #endif is_dir = (path_len && path[path_len - 1] == '/') ? 1 : 0; if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, error TSRMLS_CC)) { return NULL; } if (FAILURE == phar_get_entry_data(&ret, fname, fname_len, path, path_len, mode, allow_dir, error, security TSRMLS_CC)) { return NULL; } else if (ret) { return ret; } if (phar_path_check(&path, &path_len, &pcr_error) > pcr_is_ok) { if (error) { spprintf(error, 0, "phar error: invalid path \"%s\" contains %s", path, pcr_error); } return NULL; } if (phar->is_persistent && FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be created, could not make cached phar writeable", path, fname); } return NULL; } /* create a new phar data holder */ ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data)); /* create an entry, this is a new file */ memset(&etemp, 0, sizeof(phar_entry_info)); etemp.filename_len = path_len; etemp.fp_type = PHAR_MOD; etemp.fp = php_stream_fopen_tmpfile(); if (!etemp.fp) { if (error) { spprintf(error, 0, "phar error: unable to create temporary file"); } efree(ret); return NULL; } etemp.fp_refcount = 1; if (allow_dir == 2) { etemp.is_dir = 1; etemp.flags = etemp.old_flags = PHAR_ENT_PERM_DEF_DIR; } else { etemp.flags = etemp.old_flags = PHAR_ENT_PERM_DEF_FILE; } if (is_dir) { etemp.filename_len--; /* strip trailing / */ path_len--; } phar_add_virtual_dirs(phar, path, path_len TSRMLS_CC); etemp.is_modified = 1; etemp.timestamp = time(0); etemp.is_crc_checked = 1; etemp.phar = phar; etemp.filename = estrndup(path, path_len); etemp.is_zip = phar->is_zip; if (phar->is_tar) { etemp.is_tar = phar->is_tar; etemp.tar_type = etemp.is_dir ? TAR_DIR : TAR_FILE; } if (FAILURE == zend_hash_add(&phar->manifest, etemp.filename, path_len, (void*)&etemp, sizeof(phar_entry_info), (void **) &entry)) { php_stream_close(etemp.fp); if (error) { spprintf(error, 0, "phar error: unable to add new entry \"%s\" to phar \"%s\"", etemp.filename, phar->fname); } efree(ret); efree(etemp.filename); return NULL; } if (!entry) { php_stream_close(etemp.fp); efree(etemp.filename); efree(ret); return NULL; } ++(phar->refcount); ret->phar = phar; ret->fp = entry->fp; ret->position = ret->zero = 0; ret->for_write = 1; ret->is_zip = entry->is_zip; ret->is_tar = entry->is_tar; ret->internal_file = entry; return ret; } /* }}} */ /* initialize a phar_archive_data's read-only fp for existing phar data */ int phar_open_archive_fp(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar_get_pharfp(phar TSRMLS_CC)) { return SUCCESS; } if (php_check_open_basedir(phar->fname TSRMLS_CC)) { return FAILURE; } phar_set_pharfp(phar, php_stream_open_wrapper(phar->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, NULL) TSRMLS_CC); if (!phar_get_pharfp(phar TSRMLS_CC)) { return FAILURE; } return SUCCESS; } /* }}} */ /* copy file data from an existing to a new phar_entry_info that is not in the manifest */ int phar_copy_entry_fp(phar_entry_info *source, phar_entry_info *dest, char **error TSRMLS_DC) /* {{{ */ { phar_entry_info *link; if (FAILURE == phar_open_entry_fp(source, error, 1 TSRMLS_CC)) { return FAILURE; } if (dest->link) { efree(dest->link); dest->link = NULL; dest->tar_type = (dest->is_tar ? TAR_FILE : '\0'); } dest->fp_type = PHAR_MOD; dest->offset = 0; dest->is_modified = 1; dest->fp = php_stream_fopen_tmpfile(); if (dest->fp == NULL) { spprintf(error, 0, "phar error: unable to create temporary file"); return EOF; } phar_seek_efp(source, 0, SEEK_SET, 0, 1 TSRMLS_CC); link = phar_get_link_source(source TSRMLS_CC); if (!link) { link = source; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), dest->fp, link->uncompressed_filesize, NULL)) { php_stream_close(dest->fp); dest->fp_type = PHAR_FP; if (error) { spprintf(error, 4096, "phar error: unable to copy contents of file \"%s\" to \"%s\" in phar archive \"%s\"", source->filename, dest->filename, source->phar->fname); } return FAILURE; } return SUCCESS; } /* }}} */ /* open and decompress a compressed phar entry */ int phar_open_entry_fp(phar_entry_info *entry, char **error, int follow_links TSRMLS_DC) /* {{{ */ { php_stream_filter *filter; phar_archive_data *phar = entry->phar; char *filtername; off_t loc; php_stream *ufp; phar_entry_data dummy; if (follow_links && entry->link) { phar_entry_info *link_entry = phar_get_link_source(entry TSRMLS_CC); if (link_entry && link_entry != entry) { return phar_open_entry_fp(link_entry, error, 1 TSRMLS_CC); } } if (entry->is_modified) { return SUCCESS; } if (entry->fp_type == PHAR_TMP) { if (!entry->fp) { entry->fp = php_stream_open_wrapper(entry->tmp, "rb", STREAM_MUST_SEEK|0, NULL); } return SUCCESS; } if (entry->fp_type != PHAR_FP) { /* either newly created or already modified */ return SUCCESS; } if (!phar_get_pharfp(phar TSRMLS_CC)) { if (FAILURE == phar_open_archive_fp(phar TSRMLS_CC)) { spprintf(error, 4096, "phar error: Cannot open phar archive \"%s\" for reading", phar->fname); return FAILURE; } } if ((entry->old_flags && !(entry->old_flags & PHAR_ENT_COMPRESSION_MASK)) || !(entry->flags & PHAR_ENT_COMPRESSION_MASK)) { dummy.internal_file = entry; dummy.phar = phar; dummy.zero = entry->offset; dummy.fp = phar_get_pharfp(phar TSRMLS_CC); if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 1 TSRMLS_CC)) { return FAILURE; } return SUCCESS; } if (!phar_get_entrypufp(entry TSRMLS_CC)) { phar_set_entrypufp(entry, php_stream_fopen_tmpfile() TSRMLS_CC); if (!phar_get_entrypufp(entry TSRMLS_CC)) { spprintf(error, 4096, "phar error: Cannot open temporary file for decompressing phar archive \"%s\" file \"%s\"", phar->fname, entry->filename); return FAILURE; } } dummy.internal_file = entry; dummy.phar = phar; dummy.zero = entry->offset; dummy.fp = phar_get_pharfp(phar TSRMLS_CC); if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 1 TSRMLS_CC)) { return FAILURE; } ufp = phar_get_entrypufp(entry TSRMLS_CC); if ((filtername = phar_decompress_filter(entry, 0)) != NULL) { filter = php_stream_filter_create(filtername, NULL, 0 TSRMLS_CC); } else { filter = NULL; } if (!filter) { spprintf(error, 4096, "phar error: unable to read phar \"%s\" (cannot create %s filter while decompressing file \"%s\")", phar->fname, phar_decompress_filter(entry, 1), entry->filename); return FAILURE; } /* now we can safely use proper decompression */ /* save the new offset location within ufp */ php_stream_seek(ufp, 0, SEEK_END); loc = php_stream_tell(ufp); php_stream_filter_append(&ufp->writefilters, filter); php_stream_seek(phar_get_entrypfp(entry TSRMLS_CC), phar_get_fp_offset(entry TSRMLS_CC), SEEK_SET); if (entry->uncompressed_filesize) { if (SUCCESS != phar_stream_copy_to_stream(phar_get_entrypfp(entry TSRMLS_CC), ufp, entry->compressed_filesize, NULL)) { spprintf(error, 4096, "phar error: internal corruption of phar \"%s\" (actual filesize mismatch on file \"%s\")", phar->fname, entry->filename); php_stream_filter_remove(filter, 1 TSRMLS_CC); return FAILURE; } } php_stream_filter_flush(filter, 1); php_stream_flush(ufp); php_stream_filter_remove(filter, 1 TSRMLS_CC); if (php_stream_tell(ufp) - loc != (off_t) entry->uncompressed_filesize) { spprintf(error, 4096, "phar error: internal corruption of phar \"%s\" (actual filesize mismatch on file \"%s\")", phar->fname, entry->filename); return FAILURE; } entry->old_flags = entry->flags; /* this is now the new location of the file contents within this fp */ phar_set_fp_type(entry, PHAR_UFP, loc TSRMLS_CC); dummy.zero = entry->offset; dummy.fp = ufp; if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 0 TSRMLS_CC)) { return FAILURE; } return SUCCESS; } /* }}} */ int phar_create_writeable_entry(phar_archive_data *phar, phar_entry_info *entry, char **error TSRMLS_DC) /* {{{ */ { if (entry->fp_type == PHAR_MOD) { /* already newly created, truncate */ php_stream_truncate_set_size(entry->fp, 0); entry->old_flags = entry->flags; entry->is_modified = 1; phar->is_modified = 1; /* reset file size */ entry->uncompressed_filesize = 0; entry->compressed_filesize = 0; entry->crc32 = 0; entry->flags = PHAR_ENT_PERM_DEF_FILE; entry->fp_type = PHAR_MOD; entry->offset = 0; return SUCCESS; } if (error) { *error = NULL; } /* open a new temp file for writing */ if (entry->link) { efree(entry->link); entry->link = NULL; entry->tar_type = (entry->is_tar ? TAR_FILE : '\0'); } entry->fp = php_stream_fopen_tmpfile(); if (!entry->fp) { if (error) { spprintf(error, 0, "phar error: unable to create temporary file"); } return FAILURE; } entry->old_flags = entry->flags; entry->is_modified = 1; phar->is_modified = 1; /* reset file size */ entry->uncompressed_filesize = 0; entry->compressed_filesize = 0; entry->crc32 = 0; entry->flags = PHAR_ENT_PERM_DEF_FILE; entry->fp_type = PHAR_MOD; entry->offset = 0; return SUCCESS; } /* }}} */ int phar_separate_entry_fp(phar_entry_info *entry, char **error TSRMLS_DC) /* {{{ */ { php_stream *fp; phar_entry_info *link; if (FAILURE == phar_open_entry_fp(entry, error, 1 TSRMLS_CC)) { return FAILURE; } if (entry->fp_type == PHAR_MOD) { return SUCCESS; } fp = php_stream_fopen_tmpfile(); if (fp == NULL) { spprintf(error, 0, "phar error: unable to create temporary file"); return FAILURE; } phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC); link = phar_get_link_source(entry TSRMLS_CC); if (!link) { link = entry; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) { if (error) { spprintf(error, 4096, "phar error: cannot separate entry file \"%s\" contents in phar archive \"%s\" for write access", entry->filename, entry->phar->fname); } return FAILURE; } if (entry->link) { efree(entry->link); entry->link = NULL; entry->tar_type = (entry->is_tar ? TAR_FILE : '\0'); } entry->offset = 0; entry->fp = fp; entry->fp_type = PHAR_MOD; entry->is_modified = 1; return SUCCESS; } /* }}} */ /** * helper function to open an internal file's fp just-in-time */ phar_entry_info * phar_open_jit(phar_archive_data *phar, phar_entry_info *entry, char **error TSRMLS_DC) /* {{{ */ { if (error) { *error = NULL; } /* seek to start of internal file and read it */ if (FAILURE == phar_open_entry_fp(entry, error, 1 TSRMLS_CC)) { return NULL; } if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) { spprintf(error, 4096, "phar error: cannot seek to start of file \"%s\" in phar \"%s\"", entry->filename, phar->fname); return NULL; } return entry; } /* }}} */ PHP_PHAR_API int phar_resolve_alias(char *alias, int alias_len, char **filename, int *filename_len TSRMLS_DC) /* {{{ */ { phar_archive_data **fd_ptr; if (PHAR_GLOBALS->phar_alias_map.arBuckets && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void**)&fd_ptr)) { *filename = (*fd_ptr)->fname; *filename_len = (*fd_ptr)->fname_len; return SUCCESS; } return FAILURE; } /* }}} */ int phar_free_alias(phar_archive_data *phar, char *alias, int alias_len TSRMLS_DC) /* {{{ */ { if (phar->refcount || phar->is_persistent) { return FAILURE; } /* this archive has no open references, so emit an E_STRICT and remove it */ if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { return FAILURE; } /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; return SUCCESS; } /* }}} */ /** * Looks up a phar archive in the filename map, connecting it to the alias * (if any) or returns null */ int phar_get_archive(phar_archive_data **archive, char *fname, int fname_len, char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *fd, **fd_ptr; char *my_realpath, *save; int save_len; ulong fhash, ahash = 0; phar_request_initialize(TSRMLS_C); if (error) { *error = NULL; } *archive = NULL; if (PHAR_G(last_phar) && fname_len == PHAR_G(last_phar_name_len) && !memcmp(fname, PHAR_G(last_phar_name), fname_len)) { *archive = PHAR_G(last_phar); if (alias && alias_len) { if (!PHAR_G(last_phar)->is_temporary_alias && (alias_len != PHAR_G(last_phar)->alias_len || memcmp(PHAR_G(last_phar)->alias, alias, alias_len))) { if (error) { spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, PHAR_G(last_phar)->fname, fname); } *archive = NULL; return FAILURE; } if (PHAR_G(last_phar)->alias_len && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), PHAR_G(last_phar)->alias, PHAR_G(last_phar)->alias_len, (void**)&fd_ptr)) { zend_hash_del(&(PHAR_GLOBALS->phar_alias_map), PHAR_G(last_phar)->alias, PHAR_G(last_phar)->alias_len); } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&(*archive), sizeof(phar_archive_data*), NULL); PHAR_G(last_alias) = alias; PHAR_G(last_alias_len) = alias_len; } return SUCCESS; } if (alias && alias_len && PHAR_G(last_phar) && alias_len == PHAR_G(last_alias_len) && !memcmp(alias, PHAR_G(last_alias), alias_len)) { fd = PHAR_G(last_phar); fd_ptr = &fd; goto alias_success; } if (alias && alias_len) { ahash = zend_inline_hash_func(alias, alias_len); if (SUCCESS == zend_hash_quick_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, ahash, (void**)&fd_ptr)) { alias_success: if (fname && (fname_len != (*fd_ptr)->fname_len || strncmp(fname, (*fd_ptr)->fname, fname_len))) { if (error) { spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, (*fd_ptr)->fname, fname); } if (SUCCESS == phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { efree(*error); *error = NULL; } } return FAILURE; } *archive = *fd_ptr; fd = *fd_ptr; PHAR_G(last_phar) = fd; PHAR_G(last_phar_name) = fd->fname; PHAR_G(last_phar_name_len) = fd->fname_len; PHAR_G(last_alias) = alias; PHAR_G(last_alias_len) = alias_len; return SUCCESS; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_quick_find(&cached_alias, alias, alias_len, ahash, (void **)&fd_ptr)) { goto alias_success; } } fhash = zend_inline_hash_func(fname, fname_len); my_realpath = NULL; save = fname; save_len = fname_len; if (fname && fname_len) { if (SUCCESS == zend_hash_quick_find(&(PHAR_GLOBALS->phar_fname_map), fname, fname_len, fhash, (void**)&fd_ptr)) { *archive = *fd_ptr; fd = *fd_ptr; if (alias && alias_len) { if (!fd->is_temporary_alias && (alias_len != fd->alias_len || memcmp(fd->alias, alias, alias_len))) { if (error) { spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, (*fd_ptr)->fname, fname); } return FAILURE; } if (fd->alias_len && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), fd->alias, fd->alias_len, (void**)&fd_ptr)) { zend_hash_del(&(PHAR_GLOBALS->phar_alias_map), fd->alias, fd->alias_len); } zend_hash_quick_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, ahash, (void*)&fd, sizeof(phar_archive_data*), NULL); } PHAR_G(last_phar) = fd; PHAR_G(last_phar_name) = fd->fname; PHAR_G(last_phar_name_len) = fd->fname_len; PHAR_G(last_alias) = fd->alias; PHAR_G(last_alias_len) = fd->alias_len; return SUCCESS; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_quick_find(&cached_phars, fname, fname_len, fhash, (void**)&fd_ptr)) { *archive = *fd_ptr; fd = *fd_ptr; /* this could be problematic - alias should never be different from manifest alias for cached phars */ if (!fd->is_temporary_alias && alias && alias_len) { if (alias_len != fd->alias_len || memcmp(fd->alias, alias, alias_len)) { if (error) { spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, (*fd_ptr)->fname, fname); } return FAILURE; } } PHAR_G(last_phar) = fd; PHAR_G(last_phar_name) = fd->fname; PHAR_G(last_phar_name_len) = fd->fname_len; PHAR_G(last_alias) = fd->alias; PHAR_G(last_alias_len) = fd->alias_len; return SUCCESS; } if (SUCCESS == zend_hash_quick_find(&(PHAR_GLOBALS->phar_alias_map), save, save_len, fhash, (void**)&fd_ptr)) { fd = *archive = *fd_ptr; PHAR_G(last_phar) = fd; PHAR_G(last_phar_name) = fd->fname; PHAR_G(last_phar_name_len) = fd->fname_len; PHAR_G(last_alias) = fd->alias; PHAR_G(last_alias_len) = fd->alias_len; return SUCCESS; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_quick_find(&cached_alias, save, save_len, fhash, (void**)&fd_ptr)) { fd = *archive = *fd_ptr; PHAR_G(last_phar) = fd; PHAR_G(last_phar_name) = fd->fname; PHAR_G(last_phar_name_len) = fd->fname_len; PHAR_G(last_alias) = fd->alias; PHAR_G(last_alias_len) = fd->alias_len; return SUCCESS; } /* not found, try converting \ to / */ my_realpath = expand_filepath(fname, my_realpath TSRMLS_CC); if (my_realpath) { fname_len = strlen(my_realpath); fname = my_realpath; } else { return FAILURE; } #ifdef PHP_WIN32 phar_unixify_path_separators(fname, fname_len); #endif fhash = zend_inline_hash_func(fname, fname_len); if (SUCCESS == zend_hash_quick_find(&(PHAR_GLOBALS->phar_fname_map), fname, fname_len, fhash, (void**)&fd_ptr)) { realpath_success: *archive = *fd_ptr; fd = *fd_ptr; if (alias && alias_len) { zend_hash_quick_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, ahash, (void*)&fd, sizeof(phar_archive_data*), NULL); } efree(my_realpath); PHAR_G(last_phar) = fd; PHAR_G(last_phar_name) = fd->fname; PHAR_G(last_phar_name_len) = fd->fname_len; PHAR_G(last_alias) = fd->alias; PHAR_G(last_alias_len) = fd->alias_len; return SUCCESS; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_quick_find(&cached_phars, fname, fname_len, fhash, (void**)&fd_ptr)) { goto realpath_success; } efree(my_realpath); } return FAILURE; } /* }}} */ /** * Determine which stream compression filter (if any) we need to read this file */ char * phar_compress_filter(phar_entry_info * entry, int return_unknown) /* {{{ */ { switch (entry->flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: return "zlib.deflate"; case PHAR_ENT_COMPRESSED_BZ2: return "bzip2.compress"; default: return return_unknown ? "unknown" : NULL; } } /* }}} */ /** * Determine which stream decompression filter (if any) we need to read this file */ char * phar_decompress_filter(phar_entry_info * entry, int return_unknown) /* {{{ */ { php_uint32 flags; if (entry->is_modified) { flags = entry->old_flags; } else { flags = entry->flags; } switch (flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: return "zlib.inflate"; case PHAR_ENT_COMPRESSED_BZ2: return "bzip2.decompress"; default: return return_unknown ? "unknown" : NULL; } } /* }}} */ /** * retrieve information on a file contained within a phar, or null if it ain't there */ phar_entry_info *phar_get_entry_info(phar_archive_data *phar, char *path, int path_len, char **error, int security TSRMLS_DC) /* {{{ */ { return phar_get_entry_info_dir(phar, path, path_len, 0, error, security TSRMLS_CC); } /* }}} */ /** * retrieve information on a file or directory contained within a phar, or null if none found * allow_dir is 0 for none, 1 for both empty directories in the phar and temp directories, and 2 for only * valid pre-existing empty directory entries */ phar_entry_info *phar_get_entry_info_dir(phar_archive_data *phar, char *path, int path_len, char dir, char **error, int security TSRMLS_DC) /* {{{ */ { const char *pcr_error; phar_entry_info *entry; int is_dir; #ifdef PHP_WIN32 phar_unixify_path_separators(path, path_len); #endif is_dir = (path_len && (path[path_len - 1] == '/')) ? 1 : 0; if (error) { *error = NULL; } if (security && path_len >= sizeof(".phar")-1 && !memcmp(path, ".phar", sizeof(".phar")-1)) { if (error) { spprintf(error, 4096, "phar error: cannot directly access magic \".phar\" directory or files within it"); } return NULL; } if (!path_len && !dir) { if (error) { spprintf(error, 4096, "phar error: invalid path \"%s\" must not be empty", path); } return NULL; } if (phar_path_check(&path, &path_len, &pcr_error) > pcr_is_ok) { if (error) { spprintf(error, 4096, "phar error: invalid path \"%s\" contains %s", path, pcr_error); } return NULL; } if (!phar->manifest.arBuckets) { return NULL; } if (is_dir) { if (!path_len || path_len == 1) { return NULL; } path_len--; } if (SUCCESS == zend_hash_find(&phar->manifest, path, path_len, (void**)&entry)) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return NULL; } if (entry->is_dir && !dir) { if (error) { spprintf(error, 4096, "phar error: path \"%s\" is a directory", path); } return NULL; } if (!entry->is_dir && dir == 2) { /* user requested a directory, we must return one */ if (error) { spprintf(error, 4096, "phar error: path \"%s\" exists and is a not a directory", path); } return NULL; } return entry; } if (dir) { if (zend_hash_exists(&phar->virtual_dirs, path, path_len)) { /* a file or directory exists in a sub-directory of this path */ entry = (phar_entry_info *) ecalloc(1, sizeof(phar_entry_info)); /* this next line tells PharFileInfo->__destruct() to efree the filename */ entry->is_temp_dir = entry->is_dir = 1; entry->filename = (char *) estrndup(path, path_len + 1); entry->filename_len = path_len; entry->phar = phar; return entry; } } if (phar->mounted_dirs.arBuckets && zend_hash_num_elements(&phar->mounted_dirs)) { phar_zstr key; char *str_key; ulong unused; uint keylen; zend_hash_internal_pointer_reset(&phar->mounted_dirs); while (FAILURE != zend_hash_has_more_elements(&phar->mounted_dirs)) { if (HASH_KEY_NON_EXISTENT == zend_hash_get_current_key_ex(&phar->mounted_dirs, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if ((int)keylen >= path_len || strncmp(str_key, path, keylen)) { PHAR_STR_FREE(str_key); continue; } else { char *test; int test_len; php_stream_statbuf ssb; if (SUCCESS != zend_hash_find(&phar->manifest, str_key, keylen, (void **) &entry)) { if (error) { spprintf(error, 4096, "phar internal error: mounted path \"%s\" could not be retrieved from manifest", str_key); } PHAR_STR_FREE(str_key); return NULL; } if (!entry->tmp || !entry->is_mounted) { if (error) { spprintf(error, 4096, "phar internal error: mounted path \"%s\" is not properly initialized as a mounted path", str_key); } PHAR_STR_FREE(str_key); return NULL; } PHAR_STR_FREE(str_key); test_len = spprintf(&test, MAXPATHLEN, "%s%s", entry->tmp, path + keylen); if (SUCCESS != php_stream_stat_path(test, &ssb)) { efree(test); return NULL; } if (ssb.sb.st_mode & S_IFDIR && !dir) { efree(test); if (error) { spprintf(error, 4096, "phar error: path \"%s\" is a directory", path); } return NULL; } if ((ssb.sb.st_mode & S_IFDIR) == 0 && dir) { efree(test); /* user requested a directory, we must return one */ if (error) { spprintf(error, 4096, "phar error: path \"%s\" exists and is a not a directory", path); } return NULL; } /* mount the file just in time */ if (SUCCESS != phar_mount_entry(phar, test, test_len, path, path_len TSRMLS_CC)) { efree(test); if (error) { spprintf(error, 4096, "phar error: path \"%s\" exists as file \"%s\" and could not be mounted", path, test); } return NULL; } efree(test); if (SUCCESS != zend_hash_find(&phar->manifest, path, path_len, (void**)&entry)) { if (error) { spprintf(error, 4096, "phar error: path \"%s\" exists as file \"%s\" and could not be retrieved after being mounted", path, test); } return NULL; } return entry; } } } return NULL; } /* }}} */ static const char hexChars[] = "0123456789ABCDEF"; static int phar_hex_str(const char *digest, size_t digest_len, char **signature TSRMLS_DC) /* {{{ */ { int pos = -1; size_t len = 0; *signature = (char*)safe_pemalloc(digest_len, 2, 1, PHAR_G(persist)); for (; len < digest_len; ++len) { (*signature)[++pos] = hexChars[((const unsigned char *)digest)[len] >> 4]; (*signature)[++pos] = hexChars[((const unsigned char *)digest)[len] & 0x0F]; } (*signature)[++pos] = '\0'; return pos; } /* }}} */ #ifndef PHAR_HAVE_OPENSSL static int phar_call_openssl_signverify(int is_sign, php_stream *fp, off_t end, char *key, int key_len, char **signature, int *signature_len TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcc; zval *zdata, *zsig, *zkey, *retval_ptr, **zp[3], *openssl; MAKE_STD_ZVAL(zdata); MAKE_STD_ZVAL(openssl); ZVAL_STRINGL(openssl, is_sign ? "openssl_sign" : "openssl_verify", is_sign ? sizeof("openssl_sign")-1 : sizeof("openssl_verify")-1, 1); MAKE_STD_ZVAL(zsig); ZVAL_STRINGL(zsig, *signature, *signature_len, 1); MAKE_STD_ZVAL(zkey); ZVAL_STRINGL(zkey, key, key_len, 1); zp[0] = &zdata; zp[1] = &zsig; zp[2] = &zkey; php_stream_rewind(fp); Z_TYPE_P(zdata) = IS_STRING; Z_STRLEN_P(zdata) = end; if (end != (off_t) php_stream_copy_to_mem(fp, &(Z_STRVAL_P(zdata)), (size_t) end, 0)) { zval_dtor(zdata); zval_dtor(zsig); zval_dtor(zkey); zval_dtor(openssl); efree(openssl); efree(zdata); efree(zkey); efree(zsig); return FAILURE; } if (FAILURE == zend_fcall_info_init(openssl, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) { zval_dtor(zdata); zval_dtor(zsig); zval_dtor(zkey); zval_dtor(openssl); efree(openssl); efree(zdata); efree(zkey); efree(zsig); return FAILURE; } fci.param_count = 3; fci.params = zp; Z_ADDREF_P(zdata); if (is_sign) { Z_SET_ISREF_P(zsig); } else { Z_ADDREF_P(zsig); } Z_ADDREF_P(zkey); fci.retval_ptr_ptr = &retval_ptr; if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) { zval_dtor(zdata); zval_dtor(zsig); zval_dtor(zkey); zval_dtor(openssl); efree(openssl); efree(zdata); efree(zkey); efree(zsig); return FAILURE; } zval_dtor(openssl); efree(openssl); Z_DELREF_P(zdata); if (is_sign) { Z_UNSET_ISREF_P(zsig); } else { Z_DELREF_P(zsig); } Z_DELREF_P(zkey); zval_dtor(zdata); efree(zdata); zval_dtor(zkey); efree(zkey); switch (Z_TYPE_P(retval_ptr)) { default: case IS_LONG: zval_dtor(zsig); efree(zsig); if (1 == Z_LVAL_P(retval_ptr)) { efree(retval_ptr); return SUCCESS; } efree(retval_ptr); return FAILURE; case IS_BOOL: efree(retval_ptr); if (Z_BVAL_P(retval_ptr)) { *signature = estrndup(Z_STRVAL_P(zsig), Z_STRLEN_P(zsig)); *signature_len = Z_STRLEN_P(zsig); zval_dtor(zsig); efree(zsig); return SUCCESS; } zval_dtor(zsig); efree(zsig); return FAILURE; } } /* }}} */ #endif /* #ifndef PHAR_HAVE_OPENSSL */ int phar_verify_signature(php_stream *fp, size_t end_of_phar, php_uint32 sig_type, char *sig, int sig_len, char *fname, char **signature, int *signature_len, char **error TSRMLS_DC) /* {{{ */ { int read_size, len; off_t read_len; unsigned char buf[1024]; php_stream_rewind(fp); switch (sig_type) { case PHAR_SIG_OPENSSL: { #ifdef PHAR_HAVE_OPENSSL BIO *in; EVP_PKEY *key; EVP_MD *mdtype = (EVP_MD *) EVP_sha1(); EVP_MD_CTX md_ctx; #else int tempsig; #endif php_uint32 pubkey_len; char *pubkey = NULL, *pfile; php_stream *pfp; #ifndef PHAR_HAVE_OPENSSL if (!zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { if (error) { spprintf(error, 0, "openssl not loaded"); } return FAILURE; } #endif /* use __FILE__ . '.pubkey' for public key file */ spprintf(&pfile, 0, "%s.pubkey", fname); pfp = php_stream_open_wrapper(pfile, "rb", 0, NULL); efree(pfile); #if PHP_MAJOR_VERSION > 5 if (!pfp || !(pubkey_len = php_stream_copy_to_mem(pfp, (void **) &pubkey, PHP_STREAM_COPY_ALL, 0)) || !pubkey) { #else if (!pfp || !(pubkey_len = php_stream_copy_to_mem(pfp, &pubkey, PHP_STREAM_COPY_ALL, 0)) || !pubkey) { #endif if (pfp) { php_stream_close(pfp); } if (error) { spprintf(error, 0, "openssl public key could not be read"); } return FAILURE; } php_stream_close(pfp); #ifndef PHAR_HAVE_OPENSSL tempsig = sig_len; if (FAILURE == phar_call_openssl_signverify(0, fp, end_of_phar, pubkey, pubkey_len, &sig, &tempsig TSRMLS_CC)) { if (pubkey) { efree(pubkey); } if (error) { spprintf(error, 0, "openssl signature could not be verified"); } return FAILURE; } if (pubkey) { efree(pubkey); } sig_len = tempsig; #else in = BIO_new_mem_buf(pubkey, pubkey_len); if (NULL == in) { efree(pubkey); if (error) { spprintf(error, 0, "openssl signature could not be processed"); } return FAILURE; } key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL); BIO_free(in); efree(pubkey); if (NULL == key) { if (error) { spprintf(error, 0, "openssl signature could not be processed"); } return FAILURE; } EVP_VerifyInit(&md_ctx, mdtype); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } php_stream_seek(fp, 0, SEEK_SET); while (read_size && (len = php_stream_read(fp, (char*)buf, read_size)) > 0) { EVP_VerifyUpdate (&md_ctx, buf, len); read_len -= (off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } if (EVP_VerifyFinal(&md_ctx, (unsigned char *)sig, sig_len, key) != 1) { /* 1: signature verified, 0: signature does not match, -1: failed signature operation */ EVP_MD_CTX_cleanup(&md_ctx); if (error) { spprintf(error, 0, "broken openssl signature"); } return FAILURE; } EVP_MD_CTX_cleanup(&md_ctx); #endif *signature_len = phar_hex_str((const char*)sig, sig_len, signature TSRMLS_CC); } break; #ifdef PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; PHP_SHA512_CTX context; PHP_SHA512Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA512Update(&context, buf, len); read_len -= (off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA512Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature TSRMLS_CC); break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; PHP_SHA256_CTX context; PHP_SHA256Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA256Update(&context, buf, len); read_len -= (off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA256Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature TSRMLS_CC); break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (error) { spprintf(error, 0, "unsupported signature"); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; PHP_SHA1_CTX context; PHP_SHA1Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA1Update(&context, buf, len); read_len -= (off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA1Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature TSRMLS_CC); break; } case PHAR_SIG_MD5: { unsigned char digest[16]; PHP_MD5_CTX context; PHP_MD5Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_MD5Update(&context, buf, len); read_len -= (off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_MD5Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature TSRMLS_CC); break; } default: if (error) { spprintf(error, 0, "broken or unsupported signature"); } return FAILURE; } return SUCCESS; } /* }}} */
177,745
10,262
221110319063430331325118009267889576270
null
null
null
xcursor
4794b5dd34688158fb51a2943032569d3780c4b8
1
XcursorCommentCreate (XcursorUInt comment_type, int length) { XcursorComment *comment; if (length > XCURSOR_COMMENT_MAX_LEN) return NULL; { XcursorComment *comment; if (length > XCURSOR_COMMENT_MAX_LEN) return NULL; comment = malloc (sizeof (XcursorComment) + length + 1); comment->comment[0] = '\0'; return comment; } void XcursorCommentDestroy (XcursorComment *comment) { free (comment); } XcursorComments * XcursorCommentsCreate (int size) { XcursorComments *comments; comments = malloc (sizeof (XcursorComments) + size * sizeof (XcursorComment *)); if (!comments) return NULL; comments->ncomment = 0; comments->comments = (XcursorComment **) (comments + 1); return comments; } void XcursorCommentsDestroy (XcursorComments *comments) { int n; if (!comments) return; for (n = 0; n < comments->ncomment; n++) XcursorCommentDestroy (comments->comments[n]); free (comments); } static XcursorBool _XcursorReadUInt (XcursorFile *file, XcursorUInt *u) { unsigned char bytes[4]; if (!file || !u) return XcursorFalse; if ((*file->read) (file, bytes, 4) != 4) return XcursorFalse; *u = ((bytes[0] << 0) | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); return XcursorTrue; } static XcursorBool _XcursorReadBytes (XcursorFile *file, char *bytes, int length) { if (!file || !bytes || (*file->read) (file, (unsigned char *) bytes, length) != length) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorWriteUInt (XcursorFile *file, XcursorUInt u) { unsigned char bytes[4]; if (!file) return XcursorFalse; bytes[0] = u; bytes[1] = u >> 8; bytes[2] = u >> 16; bytes[3] = u >> 24; if ((*file->write) (file, bytes, 4) != 4) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorWriteBytes (XcursorFile *file, char *bytes, int length) { if (!file || !bytes || (*file->write) (file, (unsigned char *) bytes, length) != length) return XcursorFalse; return XcursorTrue; } static void _XcursorFileHeaderDestroy (XcursorFileHeader *fileHeader) { free (fileHeader); } static XcursorFileHeader * _XcursorFileHeaderCreate (XcursorUInt ntoc) { XcursorFileHeader *fileHeader; if (ntoc > 0x10000) return NULL; fileHeader = malloc (sizeof (XcursorFileHeader) + ntoc * sizeof (XcursorFileToc)); if (!fileHeader) return NULL; fileHeader->magic = XCURSOR_MAGIC; fileHeader->header = XCURSOR_FILE_HEADER_LEN; fileHeader->version = XCURSOR_FILE_VERSION; fileHeader->ntoc = ntoc; fileHeader->tocs = (XcursorFileToc *) (fileHeader + 1); return fileHeader; } static XcursorFileHeader * _XcursorReadFileHeader (XcursorFile *file) { XcursorFileHeader head, *fileHeader; XcursorUInt skip; int n; if (!file) return NULL; if (!_XcursorReadUInt (file, &head.magic)) return NULL; if (head.magic != XCURSOR_MAGIC) return NULL; if (!_XcursorReadUInt (file, &head.header)) return NULL; if (!_XcursorReadUInt (file, &head.version)) return NULL; if (!_XcursorReadUInt (file, &head.ntoc)) return NULL; skip = head.header - XCURSOR_FILE_HEADER_LEN; if (skip) if ((*file->seek) (file, skip, SEEK_CUR) == EOF) return NULL; fileHeader = _XcursorFileHeaderCreate (head.ntoc); if (!fileHeader) return NULL; fileHeader->magic = head.magic; fileHeader->header = head.header; fileHeader->version = head.version; fileHeader->ntoc = head.ntoc; for (n = 0; n < fileHeader->ntoc; n++) { if (!_XcursorReadUInt (file, &fileHeader->tocs[n].type)) break; if (!_XcursorReadUInt (file, &fileHeader->tocs[n].subtype)) break; if (!_XcursorReadUInt (file, &fileHeader->tocs[n].position)) break; } if (n != fileHeader->ntoc) { _XcursorFileHeaderDestroy (fileHeader); return NULL; } return fileHeader; } static XcursorUInt _XcursorFileHeaderLength (XcursorFileHeader *fileHeader) { return (XCURSOR_FILE_HEADER_LEN + fileHeader->ntoc * XCURSOR_FILE_TOC_LEN); } static XcursorBool _XcursorWriteFileHeader (XcursorFile *file, XcursorFileHeader *fileHeader) { int toc; if (!file || !fileHeader) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->magic)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->header)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->version)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->ntoc)) return XcursorFalse; for (toc = 0; toc < fileHeader->ntoc; toc++) { if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].type)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].subtype)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].position)) return XcursorFalse; } return XcursorTrue; } static XcursorBool _XcursorSeekToToc (XcursorFile *file, XcursorFileHeader *fileHeader, int toc) { if (!file || !fileHeader || \ (*file->seek) (file, fileHeader->tocs[toc].position, SEEK_SET) == EOF) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorFileReadChunkHeader (XcursorFile *file, XcursorFileHeader *fileHeader, int toc, XcursorChunkHeader *chunkHeader) { if (!file || !fileHeader || !chunkHeader) return XcursorFalse; if (!_XcursorSeekToToc (file, fileHeader, toc)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->header)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->type)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->subtype)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->version)) return XcursorFalse; /* sanity check */ if (chunkHeader->type != fileHeader->tocs[toc].type || chunkHeader->subtype != fileHeader->tocs[toc].subtype) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorFileWriteChunkHeader (XcursorFile *file, XcursorFileHeader *fileHeader, int toc, XcursorChunkHeader *chunkHeader) { if (!file || !fileHeader || !chunkHeader) return XcursorFalse; if (!_XcursorSeekToToc (file, fileHeader, toc)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->header)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->type)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->subtype)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->version)) return XcursorFalse; return XcursorTrue; } #define dist(a,b) ((a) > (b) ? (a) - (b) : (b) - (a)) static XcursorDim _XcursorFindBestSize (XcursorFileHeader *fileHeader, XcursorDim size, int *nsizesp) { int n; int nsizes = 0; XcursorDim bestSize = 0; XcursorDim thisSize; if (!fileHeader || !nsizesp) return 0; for (n = 0; n < fileHeader->ntoc; n++) { if (fileHeader->tocs[n].type != XCURSOR_IMAGE_TYPE) continue; thisSize = fileHeader->tocs[n].subtype; if (!bestSize || dist (thisSize, size) < dist (bestSize, size)) { bestSize = thisSize; nsizes = 1; } else if (thisSize == bestSize) nsizes++; } *nsizesp = nsizes; return bestSize; } static int _XcursorFindImageToc (XcursorFileHeader *fileHeader, XcursorDim size, int count) { int toc; XcursorDim thisSize; if (!fileHeader) return 0; for (toc = 0; toc < fileHeader->ntoc; toc++) { if (fileHeader->tocs[toc].type != XCURSOR_IMAGE_TYPE) continue; thisSize = fileHeader->tocs[toc].subtype; if (thisSize != size) continue; if (!count) break; count--; } if (toc == fileHeader->ntoc) return -1; return toc; } static XcursorImage * _XcursorReadImage (XcursorFile *file, XcursorFileHeader *fileHeader, int toc) { XcursorChunkHeader chunkHeader; XcursorImage head; XcursorImage *image; int n; XcursorPixel *p; if (!file || !fileHeader) return NULL; if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader)) return NULL; if (!_XcursorReadUInt (file, &head.width)) return NULL; if (!_XcursorReadUInt (file, &head.height)) return NULL; if (!_XcursorReadUInt (file, &head.xhot)) return NULL; if (!_XcursorReadUInt (file, &head.yhot)) return NULL; if (!_XcursorReadUInt (file, &head.delay)) return NULL; /* sanity check data */ if (head.width >= 0x10000 || head.height > 0x10000) return NULL; if (!_XcursorReadUInt (file, &head.delay)) return NULL; /* sanity check data */ if (head.width >= 0x10000 || head.height > 0x10000) return NULL; if (head.width == 0 || head.height == 0) return NULL; image->version = chunkHeader.version; image->size = chunkHeader.subtype; /* Create the image and initialize it */ image = XcursorImageCreate (head.width, head.height); if (chunkHeader.version < image->version) image->version = chunkHeader.version; image->size = chunkHeader.subtype; { XcursorImageDestroy (image); return NULL; } p++; } return image; }
CWE-190
177,800
10,263
115904642290960528563414433424960896673
null
null
null
qemu
1d20398694a3b67a388d955b7a945ba4aa90a8a8
1
static void coroutine_fn v9fs_wstat(void *opaque) { int32_t fid; int err = 0; int16_t unused; V9fsStat v9stat; size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsPDU *pdu = opaque; v9fs_stat_init(&v9stat); err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat); goto out_nofid; }
CWE-362
177,805
10,264
16541529706646081222955487882159418432
null
null
null
qemu
bfc56535f793c557aa754c50213fc5f882e6482d
1
static void vga_draw_graphic(VGACommonState *s, int full_update) { DisplaySurface *surface = qemu_console_surface(s->con); int y1, y, update, linesize, y_start, double_scan, mask, depth; int width, height, shift_control, line_offset, bwidth, bits; ram_addr_t page0, page1; DirtyBitmapSnapshot *snap = NULL; int disp_width, multi_scan, multi_run; uint8_t *d; uint32_t v, addr1, addr; vga_draw_line_func *vga_draw_line = NULL; bool share_surface; pixman_format_code_t format; #ifdef HOST_WORDS_BIGENDIAN bool byteswap = !s->big_endian_fb; #else bool byteswap = s->big_endian_fb; #endif full_update |= update_basic_params(s); s->get_resolution(s, &width, &height); disp_width = width; shift_control = (s->gr[VGA_GFX_MODE] >> 5) & 3; double_scan = (s->cr[VGA_CRTC_MAX_SCAN] >> 7); if (shift_control != 1) { multi_scan = (((s->cr[VGA_CRTC_MAX_SCAN] & 0x1f) + 1) << double_scan) - 1; } else { /* in CGA modes, multi_scan is ignored */ /* XXX: is it correct ? */ multi_scan = double_scan; } multi_run = multi_scan; if (shift_control != s->shift_control || double_scan != s->double_scan) { full_update = 1; s->shift_control = shift_control; s->double_scan = double_scan; } if (shift_control == 0) { if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) { disp_width <<= 1; } } else if (shift_control == 1) { if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) { disp_width <<= 1; } } depth = s->get_bpp(s); /* * Check whether we can share the surface with the backend * or whether we need a shadow surface. We share native * endian surfaces for 15bpp and above and byteswapped * surfaces for 24bpp and above. */ format = qemu_default_pixman_format(depth, !byteswap); if (format) { share_surface = dpy_gfx_check_format(s->con, format) && !s->force_shadow; } else { share_surface = false; } if (s->line_offset != s->last_line_offset || disp_width != s->last_width || height != s->last_height || s->last_depth != depth || s->last_byteswap != byteswap || share_surface != is_buffer_shared(surface)) { if (share_surface) { surface = qemu_create_displaysurface_from(disp_width, height, format, s->line_offset, s->vram_ptr + (s->start_addr * 4)); dpy_gfx_replace_surface(s->con, surface); } else { qemu_console_resize(s->con, disp_width, height); surface = qemu_console_surface(s->con); } s->last_scr_width = disp_width; s->last_scr_height = height; s->last_width = disp_width; s->last_height = height; s->last_line_offset = s->line_offset; s->last_depth = depth; s->last_byteswap = byteswap; full_update = 1; } else if (is_buffer_shared(surface) && (full_update || surface_data(surface) != s->vram_ptr + (s->start_addr * 4))) { pixman_format_code_t format = qemu_default_pixman_format(depth, !byteswap); surface = qemu_create_displaysurface_from(disp_width, height, format, s->line_offset, s->vram_ptr + (s->start_addr * 4)); dpy_gfx_replace_surface(s->con, surface); } if (shift_control == 0) { full_update |= update_palette16(s); if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) { v = VGA_DRAW_LINE4D2; } else { v = VGA_DRAW_LINE4; } bits = 4; } else if (shift_control == 1) { full_update |= update_palette16(s); if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) { v = VGA_DRAW_LINE2D2; } else { v = VGA_DRAW_LINE2; } bits = 4; } else { switch(s->get_bpp(s)) { default: case 0: full_update |= update_palette256(s); v = VGA_DRAW_LINE8D2; bits = 4; break; case 8: full_update |= update_palette256(s); v = VGA_DRAW_LINE8; bits = 8; break; case 15: v = s->big_endian_fb ? VGA_DRAW_LINE15_BE : VGA_DRAW_LINE15_LE; bits = 16; break; case 16: v = s->big_endian_fb ? VGA_DRAW_LINE16_BE : VGA_DRAW_LINE16_LE; bits = 16; break; case 24: v = s->big_endian_fb ? VGA_DRAW_LINE24_BE : VGA_DRAW_LINE24_LE; bits = 24; break; case 32: v = s->big_endian_fb ? VGA_DRAW_LINE32_BE : VGA_DRAW_LINE32_LE; bits = 32; break; } } vga_draw_line = vga_draw_line_table[v]; if (!is_buffer_shared(surface) && s->cursor_invalidate) { s->cursor_invalidate(s); } line_offset = s->line_offset; #if 0 printf("w=%d h=%d v=%d line_offset=%d cr[0x09]=0x%02x cr[0x17]=0x%02x linecmp=%d sr[0x01]=0x%02x\n", width, height, v, line_offset, s->cr[9], s->cr[VGA_CRTC_MODE], s->line_compare, sr(s, VGA_SEQ_CLOCK_MODE)); #endif addr1 = (s->start_addr * 4); bwidth = (width * bits + 7) / 8; y_start = -1; d = surface_data(surface); linesize = surface_stride(surface); y1 = 0; if (!full_update) { vga_sync_dirty_bitmap(s); snap = memory_region_snapshot_and_clear_dirty(&s->vram, addr1, bwidth * height, DIRTY_MEMORY_VGA); } for(y = 0; y < height; y++) { addr = addr1; if (!(s->cr[VGA_CRTC_MODE] & 1)) { int shift; /* CGA compatibility handling */ shift = 14 + ((s->cr[VGA_CRTC_MODE] >> 6) & 1); addr = (addr & ~(1 << shift)) | ((y1 & 1) << shift); } if (!(s->cr[VGA_CRTC_MODE] & 2)) { addr = (addr & ~0x8000) | ((y1 & 2) << 14); } update = full_update; page0 = addr; page1 = addr + bwidth - 1; if (full_update) { update = 1; } else { update = memory_region_snapshot_get_dirty(&s->vram, snap, page0, page1 - page0); } /* explicit invalidation for the hardware cursor (cirrus only) */ update |= vga_scanline_invalidated(s, y); if (update) { if (y_start < 0) y_start = y; if (!(is_buffer_shared(surface))) { vga_draw_line(s, d, s->vram_ptr + addr, width); if (s->cursor_draw_line) s->cursor_draw_line(s, d, y); } } else { if (y_start >= 0) { /* flush to display */ dpy_gfx_update(s->con, 0, y_start, disp_width, y - y_start); y_start = -1; } } if (!multi_run) { mask = (s->cr[VGA_CRTC_MODE] & 3) ^ 3; if ((y1 & mask) == mask) addr1 += line_offset; y1++; multi_run = multi_scan; } else { multi_run--; } /* line compare acts on the displayed lines */ if (y == s->line_compare) addr1 = 0; d += linesize; } if (y_start >= 0) { /* flush to display */ dpy_gfx_update(s->con, 0, y_start, disp_width, y - y_start); } g_free(snap); memset(s->invalidated_y_table, 0, sizeof(s->invalidated_y_table)); }
CWE-617
177,868
10,269
248065639524337933991322249217617341178
null
null
null