static void v9fs_create(void *opaque) { int32_t fid; int err = 0; size_t offset = 7; V9fsFidState *fidp; V9fsQID qid; int32_t perm; int8_t mode; V9fsPath path; struct stat stbuf; V9fsString name; V9fsString extension; int iounit; V9fsPDU *pdu = opaque; v9fs_path_init(&path); pdu_unmarshal(pdu, offset, "dsdbs", &fid, &name, &perm, &mode, &extension); trace_v9fs_create(pdu->tag, pdu->id, fid, name.data, perm, mode); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } if (perm & P9_STAT_MODE_DIR) { err = v9fs_co_mkdir(pdu, fidp, &name, perm & 0777, fidp->uid, -1, &stbuf); if (err < 0) { goto out; } err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); if (err < 0) { goto out; } v9fs_path_copy(&fidp->path, &path); err = v9fs_co_opendir(pdu, fidp); if (err < 0) { goto out; } fidp->fid_type = P9_FID_DIR; } else if (perm & P9_STAT_MODE_SYMLINK) { err = v9fs_co_symlink(pdu, fidp, &name, extension.data, -1 , &stbuf); if (err < 0) { goto out; } err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); if (err < 0) { goto out; } v9fs_path_copy(&fidp->path, &path); } else if (perm & P9_STAT_MODE_LINK) { int32_t ofid = atoi(extension.data); V9fsFidState *ofidp = get_fid(pdu, ofid); if (ofidp == NULL) { err = -EINVAL; goto out; } err = v9fs_co_link(pdu, ofidp, fidp, &name); put_fid(pdu, ofidp); if (err < 0) { goto out; } err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); if (err < 0) { fidp->fid_type = P9_FID_NONE; goto out; } v9fs_path_copy(&fidp->path, &path); err = v9fs_co_lstat(pdu, &fidp->path, &stbuf); if (err < 0) { fidp->fid_type = P9_FID_NONE; goto out; } } else if (perm & P9_STAT_MODE_DEVICE) { char ctype; uint32_t major, minor; mode_t nmode = 0; if (sscanf(extension.data, "%c %u %u", &ctype, &major, &minor) != 3) { err = -errno; goto out; } switch (ctype) { case 'c': nmode = S_IFCHR; break; case 'b': nmode = S_IFBLK; break; default: err = -EIO; goto out; } nmode |= perm & 0777; err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1, makedev(major, minor), nmode, &stbuf); if (err < 0) { goto out; } err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); if (err < 0) { goto out; } v9fs_path_copy(&fidp->path, &path); } else if (perm & P9_STAT_MODE_NAMED_PIPE) { err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1, 0, S_IFIFO | (perm & 0777), &stbuf); if (err < 0) { goto out; } err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); if (err < 0) { goto out; } v9fs_path_copy(&fidp->path, &path); } else if (perm & P9_STAT_MODE_SOCKET) { err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1, 0, S_IFSOCK | (perm & 0777), &stbuf); if (err < 0) { goto out; } err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); if (err < 0) { goto out; } v9fs_path_copy(&fidp->path, &path); } else { err = v9fs_co_open2(pdu, fidp, &name, -1, omode_to_uflags(mode)|O_CREAT, perm, &stbuf); if (err < 0) { goto out; } fidp->fid_type = P9_FID_FILE; fidp->open_flags = omode_to_uflags(mode); if (fidp->open_flags & O_EXCL) { /* * We let the host file system do O_EXCL check * We should not reclaim such fd */ fidp->flags |= FID_NON_RECLAIMABLE; } } iounit = get_iounit(pdu, &fidp->path); stat_to_qid(&stbuf, &qid); offset += pdu_marshal(pdu, offset, "Qd", &qid, iounit); err = offset; out: put_fid(pdu, fidp); out_nofid: complete_pdu(pdu->s, pdu, err); v9fs_string_free(&name); v9fs_string_free(&extension); v9fs_path_free(&path); }


size_t zmalloc_size(void *ptr) {
    void *realptr = (char*)ptr-PREFIX_SIZE;
    size_t size = *((size_t*)realptr);
    /* Assume at least that all the allocations are padded at sizeof(long) by
     * the underlying allocator. */
    if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1));
    return size+PREFIX_SIZE;
}


double tlist_returns_set_rows ( List * tlist ) {
 double result = 1 ;
 ListCell * lc ;
 foreach ( lc , tlist ) {
 TargetEntry * tle = ( TargetEntry * ) lfirst ( lc ) ;
 double colresult ;
 colresult = expression_returns_set_rows ( ( Node * ) tle -> expr ) ;
 if ( result < colresult ) result = colresult ;
 }
 return result ;
 }


static int qrtr_recvmsg(struct socket *sock, struct msghdr *msg,
			size_t size, int flags)
{
	DECLARE_SOCKADDR(struct sockaddr_qrtr *, addr, msg->msg_name);
	struct sock *sk = sock->sk;
	struct sk_buff *skb;
	struct qrtr_cb *cb;
	int copied, rc;

	lock_sock(sk);

	if (sock_flag(sk, SOCK_ZAPPED)) {
		release_sock(sk);
		return -EADDRNOTAVAIL;
	}

	skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
				flags & MSG_DONTWAIT, &rc);
	if (!skb) {
		release_sock(sk);
		return rc;
	}
	cb = (struct qrtr_cb *)skb->cb;

	copied = skb->len;
	if (copied > size) {
		copied = size;
		msg->msg_flags |= MSG_TRUNC;
	}

	rc = skb_copy_datagram_msg(skb, 0, msg, copied);
	if (rc < 0)
		goto out;
	rc = copied;

	if (addr) {
		addr->sq_family = AF_QIPCRTR;
		addr->sq_node = cb->src_node;
		addr->sq_port = cb->src_port;
		msg->msg_namelen = sizeof(*addr);
	}

out:
	if (cb->confirm_rx)
		qrtr_send_resume_tx(cb);

	skb_free_datagram(sk, skb);
	release_sock(sk);

	return rc;
}


static void test_sshort_bug ( ) {
 MYSQL_STMT * stmt ;
 MYSQL_BIND my_bind [ 4 ] ;
 short short_value ;
 int32 long_value ;
 ulong s_length , l_length , ll_length , t_length ;
 ulonglong longlong_value ;
 int rc ;
 uchar tiny_value ;
 char llbuf [ 22 ] ;
 myheader ( "test_sshort_bug" ) ;
 rc = mysql_query ( mysql , "DROP TABLE IF EXISTS test_sshort" ) ;
 myquery ( rc ) ;
 rc = mysql_query ( mysql , "CREATE TABLE test_sshort(a smallint signed, \ b smallint signed, \ c smallint unsigned, \ d smallint unsigned)" ) ;
 myquery ( rc ) ;
 rc = mysql_query ( mysql , "INSERT INTO test_sshort VALUES(-5999, -5999, 35999, 200)" ) ;
 myquery ( rc ) ;
 stmt = mysql_simple_prepare ( mysql , "SELECT * FROM test_sshort" ) ;
 check_stmt ( stmt ) ;
 rc = mysql_stmt_execute ( stmt ) ;
 check_execute ( stmt , rc ) ;
 memset ( my_bind , 0 , sizeof ( my_bind ) ) ;
 my_bind [ 0 ] . buffer_type = MYSQL_TYPE_SHORT ;
 my_bind [ 0 ] . buffer = ( void * ) & short_value ;
 my_bind [ 0 ] . length = & s_length ;
 my_bind [ 1 ] . buffer_type = MYSQL_TYPE_LONG ;
 my_bind [ 1 ] . buffer = ( void * ) & long_value ;
 my_bind [ 1 ] . length = & l_length ;
 my_bind [ 2 ] . buffer_type = MYSQL_TYPE_LONGLONG ;
 my_bind [ 2 ] . buffer = ( void * ) & longlong_value ;
 my_bind [ 2 ] . length = & ll_length ;
 my_bind [ 3 ] . buffer_type = MYSQL_TYPE_TINY ;
 my_bind [ 3 ] . buffer = ( void * ) & tiny_value ;
 my_bind [ 3 ] . is_unsigned = TRUE ;
 my_bind [ 3 ] . length = & t_length ;
 rc = mysql_stmt_bind_result ( stmt , my_bind ) ;
 check_execute ( stmt , rc ) ;
 rc = mysql_stmt_fetch ( stmt ) ;
 check_execute ( stmt , rc ) ;
 if ( ! opt_silent ) {
 fprintf ( stdout , "\n sshort : %d (%ld)" , short_value , s_length ) ;
 fprintf ( stdout , "\n slong : %ld (%ld)" , ( long ) long_value , l_length ) ;
 fprintf ( stdout , "\n longlong : %s (%ld)" , llstr ( longlong_value , llbuf ) , ll_length ) ;
 fprintf ( stdout , "\n tinyint : %d (%ld)" , tiny_value , t_length ) ;
 }
 DIE_UNLESS ( short_value == - 5999 ) ;
 DIE_UNLESS ( s_length == 2 ) ;
 DIE_UNLESS ( long_value == - 5999 ) ;
 DIE_UNLESS ( l_length == 4 ) ;
 DIE_UNLESS ( longlong_value == 35999 ) ;
 DIE_UNLESS ( ll_length == 8 ) ;
 DIE_UNLESS ( tiny_value == 200 ) ;
 DIE_UNLESS ( t_length == 1 ) ;
 rc = mysql_stmt_fetch ( stmt ) ;
 DIE_UNLESS ( rc == MYSQL_NO_DATA ) ;
 mysql_stmt_close ( stmt ) ;
 }


static inline void flash_sync_area(Flash *s, int64_t off, int64_t len) { QEMUIOVector *iov = g_new(QEMUIOVector, 1); if (!s->blk || blk_is_read_only(s->blk)) { return; } assert(!(len % BDRV_SECTOR_SIZE)); qemu_iovec_init(iov, 1); qemu_iovec_add(iov, s->storage + off, len); blk_aio_pwritev(s->blk, off, iov, 0, blk_sync_complete, iov); }


static void gdb_vm_stopped(void *opaque, int reason) { GDBState *s = opaque; char buf[256]; int ret; if (s->state == RS_SYSCALL) /* disable single step if it was enable */ cpu_single_step(s->env, 0); if (reason == EXCP_DEBUG) { tb_flush(s->env); ret = SIGTRAP; } else if (reason == EXCP_INTERRUPT) { ret = SIGINT; } else { ret = 0; snprintf(buf, sizeof(buf), "S%02x", ret);


static void remove_server ( char * prefix , char * port ) {
 char * old_port = NULL ;
 struct server * old_server = NULL ;
 cork_hash_table_delete ( server_table , ( void * ) port , ( void * * ) & old_port , ( void * * ) & old_server ) ;
 if ( old_server != NULL ) {
 destroy_server ( old_server ) ;
 ss_free ( old_server ) ;
 }
 stop_server ( prefix , port ) ;
 }


static BlockAIOCB *read_fifo_child(QuorumAIOCB *acb) { BDRVQuorumState *s = acb->common.bs->opaque; acb->qcrs[acb->child_iter].buf = qemu_blockalign(s->children[acb->child_iter]->bs, acb->qiov->size); qemu_iovec_init(&acb->qcrs[acb->child_iter].qiov, acb->qiov->niov); qemu_iovec_clone(&acb->qcrs[acb->child_iter].qiov, acb->qiov, acb->qcrs[acb->child_iter].buf); bdrv_aio_readv(s->children[acb->child_iter]->bs, acb->sector_num, &acb->qcrs[acb->child_iter].qiov, acb->nb_sectors, quorum_aio_cb, &acb->qcrs[acb->child_iter]); return &acb->common; }


error_t rza1EthInit(NetInterface *interface)
{
   error_t error;

   //Debug message
   TRACE_INFO("Initializing RZ/A1 Ethernet MAC...\r\n");

   //Save underlying network interface
   nicDriverInterface = interface;

   //Enable Ethernet peripheral clock
   CPG.STBCR7 &= ~CPG_STBCR7_MSTP74;

   //GPIO configuration
   rza1EthInitGpio(interface);

   //Perform software reset
   ETHER.ARSTR = ETHER_ARSTR_ARST;
   //Wait for the reset to complete
   sleep(10);

   //Start EDMAC transmitting and receiving units
   ETHER.EDSR0 = ETHER_EDSR0_ENT | ETHER_EDSR0_ENR;

   //To execute a software reset with this register, 1 must be
   //written to both the SWRT and SWRR bits simultaneously
   ETHER.EDMR0 = ETHER_EDMR0_SWRT | ETHER_EDMR0_SWRR;
   //Wait for the reset to complete
   while(ETHER.EDMR0 & (ETHER_EDMR0_SWRT | ETHER_EDMR0_SWRR))
   {
   }

   //Valid Ethernet PHY or switch driver?
   if(interface->phyDriver != NULL)
   {
      //Ethernet PHY initialization
      error = interface->phyDriver->init(interface);
   }
   else if(interface->switchDriver != NULL)
   {
      //Ethernet switch initialization
      error = interface->switchDriver->init(interface);
   }
   else
   {
      //The interface is not properly configured
      error = ERROR_FAILURE;
   }

   //Any error to report?
   if(error)
   {
      return error;
   }

   //Initialize DMA descriptor lists
   rza1EthInitDmaDesc(interface);

   //Select little endian mode and set descriptor length (16 bytes)
   ETHER.EDMR0 = ETHER_EDMR0_DE | ETHER_EDMR0_DL_16;

   //Error masks
   ETHER.TRSCER0 = 0;
   //Use store and forward mode
   ETHER.TFTR0 = 0;

   //Set transmit FIFO size and receive FIFO size (2048 bytes)
   ETHER.FDR0 = ETHER_FDR0_TFD_2048 | ETHER_FDR0_RFD_2048;

   //Enable continuous reception of multiple frames
   ETHER.RMCR0 = ETHER_RMCR0_RNC;
   //No padding insertion into receive data
   ETHER.RPADIR0 = 0;

   //Receive FIFO threshold (8 frames or 2048-64 bytes)
   ETHER.FCFTR0 = ETHER_FCFTR0_RFF_8 | ETHER_FCFTR0_RFD_2048;

   //Intelligent checksum operation mode
   ETHER.CSMR = 0;

   //Enable multicast address filtering
   ETHER.ECMR0 |= ETH_ECMR0_MCT;

   //Set the upper 32 bits of the MAC address
   ETHER.MAHR0 = (interface->macAddr.b[0] << 24) | (interface->macAddr.b[1] << 16) |
      (interface->macAddr.b[2] << 8) | interface->macAddr.b[3];

   //Set the lower 16 bits of the MAC address
   ETHER.MALR0 = (interface->macAddr.b[4] << 8) | interface->macAddr.b[5];

   //Disable all CAM entries
   ETHER.TSU_TEN = 0;

   //Maximum frame length that can be accepted
   ETHER.RFLR0 = RZA1_ETH_RX_BUFFER_SIZE;
   //Automatic pause frame
   ETHER.APR0 = 0;
   //Manual pause frame
   ETHER.MPR0 = 0;
   //Automatic pause frame retransmit count
   ETHER.TPAUSER0 = 0;

   //Disable all EMAC interrupts
   ETHER.ECSIPR0 = 0;

   //Enable the desired EDMAC interrupts
   ETHER.EESIPR0 =  ETHER_EESIPR0_TWBIP | ETHER_EESIPR0_FRIP;

   //Register interrupt handler
   R_INTC_Regist_Int_Func(INTC_ID_ETHERI, rza1EthIrqHandler);
   //Configure interrupt priority
   R_INTC_Set_Priority(INTC_ID_ETHERI, RZA1_ETH_IRQ_PRIORITY);

   //Enable EDMAC transmission and reception
   ETHER.ECMR0 |= ETH_ECMR0_RE | ETH_ECMR0_TE;

   //Instruct the DMA to poll the receive descriptor list
   ETHER.EDRRR0 = ETHER_EDRRR0_RR;

   //Accept any packets from the upper layer
   osSetEvent(&interface->nicTxEvent);

   //Successful initialization
   return NO_ERROR;
}


static void nvdimm_realize(PCDIMMDevice *dimm, Error **errp) { MemoryRegion *mr = host_memory_backend_get_memory(dimm->hostmem, errp); NVDIMMDevice *nvdimm = NVDIMM(dimm); uint64_t align, pmem_size, size = memory_region_size(mr); align = memory_region_get_alignment(mr); pmem_size = size - nvdimm->label_size; nvdimm->label_data = memory_region_get_ram_ptr(mr) + pmem_size; pmem_size = QEMU_ALIGN_DOWN(pmem_size, align); if (size <= nvdimm->label_size || !pmem_size) { HostMemoryBackend *hostmem = dimm->hostmem; char *path = object_get_canonical_path_component(OBJECT(hostmem)); error_setg(errp, "the size of memdev %s (0x%" PRIx64 ") is too " "small to contain nvdimm label (0x%" PRIx64 ") and " "aligned PMEM (0x%" PRIx64 ")", path, memory_region_size(mr), nvdimm->label_size, align); return; } memory_region_init_alias(&nvdimm->nvdimm_mr, OBJECT(dimm), "nvdimm-memory", mr, 0, pmem_size); nvdimm->nvdimm_mr.align = align; }


void xmc4400EthDisableIrq(NetInterface *interface)
{
   //Disable Ethernet MAC interrupts
   NVIC_DisableIRQ(ETH0_0_IRQn);

   //Valid Ethernet PHY or switch driver?
   if(interface->phyDriver != NULL)
   {
      //Disable Ethernet PHY interrupts
      interface->phyDriver->disableIrq(interface);
   }
   else if(interface->switchDriver != NULL)
   {
      //Disable Ethernet switch interrupts
      interface->switchDriver->disableIrq(interface);
   }
   else
   {
      //Just for sanity
   }
}


void xmc4400EthInitGpio(NetInterface *interface)
{
   uint32_t temp;

   //Configure ETH0.TX_EN (P0.4)
   temp = PORT0->IOCR4;
   temp &= ~PORT0_IOCR4_PC4_Msk;
   temp |= (17UL << PORT0_IOCR4_PC4_Pos);
   PORT0->IOCR4 = temp;

   //Configure ETH0.MDIO (P2.0), ETH0.RXD0A (P2.2) and ETH0.RXD1A (P2.3)
   temp = PORT2->IOCR0;
   temp &= ~(PORT2_IOCR0_PC0_Msk | PORT2_IOCR0_PC2_Msk | PORT2_IOCR0_PC3_Msk);
   temp |= (0UL << PORT2_IOCR0_PC0_Pos) | (0UL << PORT2_IOCR0_PC2_Pos) | (0UL << PORT2_IOCR0_PC3_Pos);
   PORT2->IOCR0 = temp;

   //Configure ETH0.RXERA (P2.4)and ETH0.MDC (P2.7)
   temp = PORT2->IOCR4;
   temp &= ~(PORT2_IOCR4_PC4_Msk | PORT2_IOCR4_PC7_Msk);
   temp |= (0UL << PORT2_IOCR4_PC4_Pos) | (17UL << PORT2_IOCR4_PC7_Pos);
   PORT2->IOCR4 = temp;

   //Configure ETH0.TXD0 (P2.8) and ETH0.TXD1 (P2.9)
   temp = PORT2->IOCR8;
   temp &= ~(PORT2_IOCR8_PC8_Msk | PORT2_IOCR8_PC9_Msk);
   temp |= (17UL << PORT2_IOCR8_PC8_Pos) | (17UL << PORT2_IOCR8_PC9_Pos);
   PORT2->IOCR8 = temp;

   //Configure ETH0.CLK_RMIIC (P15.8) and ETH0.CRS_DVC (P15.9)
   temp = PORT15->IOCR8;
   temp &= ~(PORT15_IOCR8_PC8_Msk | PORT15_IOCR8_PC9_Msk);
   temp |= (0UL << PORT15_IOCR8_PC8_Pos) | (0UL << PORT15_IOCR8_PC9_Pos);
   PORT15->IOCR8 = temp;

   //Assign ETH_MDIO (P2.0) to HW0
   temp = PORT2->HWSEL & ~PORT2_HWSEL_HW0_Msk;
   PORT2->HWSEL = temp | (1UL << PORT2_HWSEL_HW0_Pos);

   //Select output driver strength for ETH0.TX_EN (P2.5)
   temp = PORT2->PDR0;
   temp &= ~PORT2_PDR0_PD5_Msk;
   temp |= (0UL << PORT2_PDR0_PD5_Pos);
   PORT2->PDR0 = temp;

   //Select output driver strength for ETH0.TXD0 (P2.8) and ETH0.TXD1 (P2.9)
   temp = PORT2->PDR1;
   temp &= ~(PORT2_PDR1_PD8_Msk | PORT2_PDR1_PD9_Msk);
   temp |= (0UL << PORT2_PDR1_PD8_Pos) | (0UL << PORT2_PDR1_PD9_Pos);
   PORT2->PDR1 = temp;

   //Use ETH0.CLK_RMIIC (P15.8) and ETH0.CRS_DVC (P15.9) as digital inputs
   PORT15->PDISC &= ~(PORT15_PDISC_PDIS8_Msk | PORT15_PDISC_PDIS9_Msk);

   //Select RMII operation mode
   ETH0_CON->CON = ETH_CON_INFSEL_Msk | ETH_CON_MDIO_B | ETH_CON_RXER_A |
      ETH_CON_CRS_DV_C | ETH_CON_CLK_RMII_C | ETH_CON_RXD1_A | ETH_CON_RXD0_A;
}


static void model_rd_for_sb ( VP9_COMP * cpi , BLOCK_SIZE bsize , MACROBLOCK * x , MACROBLOCKD * xd , int * out_rate_sum , int64_t * out_dist_sum ) {
 int i ;
 int64_t rate_sum = 0 ;
 int64_t dist_sum = 0 ;
 const int ref = xd -> mi [ 0 ] . src_mi -> mbmi . ref_frame [ 0 ] ;
 unsigned int sse ;
 unsigned int var = 0 ;
 unsigned int sum_sse = 0 ;
 const int shift = 8 ;
 int rate ;
 int64_t dist ;
 x -> pred_sse [ ref ] = 0 ;
 for ( i = 0 ;
 i < MAX_MB_PLANE ;
 ++ i ) {
 struct macroblock_plane * const p = & x -> plane [ i ] ;
 struct macroblockd_plane * const pd = & xd -> plane [ i ] ;
 const BLOCK_SIZE bs = get_plane_block_size ( bsize , pd ) ;
 const TX_SIZE max_tx_size = max_txsize_lookup [ bs ] ;
 const BLOCK_SIZE unit_size = txsize_to_bsize [ max_tx_size ] ;
 int bw = 1 << ( b_width_log2_lookup [ bs ] - b_width_log2_lookup [ unit_size ] ) ;
 int bh = 1 << ( b_height_log2_lookup [ bs ] - b_width_log2_lookup [ unit_size ] ) ;
 int idx , idy ;
 int lw = b_width_log2_lookup [ unit_size ] + 2 ;
 int lh = b_height_log2_lookup [ unit_size ] + 2 ;
 sum_sse = 0 ;
 for ( idy = 0 ;
 idy < bh ;
 ++ idy ) {
 for ( idx = 0 ;
 idx < bw ;
 ++ idx ) {
 uint8_t * src = p -> src . buf + ( idy * p -> src . stride << lh ) + ( idx << lw ) ;
 uint8_t * dst = pd -> dst . buf + ( idy * pd -> dst . stride << lh ) + ( idx << lh ) ;
 int block_idx = ( idy << 1 ) + idx ;
 var = cpi -> fn_ptr [ unit_size ] . vf ( src , p -> src . stride , dst , pd -> dst . stride , & sse ) ;
 x -> bsse [ ( i << 2 ) + block_idx ] = sse ;
 sum_sse += sse ;
 if ( ! x -> select_tx_size ) {
 if ( x -> bsse [ ( i << 2 ) + block_idx ] < p -> quant_thred [ 0 ] >> shift ) x -> skip_txfm [ ( i << 2 ) + block_idx ] = 1 ;
 else if ( var < p -> quant_thred [ 1 ] >> shift ) x -> skip_txfm [ ( i << 2 ) + block_idx ] = 2 ;
 else x -> skip_txfm [ ( i << 2 ) + block_idx ] = 0 ;
 }
 if ( i == 0 ) x -> pred_sse [ ref ] += sse ;
 }
 }
 if ( cpi -> oxcf . speed > 4 ) {
 int64_t rate ;
 int64_t dist ;
 int64_t square_error = sse ;
 int quantizer = ( pd -> dequant [ 1 ] >> 3 ) ;
 if ( quantizer < 120 ) rate = ( square_error * ( 280 - quantizer ) ) >> 8 ;
 else rate = 0 ;
 dist = ( square_error * quantizer ) >> 8 ;
 rate_sum += rate ;
 dist_sum += dist ;
 }
 else {
 vp9_model_rd_from_var_lapndz ( sum_sse , 1 << num_pels_log2_lookup [ bs ] , pd -> dequant [ 1 ] >> 3 , & rate , & dist ) ;
 rate_sum += rate ;
 dist_sum += dist ;
 }
 }
 * out_rate_sum = ( int ) rate_sum ;
 * out_dist_sum = dist_sum << 4 ;
 }


error_t xmc4400EthUpdateMacAddrFilter(NetInterface *interface)
{
   uint_t i;
   uint_t j;
   uint_t k;
   uint32_t crc;
   uint32_t hashTable[2];
   MacAddr unicastMacAddr[3];
   MacFilterEntry *entry;

   //Debug message
   TRACE_DEBUG("Updating MAC filter...\r\n");

   //Set the MAC address of the station
   ETH0->MAC_ADDRESS0_LOW = interface->macAddr.w[0] | (interface->macAddr.w[1] << 16);
   ETH0->MAC_ADDRESS0_HIGH = interface->macAddr.w[2];

   //The MAC supports 3 additional addresses for unicast perfect filtering
   unicastMacAddr[0] = MAC_UNSPECIFIED_ADDR;
   unicastMacAddr[1] = MAC_UNSPECIFIED_ADDR;
   unicastMacAddr[2] = MAC_UNSPECIFIED_ADDR;

   //The hash table is used for multicast address filtering
   hashTable[0] = 0;
   hashTable[1] = 0;

   //The MAC address filter contains the list of MAC addresses to accept
   //when receiving an Ethernet frame
   for(i = 0, j = 0; i < MAC_ADDR_FILTER_SIZE; i++)
   {
      //Point to the current entry
      entry = &interface->macAddrFilter[i];

      //Valid entry?
      if(entry->refCount > 0)
      {
         //Multicast address?
         if(macIsMulticastAddr(&entry->addr))
         {
            //Compute CRC over the current MAC address
            crc = xmc4400EthCalcCrc(&entry->addr, sizeof(MacAddr));

            //The upper 6 bits in the CRC register are used to index the
            //contents of the hash table
            k = (crc >> 26) & 0x3F;

            //Update hash table contents
            hashTable[k / 32] |= (1 << (k % 32));
         }
         else
         {
            //Up to 3 additional MAC addresses can be specified
            if(j < 3)
            {
               //Save the unicast address
               unicastMacAddr[j++] = entry->addr;
            }
         }
      }
   }

   //Configure the first unicast address filter
   if(j >= 1)
   {
      //When the AE bit is set, the entry is used for perfect filtering
      ETH0->MAC_ADDRESS1_LOW = unicastMacAddr[0].w[0] | (unicastMacAddr[0].w[1] << 16);
      ETH0->MAC_ADDRESS1_HIGH = unicastMacAddr[0].w[2] | ETH_MAC_ADDRESS1_HIGH_AE_Msk;
   }
   else
   {
      //When the AE bit is cleared, the entry is ignored
      ETH0->MAC_ADDRESS1_LOW = 0;
      ETH0->MAC_ADDRESS1_HIGH = 0;
   }

   //Configure the second unicast address filter
   if(j >= 2)
   {
      //When the AE bit is set, the entry is used for perfect filtering
      ETH0->MAC_ADDRESS2_LOW = unicastMacAddr[1].w[0] | (unicastMacAddr[1].w[1] << 16);
      ETH0->MAC_ADDRESS2_HIGH = unicastMacAddr[1].w[2] | ETH_MAC_ADDRESS2_HIGH_AE_Msk;
   }
   else
   {
      //When the AE bit is cleared, the entry is ignored
      ETH0->MAC_ADDRESS2_LOW = 0;
      ETH0->MAC_ADDRESS2_HIGH = 0;
   }

   //Configure the third unicast address filter
   if(j >= 3)
   {
      //When the AE bit is set, the entry is used for perfect filtering
      ETH0->MAC_ADDRESS3_LOW = unicastMacAddr[2].w[0] | (unicastMacAddr[2].w[1] << 16);
      ETH0->MAC_ADDRESS3_HIGH = unicastMacAddr[2].w[2] | ETH_MAC_ADDRESS3_HIGH_AE_Msk;
   }
   else
   {
      //When the AE bit is cleared, the entry is ignored
      ETH0->MAC_ADDRESS3_LOW = 0;
      ETH0->MAC_ADDRESS3_HIGH = 0;
   }

   //Configure the multicast address filter
   ETH0->HASH_TABLE_LOW = hashTable[0];
   ETH0->HASH_TABLE_HIGH = hashTable[1];

   //Debug message
   TRACE_DEBUG("  HASH_TABLE_LOW = %08" PRIX32 "\r\n", ETH0->HASH_TABLE_LOW);
   TRACE_DEBUG("  HASH_TABLE_HIGH = %08" PRIX32 "\r\n", ETH0->HASH_TABLE_HIGH);

   //Successful processing
   return NO_ERROR;
}


static void test_validate_union_flat(TestInputVisitorData *data, const void *unused) { UserDefFlatUnion *tmp = NULL; Visitor *v; Error *err = NULL; v = validate_test_init(data, "{ 'enum1': 'value1', " "'string': 'str', " "'boolean': true }"); /* TODO when generator bug is fixed, add 'integer': 41 */ visit_type_UserDefFlatUnion(v, &tmp, NULL, &err); g_assert(!err); qapi_free_UserDefFlatUnion(tmp); }


static void save_mtu ( packet_info * pinfo , bluetooth_data_t * bluetooth_data , guint mtu ) {
 wmem_tree_key_t key [ 4 ] ;
 guint32 frame_number ;
 mtu_data_t * mtu_data ;
 frame_number = pinfo -> num ;
 key [ 0 ] . length = 1 ;
 key [ 0 ] . key = & bluetooth_data -> interface_id ;
 key [ 1 ] . length = 1 ;
 key [ 1 ] . key = & bluetooth_data -> adapter_id ;
 key [ 2 ] . length = 1 ;
 key [ 2 ] . key = & frame_number ;
 key [ 3 ] . length = 0 ;
 key [ 3 ] . key = NULL ;
 mtu_data = wmem_new ( wmem_file_scope ( ) , mtu_data_t ) ;
 mtu_data -> mtu = mtu ;
 wmem_tree_insert32_array ( mtus , key , mtu_data ) ;
 }


uint16_t ksz9131ReadPhyReg(NetInterface *interface, uint8_t address)
{
   uint16_t data;

   //Read the specified PHY register
   if(interface->smiDriver != NULL)
   {
      data = interface->smiDriver->readPhyReg(SMI_OPCODE_READ,
         interface->phyAddr, address);
   }
   else
   {
      data = interface->nicDriver->readPhyReg(SMI_OPCODE_READ,
         interface->phyAddr, address);
   }

   //Return the value of the PHY register
   return data;
}


static inline void RENAME(yvu9_to_yuy2)(const uint8_t *src1, const uint8_t *src2, const uint8_t *src3, uint8_t *dst, unsigned width, unsigned height, int srcStride1, int srcStride2, int srcStride3, int dstStride) { unsigned long y,x,w,h; w=width/2; h=height; for(y=0;y<h;y++){ const uint8_t* yp=src1+srcStride1*y; const uint8_t* up=src2+srcStride2*(y>>2); const uint8_t* vp=src3+srcStride3*(y>>2); uint8_t* d=dst+dstStride*y; x=0; #ifdef HAVE_MMX for(;x<w-7;x+=8) { asm volatile( PREFETCH" 32(%1, %0)\n\t" PREFETCH" 32(%2, %0)\n\t" PREFETCH" 32(%3, %0)\n\t" "movq (%1, %0, 4), %%mm0\n\t" /* Y0Y1Y2Y3Y4Y5Y6Y7 */ "movq (%2, %0), %%mm1\n\t" /* U0U1U2U3U4U5U6U7 */ "movq (%3, %0), %%mm2\n\t" /* V0V1V2V3V4V5V6V7 */ "movq %%mm0, %%mm3\n\t" /* Y0Y1Y2Y3Y4Y5Y6Y7 */ "movq %%mm1, %%mm4\n\t" /* U0U1U2U3U4U5U6U7 */ "movq %%mm2, %%mm5\n\t" /* V0V1V2V3V4V5V6V7 */ "punpcklbw %%mm1, %%mm1\n\t" /* U0U0 U1U1 U2U2 U3U3 */ "punpcklbw %%mm2, %%mm2\n\t" /* V0V0 V1V1 V2V2 V3V3 */ "punpckhbw %%mm4, %%mm4\n\t" /* U4U4 U5U5 U6U6 U7U7 */ "punpckhbw %%mm5, %%mm5\n\t" /* V4V4 V5V5 V6V6 V7V7 */ "movq %%mm1, %%mm6\n\t" "punpcklbw %%mm2, %%mm1\n\t" /* U0V0 U0V0 U1V1 U1V1*/ "punpcklbw %%mm1, %%mm0\n\t" /* Y0U0 Y1V0 Y2U0 Y3V0*/ "punpckhbw %%mm1, %%mm3\n\t" /* Y4U1 Y5V1 Y6U1 Y7V1*/ MOVNTQ" %%mm0, (%4, %0, 8)\n\t" MOVNTQ" %%mm3, 8(%4, %0, 8)\n\t" "punpckhbw %%mm2, %%mm6\n\t" /* U2V2 U2V2 U3V3 U3V3*/ "movq 8(%1, %0, 4), %%mm0\n\t" "movq %%mm0, %%mm3\n\t" "punpcklbw %%mm6, %%mm0\n\t" /* Y U2 Y V2 Y U2 Y V2*/ "punpckhbw %%mm6, %%mm3\n\t" /* Y U3 Y V3 Y U3 Y V3*/ MOVNTQ" %%mm0, 16(%4, %0, 8)\n\t" MOVNTQ" %%mm3, 24(%4, %0, 8)\n\t" "movq %%mm4, %%mm6\n\t" "movq 16(%1, %0, 4), %%mm0\n\t" "movq %%mm0, %%mm3\n\t" "punpcklbw %%mm5, %%mm4\n\t" "punpcklbw %%mm4, %%mm0\n\t" /* Y U4 Y V4 Y U4 Y V4*/ "punpckhbw %%mm4, %%mm3\n\t" /* Y U5 Y V5 Y U5 Y V5*/ MOVNTQ" %%mm0, 32(%4, %0, 8)\n\t" MOVNTQ" %%mm3, 40(%4, %0, 8)\n\t" "punpckhbw %%mm5, %%mm6\n\t" "movq 24(%1, %0, 4), %%mm0\n\t" "movq %%mm0, %%mm3\n\t" "punpcklbw %%mm6, %%mm0\n\t" /* Y U6 Y V6 Y U6 Y V6*/ "punpckhbw %%mm6, %%mm3\n\t" /* Y U7 Y V7 Y U7 Y V7*/ MOVNTQ" %%mm0, 48(%4, %0, 8)\n\t" MOVNTQ" %%mm3, 56(%4, %0, 8)\n\t" : "+r" (x) : "r"(yp), "r" (up), "r"(vp), "r"(d) :"memory"); } #endif for(; x<w; x++) { const int x2= x<<2; d[8*x+0]=yp[x2]; d[8*x+1]=up[x]; d[8*x+2]=yp[x2+1]; d[8*x+3]=vp[x]; d[8*x+4]=yp[x2+2]; d[8*x+5]=up[x]; d[8*x+6]=yp[x2+3]; d[8*x+7]=vp[x]; } } #ifdef HAVE_MMX asm( EMMS" \n\t" SFENCE" \n\t" ::: "memory" ); #endif }


static void purple_remove_buddy ( struct im_connection * ic , char * who , char * group ) {
 PurpleBuddy * pb ;
 struct purple_data * pd = ic -> proto_data ;
 pb = purple_find_buddy ( pd -> account , who ) ;
 if ( pb != NULL ) {
 PurpleGroup * group ;
 group = purple_buddy_get_group ( pb ) ;
 purple_account_remove_buddy ( pd -> account , pb , group ) ;
 purple_blist_remove_buddy ( pb ) ;
 }
 purple_gg_buddylist_export ( pd -> account -> gc ) ;
 }


static void *av_mallocz_static(unsigned int size) { void *ptr = av_mallocz(size); if(ptr){ array_static =av_fast_realloc(array_static, &allocated_static, sizeof(void*)*(last_static+1)); if(!array_static) return NULL; array_static[last_static++] = ptr; } return ptr; }


void pef7071Tick(NetInterface *interface)
{
   uint16_t value;
   bool_t linkState;

   //Read status register
   value = pef7071ReadPhyReg(interface, PEF7071_STAT);
   //Retrieve current link state
   linkState = (value & PEF7071_STAT_LS) ? TRUE : FALSE;

   //Link up event?
   if(linkState && !interface->linkState)
   {
      //Set event flag
      interface->phyEvent = TRUE;
      //Notify the TCP/IP stack of the event
      osSetEvent(&netEvent);
   }
   //Link down event?
   else if(!linkState && interface->linkState)
   {
      //Set event flag
      interface->phyEvent = TRUE;
      //Notify the TCP/IP stack of the event
      osSetEvent(&netEvent);
   }
}


void read_embedded_server_arguments ( const char * name ) {
 char argument [ 1024 ] , buff [ FN_REFLEN ] , * str = 0 ;
 FILE * file ;
 if ( ! test_if_hard_path ( name ) ) {
 strxmov ( buff , opt_basedir , name , NullS ) ;
 name = buff ;
 }
 fn_format ( buff , name , "" , "" , MY_UNPACK_FILENAME ) ;
 if ( ! embedded_server_arg_count ) {
 embedded_server_arg_count = 1 ;
 embedded_server_args [ 0 ] = ( char * ) "" ;
 }
 if ( ! ( file = my_fopen ( buff , O_RDONLY | FILE_BINARY , MYF ( MY_WME ) ) ) ) die ( "Failed to open file '%s'" , buff ) ;
 while ( embedded_server_arg_count < MAX_EMBEDDED_SERVER_ARGS && ( str = fgets ( argument , sizeof ( argument ) , file ) ) ) {
 * ( strend ( str ) - 1 ) = 0 ;
 if ( ! ( embedded_server_args [ embedded_server_arg_count ] = ( char * ) my_strdup ( str , MYF ( MY_WME ) ) ) ) {
 my_fclose ( file , MYF ( 0 ) ) ;
 die ( "Out of memory" ) ;
 }
 embedded_server_arg_count ++ ;
 }
 my_fclose ( file , MYF ( 0 ) ) ;
 if ( str ) die ( "Too many arguments in option file: %s" , name ) ;
 return ;
 }


static ssize_t fuse_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
	struct file *file = iocb->ki_filp;
	struct fuse_file *ff = file->private_data;
	struct inode *inode = file_inode(file);

	if (is_bad_inode(inode))
		return -EIO;

	if (FUSE_IS_DAX(inode))
		return fuse_dax_write_iter(iocb, from);

	if (!(ff->open_flags & FOPEN_DIRECT_IO))
		return fuse_cache_write_iter(iocb, from);
	else
		return fuse_direct_write_iter(iocb, from);
}


sPAPROptionVector *spapr_ovec_new(void) { sPAPROptionVector *ov; ov = g_new0(sPAPROptionVector, 1); ov->bitmap = bitmap_new(OV_MAXBITS); return ov; }


static int fuse_permission(struct inode *inode, int mask)
{
	struct fuse_conn *fc = get_fuse_conn(inode);
	bool refreshed = false;
	int err = 0;

	if (!fuse_allow_current_process(fc))
		return -EACCES;

	/*
	 * If attributes are needed, refresh them before proceeding
	 */
	if (fc->default_permissions ||
	    ((mask & MAY_EXEC) && S_ISREG(inode->i_mode))) {
		struct fuse_inode *fi = get_fuse_inode(inode);
		u32 perm_mask = STATX_MODE | STATX_UID | STATX_GID;

		if (perm_mask & READ_ONCE(fi->inval_mask) ||
		    time_before64(fi->i_time, get_jiffies_64())) {
			refreshed = true;

			err = fuse_perm_getattr(inode, mask);
			if (err)
				return err;
		}
	}

	if (fc->default_permissions) {
		err = generic_permission(inode, mask);

		/* If permission is denied, try to refresh file
		   attributes.  This is also needed, because the root
		   node will at first have no permissions */
		if (err == -EACCES && !refreshed) {
			err = fuse_perm_getattr(inode, mask);
			if (!err)
				err = generic_permission(inode, mask);
		}

		/* Note: the opposite of the above test does not
		   exist.  So if permissions are revoked this won't be
		   noticed immediately, only after the attribute
		   timeout has expired */
	} else if (mask & (MAY_ACCESS | MAY_CHDIR)) {
		err = fuse_access(inode, mask);
	} else if ((mask & MAY_EXEC) && S_ISREG(inode->i_mode)) {
		if (!(inode->i_mode & S_IXUGO)) {
			if (refreshed)
				return -EACCES;

			err = fuse_perm_getattr(inode, mask);
			if (!err && !(inode->i_mode & S_IXUGO))
				return -EACCES;
		}
	}
	return err;
}


int main(int argc, char *argv[]) { int fd_in, fd_out, comp_len, uncomp_len, i, last_out; char buf_in[1024], buf_out[65536]; z_stream zstream; struct stat statbuf; if (argc < 3) { printf("Usage: %s <infile.swf> <outfile.swf>\n", argv[0]); return 1; } fd_in = open(argv[1], O_RDONLY); if (fd_in < 0) { perror("Error opening input file"); return 1; } fd_out = open(argv[2], O_WRONLY | O_CREAT, 00644); if (fd_out < 0) { perror("Error opening output file"); close(fd_in); return 1; } if (read(fd_in, &buf_in, 8) != 8) { printf("Header error\n"); close(fd_in); close(fd_out); return 1; } if (buf_in[0] != 'C' || buf_in[1] != 'W' || buf_in[2] != 'S') { printf("Not a compressed flash file\n"); return 1; } fstat(fd_in, &statbuf); comp_len = statbuf.st_size; uncomp_len = buf_in[4] | (buf_in[5] << 8) | (buf_in[6] << 16) | (buf_in[7] << 24); printf("Compressed size: %d Uncompressed size: %d\n", comp_len - 4, uncomp_len - 4); // write out modified header buf_in[0] = 'F'; if (write(fd_out, &buf_in, 8) < 8) { perror("Error writing output file"); return 1; } zstream.zalloc = NULL; zstream.zfree = NULL; zstream.opaque = NULL; if (inflateInit(&zstream) != Z_OK) { fprintf(stderr, "inflateInit failed\n"); return 1; } for (i = 0; i < comp_len - 8;) { int ret, len = read(fd_in, &buf_in, 1024); dbgprintf("read %d bytes\n", len); last_out = zstream.total_out; zstream.next_in = &buf_in[0]; zstream.avail_in = len; zstream.next_out = &buf_out[0]; zstream.avail_out = 65536; ret = inflate(&zstream, Z_SYNC_FLUSH); if (ret != Z_STREAM_END && ret != Z_OK) { printf("Error while decompressing: %d\n", ret); inflateEnd(&zstream); return 1; } dbgprintf("a_in: %d t_in: %lu a_out: %d t_out: %lu -- %lu out\n", zstream.avail_in, zstream.total_in, zstream.avail_out, zstream.total_out, zstream.total_out - last_out); if (write(fd_out, &buf_out, zstream.total_out - last_out) < zstream.total_out - last_out) { perror("Error writing output file"); return 1; } i += len; if (ret == Z_STREAM_END || ret == Z_BUF_ERROR) break; } if (zstream.total_out != uncomp_len - 8) { printf("Size mismatch (%lu != %d), updating header...\n", zstream.total_out, uncomp_len - 8); buf_in[0] = (zstream.total_out + 8) & 0xff; buf_in[1] = ((zstream.total_out + 8) >> 8) & 0xff; buf_in[2] = ((zstream.total_out + 8) >> 16) & 0xff; buf_in[3] = ((zstream.total_out + 8) >> 24) & 0xff; if ( lseek(fd_out, 4, SEEK_SET) < 0 || write(fd_out, &buf_in, 4) < 4) { perror("Error writing output file"); return 1; } } inflateEnd(&zstream); close(fd_in); close(fd_out); return 0; }


static gpg_err_code_t make_space ( struct make_space_ctx * c , size_t n ) {
 size_t used = c -> pos - c -> sexp -> d ;
 if ( used + n + sizeof ( DATALEN ) + 1 >= c -> allocated ) {
 gcry_sexp_t newsexp ;
 byte * newhead ;
 size_t newsize ;
 newsize = c -> allocated + 2 * ( n + sizeof ( DATALEN ) + 1 ) ;
 if ( newsize <= c -> allocated ) return GPG_ERR_TOO_LARGE ;
 newsexp = gcry_realloc ( c -> sexp , sizeof * newsexp + newsize - 1 ) ;
 if ( ! newsexp ) return gpg_err_code_from_errno ( errno ) ;
 c -> allocated = newsize ;
 newhead = newsexp -> d ;
 c -> pos = newhead + used ;
 c -> sexp = newsexp ;
 }
 return 0 ;
 }


error_t ipv6AddRoute(const Ipv6Addr *prefix, uint_t prefixLen,
   NetInterface *interface, const Ipv6Addr *nextHop, uint_t metric)
{
   error_t error;
   uint_t i;
   Ipv6RoutingTableEntry *entry;
   Ipv6RoutingTableEntry *firstFreeEntry;

   //Check parameters
   if(prefix == NULL || interface == NULL)
      return ERROR_INVALID_PARAMETER;

   //Keep track of the first free entry
   firstFreeEntry = NULL;

   //Get exclusive access
   osAcquireMutex(&netMutex);

   //Loop through routing table entries
   for(i = 0; i < IPV6_ROUTING_TABLE_SIZE; i++)
   {
      //Point to the current entry
      entry = &ipv6RoutingTable[i];

      //Valid entry?
      if(entry->valid)
      {
         //Check prefix length
         if(entry->prefixLen == prefixLen)
         {
            //Check whether the current entry matches the specified destination
            if(ipv6CompPrefix(&entry->prefix, prefix, prefixLen))
               break;
         }
      }
      else
      {
         //Keep track of the first free entry
         if(firstFreeEntry == NULL)
            firstFreeEntry = entry;
      }
   }

   //If the routing table does not contain the specified destination,
   //then a new entry should be created
   if(i >= IPV6_ROUTING_TABLE_SIZE)
      entry = firstFreeEntry;

   //Check whether the routing table runs out of space
   if(entry != NULL)
   {
      //Network destination
      entry->prefix = *prefix;
      entry->prefixLen = prefixLen;

      //Interface where to forward the packet
      entry->interface = interface;

      //Address of the next hop
      if(nextHop != NULL)
         entry->nextHop = *nextHop;
      else
         entry->nextHop = IPV6_UNSPECIFIED_ADDR;

      //Metric value
      entry->metric = metric;
      //The entry is now valid
      entry->valid = TRUE;

      //Successful processing
      error = NO_ERROR;
   }
   else
   {
      //The routing table is full
      error = ERROR_FAILURE;
   }

   //Release exclusive access
   osReleaseMutex(&netMutex);

   //Return status code
   return error;
}


static void dissect_applemidi ( tvbuff_t * tvb , packet_info * pinfo , proto_tree * tree ) {
 guint16 command ;
 if ( test_applemidi ( tvb , & command , TRUE ) ) dissect_applemidi_common ( tvb , pinfo , tree , command ) ;
 else call_dissector ( rtp_handle , tvb , pinfo , tree ) ;
 }


int tls_get_message_header ( SSL * s , int * mt ) {
 int skip_message , i , recvd_type , al ;
 unsigned char * p ;
 unsigned long l ;
 p = ( unsigned char * ) s -> init_buf -> data ;
 do {
 while ( s -> init_num < SSL3_HM_HEADER_LENGTH ) {
 i = s -> method -> ssl_read_bytes ( s , SSL3_RT_HANDSHAKE , & recvd_type , & p [ s -> init_num ] , SSL3_HM_HEADER_LENGTH - s -> init_num , 0 ) ;
 if ( i <= 0 ) {
 s -> rwstate = SSL_READING ;
 return 0 ;
 }
 if ( recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC ) {
 if ( s -> init_num != 0 || i != 1 || p [ 0 ] != SSL3_MT_CCS ) {
 al = SSL_AD_UNEXPECTED_MESSAGE ;
 SSLerr ( SSL_F_TLS_GET_MESSAGE_HEADER , SSL_R_BAD_CHANGE_CIPHER_SPEC ) ;
 goto f_err ;
 }
 s -> s3 -> tmp . message_type = * mt = SSL3_MT_CHANGE_CIPHER_SPEC ;
 s -> init_num = i - 1 ;
 s -> s3 -> tmp . message_size = i ;
 return 1 ;
 }
 else if ( recvd_type != SSL3_RT_HANDSHAKE ) {
 al = SSL_AD_UNEXPECTED_MESSAGE ;
 SSLerr ( SSL_F_TLS_GET_MESSAGE_HEADER , SSL_R_CCS_RECEIVED_EARLY ) ;
 goto f_err ;
 }
 s -> init_num += i ;
 }
 skip_message = 0 ;
 if ( ! s -> server ) if ( p [ 0 ] == SSL3_MT_HELLO_REQUEST ) if ( p [ 1 ] == 0 && p [ 2 ] == 0 && p [ 3 ] == 0 ) {
 s -> init_num = 0 ;
 skip_message = 1 ;
 if ( s -> msg_callback ) s -> msg_callback ( 0 , s -> version , SSL3_RT_HANDSHAKE , p , SSL3_HM_HEADER_LENGTH , s , s -> msg_callback_arg ) ;
 }
 }
 while ( skip_message ) ;
 * mt = * p ;
 s -> s3 -> tmp . message_type = * ( p ++ ) ;
 if ( RECORD_LAYER_is_sslv2_record ( & s -> rlayer ) ) {
 l = RECORD_LAYER_get_rrec_length ( & s -> rlayer ) + SSL3_HM_HEADER_LENGTH ;
 if ( l && ! BUF_MEM_grow_clean ( s -> init_buf , ( int ) l ) ) {
 SSLerr ( SSL_F_TLS_GET_MESSAGE_HEADER , ERR_R_BUF_LIB ) ;
 goto err ;
 }
 s -> s3 -> tmp . message_size = l ;
 s -> init_msg = s -> init_buf -> data ;
 s -> init_num = SSL3_HM_HEADER_LENGTH ;
 }
 else {
 n2l3 ( p , l ) ;
 if ( l > ( INT_MAX - SSL3_HM_HEADER_LENGTH ) ) {
 al = SSL_AD_ILLEGAL_PARAMETER ;
 SSLerr ( SSL_F_TLS_GET_MESSAGE_HEADER , SSL_R_EXCESSIVE_MESSAGE_SIZE ) ;
 goto f_err ;
 }
 if ( l && ! BUF_MEM_grow_clean ( s -> init_buf , ( int ) l + SSL3_HM_HEADER_LENGTH ) ) {
 SSLerr ( SSL_F_TLS_GET_MESSAGE_HEADER , ERR_R_BUF_LIB ) ;
 goto err ;
 }
 s -> s3 -> tmp . message_size = l ;
 s -> init_msg = s -> init_buf -> data + SSL3_HM_HEADER_LENGTH ;
 s -> init_num = 0 ;
 }
 return 1 ;
 f_err : ssl3_send_alert ( s , SSL3_AL_FATAL , al ) ;
 err : return 0 ;
 }


static int _setup_cluster_cond_limits ( slurmdb_cluster_cond_t * cluster_cond , char * * extra ) {
 int set = 0 ;
 ListIterator itr = NULL ;
 char * object = NULL ;
 if ( ! cluster_cond ) return 0 ;
 if ( cluster_cond -> with_deleted ) xstrcat ( * extra , " where (deleted=0 || deleted=1)" ) ;
 else xstrcat ( * extra , " where deleted=0" ) ;
 if ( cluster_cond -> cluster_list && list_count ( cluster_cond -> cluster_list ) ) {
 set = 0 ;
 xstrcat ( * extra , " && (" ) ;
 itr = list_iterator_create ( cluster_cond -> cluster_list ) ;
 while ( ( object = list_next ( itr ) ) ) {
 if ( set ) xstrcat ( * extra , " || " ) ;
 xstrfmtcat ( * extra , "name='%s'" , object ) ;
 set = 1 ;
 }
 list_iterator_destroy ( itr ) ;
 xstrcat ( * extra , ")" ) ;
 }
 if ( cluster_cond -> federation_list && list_count ( cluster_cond -> federation_list ) ) {
 set = 0 ;
 xstrcat ( * extra , " && (" ) ;
 itr = list_iterator_create ( cluster_cond -> federation_list ) ;
 while ( ( object = list_next ( itr ) ) ) {
 if ( set ) xstrcat ( * extra , " || " ) ;
 xstrfmtcat ( * extra , "federation='%s'" , object ) ;
 set = 1 ;
 }
 list_iterator_destroy ( itr ) ;
 xstrcat ( * extra , ")" ) ;
 }
 if ( cluster_cond -> plugin_id_select_list && list_count ( cluster_cond -> plugin_id_select_list ) ) {
 set = 0 ;
 xstrcat ( * extra , " && (" ) ;
 itr = list_iterator_create ( cluster_cond -> plugin_id_select_list ) ;
 while ( ( object = list_next ( itr ) ) ) {
 if ( set ) xstrcat ( * extra , " || " ) ;
 xstrfmtcat ( * extra , "plugin_id_select='%s'" , object ) ;
 set = 1 ;
 }
 list_iterator_destroy ( itr ) ;
 xstrcat ( * extra , ")" ) ;
 }
 if ( cluster_cond -> rpc_version_list && list_count ( cluster_cond -> rpc_version_list ) ) {
 set = 0 ;
 xstrcat ( * extra , " && (" ) ;
 itr = list_iterator_create ( cluster_cond -> rpc_version_list ) ;
 while ( ( object = list_next ( itr ) ) ) {
 if ( set ) xstrcat ( * extra , " || " ) ;
 xstrfmtcat ( * extra , "rpc_version='%s'" , object ) ;
 set = 1 ;
 }
 list_iterator_destroy ( itr ) ;
 xstrcat ( * extra , ")" ) ;
 }
 if ( cluster_cond -> classification ) {
 xstrfmtcat ( * extra , " && (classification & %u)" , cluster_cond -> classification ) ;
 }
 if ( cluster_cond -> flags != NO_VAL ) {
 xstrfmtcat ( * extra , " && (flags & %u)" , cluster_cond -> flags ) ;
 }
 return set ;
 }


bool_t mqttSnClientIsShortTopicName(const char_t *topicName)
{
   bool_t res;

   //Initialize variable
   res = FALSE;

   //A short topic name is a topic name that has a fixed length of two octets
   if(osStrlen(topicName) == 2)
   {
      //Ensure the topic name does not contains wildcard characters
      if(osStrchr(topicName, '#') == NULL && osStrchr(topicName, '+') == NULL)
      {
         //The short topic name is a valid
         res = TRUE;
      }
   }

   //Return TRUE if the specified topic name is a short topic name
   return res;
}


xmlEncodeEntitiesInternal(xmlDocPtr doc, const xmlChar *input, int attr) {
    const xmlChar *cur = input;
    xmlChar *buffer = NULL;
    xmlChar *out = NULL;
    size_t buffer_size = 0;
    int html = 0;

    if (input == NULL) return(NULL);
    if (doc != NULL)
        html = (doc->type == XML_HTML_DOCUMENT_NODE);

    /*
     * allocate an translation buffer.
     */
    buffer_size = 1000;
    buffer = (xmlChar *) xmlMalloc(buffer_size * sizeof(xmlChar));
    if (buffer == NULL) {
        xmlEntitiesErrMemory("xmlEncodeEntities: malloc failed");
	return(NULL);
    }
    out = buffer;

    while (*cur != '\0') {
        size_t indx = out - buffer;
        if (indx + 100 > buffer_size) {

	    growBufferReentrant();
	    out = &buffer[indx];
	}

	/*
	 * By default one have to encode at least '<', '>', '"' and '&' !
	 */
	if (*cur == '<') {
	    const xmlChar *end;

	    /*
	     * Special handling of server side include in HTML attributes
	     */
	    if (html && attr &&
	        (cur[1] == '!') && (cur[2] == '-') && (cur[3] == '-') &&
	        ((end = xmlStrstr(cur, BAD_CAST "-->")) != NULL)) {
	        while (cur != end) {
		    *out++ = *cur++;
		    indx = out - buffer;
		    if (indx + 100 > buffer_size) {
			growBufferReentrant();
			out = &buffer[indx];
		    }
		}
		*out++ = *cur++;
		*out++ = *cur++;
		*out++ = *cur++;
		continue;
	    }
	    *out++ = '&';
	    *out++ = 'l';
	    *out++ = 't';
	    *out++ = ';';
	} else if (*cur == '>') {
	    *out++ = '&';
	    *out++ = 'g';
	    *out++ = 't';
	    *out++ = ';';
	} else if (*cur == '&') {
	    /*
	     * Special handling of &{...} construct from HTML 4, see
	     * http://www.w3.org/TR/html401/appendix/notes.html#h-B.7.1
	     */
	    if (html && attr && (cur[1] == '{') &&
	        (strchr((const char *) cur, '}'))) {
	        while (*cur != '}') {
		    *out++ = *cur++;
		    indx = out - buffer;
		    if (indx + 100 > buffer_size) {
			growBufferReentrant();
			out = &buffer[indx];
		    }
		}
		*out++ = *cur++;
		continue;
	    }
	    *out++ = '&';
	    *out++ = 'a';
	    *out++ = 'm';
	    *out++ = 'p';
	    *out++ = ';';
	} else if (((*cur >= 0x20) && (*cur < 0x80)) ||
	    (*cur == '\n') || (*cur == '\t') || ((html) && (*cur == '\r'))) {
	    /*
	     * default case, just copy !
	     */
	    *out++ = *cur;
	} else if (*cur >= 0x80) {
	    if (((doc != NULL) && (doc->encoding != NULL)) || (html)) {
		/*
		 * Bjørn Reese <br@sseusa.com> provided the patch
	        xmlChar xc;
	        xc = (*cur & 0x3F) << 6;
	        if (cur[1] != 0) {
		    xc += *(++cur) & 0x3F;
		    *out++ = xc;
	        } else
		 */
		*out++ = *cur;
	    } else {
		/*
		 * We assume we have UTF-8 input.
		 */
		char buf[11], *ptr;
		int val = 0, l = 1;

		if (*cur < 0xC0) {
		    xmlEntitiesErr(XML_CHECK_NOT_UTF8,
			    "xmlEncodeEntities: input not UTF-8");
		    if (doc != NULL)
			doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1");
		    snprintf(buf, sizeof(buf), "&#%d;", *cur);
		    buf[sizeof(buf) - 1] = 0;
		    ptr = buf;
		    while (*ptr != 0) *out++ = *ptr++;
		    cur++;
		    continue;
		} else if (*cur < 0xE0) {
                    val = (cur[0]) & 0x1F;
		    val <<= 6;
		    val |= (cur[1]) & 0x3F;
		    l = 2;
		} else if (*cur < 0xF0) {
                    val = (cur[0]) & 0x0F;
		    val <<= 6;
		    val |= (cur[1]) & 0x3F;
		    val <<= 6;
		    val |= (cur[2]) & 0x3F;
		    l = 3;
		} else if (*cur < 0xF8) {
                    val = (cur[0]) & 0x07;
		    val <<= 6;
		    val |= (cur[1]) & 0x3F;
		    val <<= 6;
		    val |= (cur[2]) & 0x3F;
		    val <<= 6;
		    val |= (cur[3]) & 0x3F;
		    l = 4;
		}
		if ((l == 1) || (!IS_CHAR(val))) {
		    xmlEntitiesErr(XML_ERR_INVALID_CHAR,
			"xmlEncodeEntities: char out of range\n");
		    if (doc != NULL)
			doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1");
		    snprintf(buf, sizeof(buf), "&#%d;", *cur);
		    buf[sizeof(buf) - 1] = 0;
		    ptr = buf;
		    while (*ptr != 0) *out++ = *ptr++;
		    cur++;
		    continue;
		}
		/*
		 * We could do multiple things here. Just save as a char ref
		 */
		snprintf(buf, sizeof(buf), "&#x%X;", val);
		buf[sizeof(buf) - 1] = 0;
		ptr = buf;
		while (*ptr != 0) *out++ = *ptr++;
		cur += l;
		continue;
	    }
	} else if (IS_BYTE_CHAR(*cur)) {
	    char buf[11], *ptr;

	    snprintf(buf, sizeof(buf), "&#%d;", *cur);
	    buf[sizeof(buf) - 1] = 0;
            ptr = buf;
	    while (*ptr != 0) *out++ = *ptr++;
	}
	cur++;
    }
    *out = 0;
    return(buffer);

mem_error:
    xmlEntitiesErrMemory("xmlEncodeEntities: realloc failed");
    xmlFree(buffer);
    return(NULL);
}


static int init_common(VC9Context *v) { static int done = 0; int i; v->mv_type_mb_plane = v->direct_mb_plane = v->skip_mb_plane = NULL; v->pq = -1; #if HAS_ADVANCED_PROFILE v->ac_pred_plane = v->over_flags_plane = NULL; v->hrd_rate = v->hrd_buffer = NULL; #endif #if 0 // spec -> actual tables converter for(i=0; i<64; i++){ int code= (vc9_norm6_spec[i][1] << vc9_norm6_spec[i][4]) + vc9_norm6_spec[i][3]; av_log(NULL, AV_LOG_DEBUG, "0x%03X, ", code); if(i%16==15) av_log(NULL, AV_LOG_DEBUG, "\n"); } for(i=0; i<64; i++){ int code= vc9_norm6_spec[i][2] + vc9_norm6_spec[i][4]; av_log(NULL, AV_LOG_DEBUG, "%2d, ", code); if(i%16==15) av_log(NULL, AV_LOG_DEBUG, "\n"); } #endif if(!done) { done = 1; INIT_VLC(&vc9_bfraction_vlc, VC9_BFRACTION_VLC_BITS, 23, vc9_bfraction_bits, 1, 1, vc9_bfraction_codes, 1, 1, 1); INIT_VLC(&vc9_norm2_vlc, VC9_NORM2_VLC_BITS, 4, vc9_norm2_bits, 1, 1, vc9_norm2_codes, 1, 1, 1); INIT_VLC(&vc9_norm6_vlc, VC9_NORM6_VLC_BITS, 64, vc9_norm6_bits, 1, 1, vc9_norm6_codes, 2, 2, 1); INIT_VLC(&vc9_cbpcy_i_vlc, VC9_CBPCY_I_VLC_BITS, 64, vc9_cbpcy_i_bits, 1, 1, vc9_cbpcy_i_codes, 2, 2, 1); INIT_VLC(&vc9_imode_vlc, VC9_IMODE_VLC_BITS, 7, vc9_imode_bits, 1, 1, vc9_imode_codes, 1, 1, 1); for(i=0; i<3; i++) { INIT_VLC(&vc9_4mv_block_pattern_vlc[i], VC9_4MV_BLOCK_PATTERN_VLC_BITS, 16, vc9_4mv_block_pattern_bits[i], 1, 1, vc9_4mv_block_pattern_codes[i], 1, 1, 1); INIT_VLC(&vc9_cbpcy_p_vlc[i], VC9_CBPCY_P_VLC_BITS, 64, vc9_cbpcy_p_bits[i], 1, 1, vc9_cbpcy_p_codes[i], 2, 2, 1); } for (i=0; i<2; i++) { INIT_VLC(&vc9_mv_diff_vlc[i], VC9_MV_DIFF_VLC_BITS, 73, vc9_mv_diff_bits[i], 1, 1, vc9_mv_diff_codes[i], 2, 2, 1); INIT_VLC(&vc9_luma_dc_vlc[i], VC9_LUMA_DC_VLC_BITS, 120, vc9_luma_dc_bits[i], 1, 1, vc9_luma_dc_codes[i], 4, 4, 1); INIT_VLC(&vc9_ttmb_vlc[i], VC9_TTMB_VLC_BITS, 16, vc9_ttmb_bits[i], 1, 1, vc9_ttmb_codes[i], 2, 2, 1); } } return 0; }


static void usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,
                                      uint8_t ep)
{
    struct usb_redir_bulk_packet_header bulk_packet;
    size_t size = usb_packet_size(p);
    const int maxp = dev->endpoint[EP2I(ep)].max_packet_size;

    if (usbredir_already_in_flight(dev, p->id)) {
        p->status = USB_RET_ASYNC;
        return;
    }

    if (dev->endpoint[EP2I(ep)].bulk_receiving_enabled) {
        if (size != 0 && (size % maxp) == 0) {
            usbredir_handle_buffered_bulk_in_data(dev, p, ep);
            return;
        }
        WARNING("bulk recv invalid size %zd ep %02x, disabling\n", size, ep);
        assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL);
        usbredir_stop_bulk_receiving(dev, ep);
        dev->endpoint[EP2I(ep)].bulk_receiving_enabled = 0;
    }

    DPRINTF("bulk-out ep %02X stream %u len %zd id %"PRIu64"\n",
            ep, p->stream, size, p->id);

    bulk_packet.endpoint  = ep;
    bulk_packet.length    = size;
    bulk_packet.stream_id = p->stream;
    bulk_packet.length_high = size >> 16;
    assert(bulk_packet.length_high == 0 ||
           usbredirparser_peer_has_cap(dev->parser,
                                       usb_redir_cap_32bits_bulk_length));

    if (ep & USB_DIR_IN || size == 0) {
        usbredirparser_send_bulk_packet(dev->parser, p->id,
                                        &bulk_packet, NULL, 0);
    } else {
        uint8_t buf[size];
        usb_packet_copy(p, buf, size);
        usbredir_log_data(dev, "bulk data out:", buf, size);
        usbredirparser_send_bulk_packet(dev->parser, p->id,
                                        &bulk_packet, buf, size);
    }
    usbredirparser_do_write(dev->parser);
    p->status = USB_RET_ASYNC;
}


static void xen_ram_init(ram_addr_t ram_size) { RAMBlock *new_block; ram_addr_t below_4g_mem_size, above_4g_mem_size = 0; new_block = qemu_mallocz(sizeof (*new_block)); pstrcpy(new_block->idstr, sizeof (new_block->idstr), "xen.ram"); new_block->host = NULL; new_block->offset = 0; new_block->length = ram_size; QLIST_INSERT_HEAD(&ram_list.blocks, new_block, next); ram_list.phys_dirty = qemu_realloc(ram_list.phys_dirty, new_block->length >> TARGET_PAGE_BITS); memset(ram_list.phys_dirty + (new_block->offset >> TARGET_PAGE_BITS), 0xff, new_block->length >> TARGET_PAGE_BITS); if (ram_size >= 0xe0000000 ) { above_4g_mem_size = ram_size - 0xe0000000; below_4g_mem_size = 0xe0000000; } else { below_4g_mem_size = ram_size; } cpu_register_physical_memory(0, below_4g_mem_size, new_block->offset); #if TARGET_PHYS_ADDR_BITS > 32 if (above_4g_mem_size > 0) { cpu_register_physical_memory(0x100000000ULL, above_4g_mem_size, new_block->offset + below_4g_mem_size); } #endif }


void assertInvalidProjection(const char* queryStr, const char* projStr) {
    BSONObj query = fromjson(queryStr);
    BSONObj projObj = fromjson(projStr);
    QueryTestServiceContext serviceCtx;
    auto opCtx = serviceCtx.makeOperationContext();
    const boost::intrusive_ptr<ExpressionContext> expCtx(
        new ExpressionContext(opCtx.get(), std::unique_ptr<CollatorInterface>(nullptr), kTestNss));
    StatusWithMatchExpression statusWithMatcher = MatchExpressionParser::parse(query, expCtx);
    ASSERT_OK(statusWithMatcher.getStatus());
    std::unique_ptr<MatchExpression> queryMatchExpr = std::move(statusWithMatcher.getValue());
    ASSERT_THROWS(
        projection_ast::parse(expCtx, projObj, queryMatchExpr.get(), query, ProjectionPolicies{}),
        DBException);
}


static void sd_close(BlockDriverState *bs) { Error *local_err = NULL; BDRVSheepdogState *s = bs->opaque; SheepdogVdiReq hdr; SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr; unsigned int wlen, rlen = 0; int fd, ret; DPRINTF("%s\n", s->name); fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); return; } memset(&hdr, 0, sizeof(hdr)); hdr.opcode = SD_OP_RELEASE_VDI; hdr.type = LOCK_TYPE_NORMAL; hdr.base_vdi_id = s->inode.vdi_id; wlen = strlen(s->name) + 1; hdr.data_length = wlen; hdr.flags = SD_FLAG_CMD_WRITE; ret = do_req(fd, s->bs, (SheepdogReq *)&hdr, s->name, &wlen, &rlen); closesocket(fd); if (!ret && rsp->result != SD_RES_SUCCESS && rsp->result != SD_RES_VDI_NOT_LOCKED) { error_report("%s, %s", sd_strerror(rsp->result), s->name); } aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd, false, NULL, NULL, NULL, NULL); closesocket(s->fd); qapi_free_SocketAddressLegacy(s->addr); }


TEST(QueryProjectionTest, InvalidElemMatchGeoNearProjection) {
    assertInvalidProjection(
        "{}",
        "{a: {$elemMatch: {$nearSphere: {$geometry: {type: 'Point', coordinates: [0, 0]}}}}}");
}


TEST(QueryProjectionTest, InvalidPositionalOperatorProjections) {
    assertInvalidProjection("{}", "{'a.$': 1}");
    assertInvalidProjection("{a: 1}", "{'b.$': 1}");
    assertInvalidProjection("{a: 1}", "{'a.$': 0}");
    assertInvalidProjection("{a: 1}", "{'a.$.d.$': 1}");
    assertInvalidProjection("{a: 1}", "{'a.$.$': 1}");
    assertInvalidProjection("{a: 1, b: 1, c: 1}", "{'abc.$': 1}");
    assertInvalidProjection("{$or: [{a: 1}, {$or: [{b: 1}, {c: 1}]}]}", "{'d.$': 1}");
    assertInvalidProjection("{a: [1, 2, 3]}", "{'.$': 1}");
}


TEST(QueryProjectionTest, InvalidElemMatchTextProjection) {
    assertInvalidProjection("{}", "{a: {$elemMatch: {$text: {$search: 'str'}}}}");
}


static AsfStream * gst_asf_demux_add_video_stream ( GstASFDemux * demux , asf_stream_video_format * video , guint16 id , guint8 * * p_data , guint64 * p_size ) {
 GstTagList * tags = NULL ;
 GstStructure * caps_s ;
 GstBuffer * extradata = NULL ;
 GstPad * src_pad ;
 GstCaps * caps ;
 gchar * str ;
 gchar * name = NULL ;
 gchar * codec_name = NULL ;
 guint64 size_left = video -> size - 40 ;
 GstBuffer * streamheader = NULL ;
 guint par_w = 1 , par_h = 1 ;
 name = g_strdup_printf ( "video_%u" , demux -> num_video_streams ) ;
 src_pad = gst_pad_new_from_static_template ( & video_src_template , name ) ;
 g_free ( name ) ;
 if ( size_left ) {
 GST_LOG ( "Video header has %" G_GUINT64_FORMAT " bytes of codec specific data (vs %" G_GUINT64_FORMAT ")" , size_left , * p_size ) ;
 g_assert ( size_left <= * p_size ) ;
 gst_asf_demux_get_buffer ( & extradata , size_left , p_data , p_size ) ;
 }
 GST_DEBUG ( "video codec %" GST_FOURCC_FORMAT , GST_FOURCC_ARGS ( video -> tag ) ) ;
 caps = gst_riff_create_video_caps ( video -> tag , NULL , ( gst_riff_strf_vids * ) video , extradata , NULL , & codec_name ) ;
 if ( caps == NULL ) {
 caps = gst_caps_new_simple ( "video/x-asf-unknown" , "fourcc" , G_TYPE_UINT , video -> tag , NULL ) ;
 }
 else {
 GstStructure * s ;
 gint ax , ay ;
 s = gst_asf_demux_get_metadata_for_stream ( demux , id ) ;
 if ( gst_structure_get_int ( s , "AspectRatioX" , & ax ) && gst_structure_get_int ( s , "AspectRatioY" , & ay ) && ( ax > 0 && ay > 0 ) ) {
 par_w = ax ;
 par_h = ay ;
 gst_caps_set_simple ( caps , "pixel-aspect-ratio" , GST_TYPE_FRACTION , ax , ay , NULL ) ;
 }
 else {
 guint ax , ay ;
 GST_DEBUG ( "Retrying with global metadata %" GST_PTR_FORMAT , demux -> global_metadata ) ;
 s = demux -> global_metadata ;
 if ( gst_structure_get_uint ( s , "AspectRatioX" , & ax ) && gst_structure_get_uint ( s , "AspectRatioY" , & ay ) ) {
 GST_DEBUG ( "ax:%d, ay:%d" , ax , ay ) ;
 if ( ax > 0 && ay > 0 ) {
 par_w = ax ;
 par_h = ay ;
 gst_caps_set_simple ( caps , "pixel-aspect-ratio" , GST_TYPE_FRACTION , ax , ay , NULL ) ;
 }
 }
 }
 s = gst_caps_get_structure ( caps , 0 ) ;
 gst_structure_remove_field ( s , "framerate" ) ;
 }
 caps_s = gst_caps_get_structure ( caps , 0 ) ;
 if ( gst_structure_has_name ( caps_s , "video/x-wmv" ) ) {
 str = g_strdup_printf ( "%" GST_FOURCC_FORMAT , GST_FOURCC_ARGS ( video -> tag ) ) ;
 gst_caps_set_simple ( caps , "format" , G_TYPE_STRING , str , NULL ) ;
 g_free ( str ) ;
 }
 else if ( gst_structure_has_name ( caps_s , "video/x-h264" ) ) {
 const GValue * value = gst_structure_get_value ( caps_s , "codec_data" ) ;
 if ( value ) {
 GstBuffer * buf = gst_value_get_buffer ( value ) ;
 GstMapInfo mapinfo ;
 if ( gst_buffer_map ( buf , & mapinfo , GST_MAP_READ ) ) {
 if ( mapinfo . size >= 4 && GST_READ_UINT32_BE ( mapinfo . data ) == 1 ) {
 streamheader = gst_buffer_ref ( buf ) ;
 gst_asf_demux_add_stream_headers_to_caps ( demux , buf , caps_s ) ;
 gst_structure_remove_field ( caps_s , "codec_data" ) ;
 }
 gst_buffer_unmap ( buf , & mapinfo ) ;
 }
 }
 }
 if ( demux -> asf_3D_mode != GST_ASF_3D_NONE ) {
 GstVideoMultiviewMode mv_mode = GST_VIDEO_MULTIVIEW_MODE_NONE ;
 GstVideoMultiviewFlags mv_flags = GST_VIDEO_MULTIVIEW_FLAGS_NONE ;
 const gchar * mview_mode_str ;
 switch ( demux -> asf_3D_mode ) {
 case GST_ASF_3D_SIDE_BY_SIDE_HALF_LR : mv_mode = GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE ;
 break ;
 case GST_ASF_3D_SIDE_BY_SIDE_HALF_RL : mv_mode = GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE ;
 mv_flags = GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST ;
 break ;
 case GST_ASF_3D_TOP_AND_BOTTOM_HALF_LR : mv_mode = GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM ;
 break ;
 case GST_ASF_3D_TOP_AND_BOTTOM_HALF_RL : mv_mode = GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM ;
 mv_flags = GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST ;
 break ;
 case GST_ASF_3D_DUAL_STREAM : {
 gboolean is_right_view = FALSE ;
 if ( demux -> mut_ex_streams != NULL ) {
 guint length ;
 gint i ;
 length = g_slist_length ( demux -> mut_ex_streams ) ;
 for ( i = 0 ;
 i < length ;
 i ++ ) {
 gpointer v_s_id ;
 v_s_id = g_slist_nth_data ( demux -> mut_ex_streams , i ) ;
 GST_DEBUG_OBJECT ( demux , "has Mutual_Exclusion object. stream id in object is %d" , GPOINTER_TO_INT ( v_s_id ) ) ;
 if ( id > GPOINTER_TO_INT ( v_s_id ) ) is_right_view = TRUE ;
 }
 }
 else {
 if ( demux -> num_video_streams > 0 ) {
 is_right_view = TRUE ;
 }
 }
 if ( is_right_view ) mv_mode = GST_VIDEO_MULTIVIEW_MODE_RIGHT ;
 else mv_mode = GST_VIDEO_MULTIVIEW_MODE_LEFT ;
 break ;
 }
 default : break ;
 }
 GST_INFO_OBJECT ( demux , "stream_id %d, has multiview-mode %d flags 0x%x" , id , mv_mode , ( guint ) mv_flags ) ;
 mview_mode_str = gst_video_multiview_mode_to_caps_string ( mv_mode ) ;
 if ( mview_mode_str != NULL ) {
 if ( gst_video_multiview_guess_half_aspect ( mv_mode , video -> width , video -> height , par_w , par_h ) ) mv_flags |= GST_VIDEO_MULTIVIEW_FLAGS_HALF_ASPECT ;
 gst_caps_set_simple ( caps , "multiview-mode" , G_TYPE_STRING , mview_mode_str , "multiview-flags" , GST_TYPE_VIDEO_MULTIVIEW_FLAGSET , mv_flags , GST_FLAG_SET_MASK_EXACT , NULL ) ;
 }
 }
 if ( codec_name ) {
 tags = gst_tag_list_new ( GST_TAG_VIDEO_CODEC , codec_name , NULL ) ;
 g_free ( codec_name ) ;
 }
 if ( extradata ) gst_buffer_unref ( extradata ) ;
 GST_INFO ( "Adding video stream #%u, id %u, codec %" GST_FOURCC_FORMAT " (0x%08x)" , demux -> num_video_streams , id , GST_FOURCC_ARGS ( video -> tag ) , video -> tag ) ;
 ++ demux -> num_video_streams ;
 return gst_asf_demux_setup_pad ( demux , src_pad , caps , id , TRUE , streamheader , tags ) ;
 }


target_ulong helper_rdhwr_ccres(CPUMIPSState *env) { check_hwrena(env, 3); return env->CCRes; }


Map1toN(SDL_PixelFormat * src, Uint8 Rmod, Uint8 Gmod, Uint8 Bmod, Uint8 Amod,
        SDL_PixelFormat * dst)
{
    Uint8 *map;
    int i;
    int bpp;
    SDL_Palette *pal = src->palette;

    bpp = ((dst->BytesPerPixel == 3) ? 4 : dst->BytesPerPixel);
    map = (Uint8 *) SDL_malloc(pal->ncolors * bpp);
    if (map == NULL) {
        SDL_OutOfMemory();
        return (NULL);
    }

    /* We memory copy to the pixel map so the endianness is preserved */
    for (i = 0; i < pal->ncolors; ++i) {
        Uint8 R = (Uint8) ((pal->colors[i].r * Rmod) / 255);
        Uint8 G = (Uint8) ((pal->colors[i].g * Gmod) / 255);
        Uint8 B = (Uint8) ((pal->colors[i].b * Bmod) / 255);
        Uint8 A = (Uint8) ((pal->colors[i].a * Amod) / 255);
        ASSEMBLE_RGBA(&map[i * bpp], dst->BytesPerPixel, dst, (Uint32)R, (Uint32)G, (Uint32)B, (Uint32)A);
    }
    return (map);
}


static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen)
{
	struct sock *sk = sock->sk;
	struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);
	struct nfc_llcp_local *local;
	struct nfc_dev *dev;
	struct sockaddr_nfc_llcp llcp_addr;
	int len, ret = 0;

	if (!addr || alen < offsetofend(struct sockaddr, sa_family) ||
	    addr->sa_family != AF_NFC)
		return -EINVAL;

	pr_debug("sk %p addr %p family %d\n", sk, addr, addr->sa_family);

	memset(&llcp_addr, 0, sizeof(llcp_addr));
	len = min_t(unsigned int, sizeof(llcp_addr), alen);
	memcpy(&llcp_addr, addr, len);

	/* This is going to be a listening socket, dsap must be 0 */
	if (llcp_addr.dsap != 0)
		return -EINVAL;

	lock_sock(sk);

	if (sk->sk_state != LLCP_CLOSED) {
		ret = -EBADFD;
		goto error;
	}

	dev = nfc_get_device(llcp_addr.dev_idx);
	if (dev == NULL) {
		ret = -ENODEV;
		goto error;
	}

	local = nfc_llcp_find_local(dev);
	if (local == NULL) {
		ret = -ENODEV;
		goto put_dev;
	}

	llcp_sock->dev = dev;
	llcp_sock->local = nfc_llcp_local_get(local);
	llcp_sock->nfc_protocol = llcp_addr.nfc_protocol;
	llcp_sock->service_name_len = min_t(unsigned int,
					    llcp_addr.service_name_len,
					    NFC_LLCP_MAX_SERVICE_NAME);
	llcp_sock->service_name = kmemdup(llcp_addr.service_name,
					  llcp_sock->service_name_len,
					  GFP_KERNEL);
	if (!llcp_sock->service_name) {
		nfc_llcp_local_put(llcp_sock->local);
		ret = -ENOMEM;
		goto put_dev;
	}
	llcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock);
	if (llcp_sock->ssap == LLCP_SAP_MAX) {
		nfc_llcp_local_put(llcp_sock->local);
		kfree(llcp_sock->service_name);
		llcp_sock->service_name = NULL;
		ret = -EADDRINUSE;
		goto put_dev;
	}

	llcp_sock->reserved_ssap = llcp_sock->ssap;

	nfc_llcp_sock_link(&local->sockets, sk);

	pr_debug("Socket bound to SAP %d\n", llcp_sock->ssap);

	sk->sk_state = LLCP_BOUND;

put_dev:
	nfc_put_device(dev);

error:
	release_sock(sk);
	return ret;
}


int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrBufLen, unsigned  char type,
                unsigned char decryptable, uint64_t* resultLen) {

    if (!type) {
        LOG_ERROR("Null type in AES_encrypt");
        return -1;
    }

    if (!message) {
        LOG_ERROR("Null message in AES_encrypt");
        return -1;
    }

    if (!encr_message) {
        LOG_ERROR("Null encr message in AES_encrypt");
        return -2;
    }

    uint64_t len = strlen(message) + 1;

    if (2 + len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE > encrBufLen ) {
        LOG_ERROR("Output buffer too small");
        return -3;
    }

    SAFE_CHAR_BUF(fullMessage, len + 2);

    fullMessage[0] = type;
    fullMessage[1] = decryptable;

    strncpy(fullMessage + 2, message, len );

    len = len + 2;
    message = fullMessage;

    sgx_read_rand(encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE);

    sgx_status_t status = sgx_rijndael128GCM_encrypt(&AES_key, (uint8_t*)message, len,
                                                     encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE,
                                                     encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE,
                                                     NULL, 0,
                                                     (sgx_aes_gcm_128bit_tag_t *) encr_message);

    *resultLen = len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;

    return status;
}


static void typhoon_pcihost_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); k->init = typhoon_pcihost_init; dc->no_user = 1; }


static inline void set_indic_properties ( hb_glyph_info_t & info ) {
 hb_codepoint_t u = info . codepoint ;
 unsigned int type = hb_indic_get_categories ( u ) ;
 indic_category_t cat = ( indic_category_t ) ( type & 0x7Fu ) ;
 indic_position_t pos = ( indic_position_t ) ( type >> 8 ) ;
 if ( unlikely ( hb_in_ranges ( u , 0x0951u , 0x0952u , 0x1CD0u , 0x1CD2u , 0x1CD4u , 0x1CE1u ) || u == 0x1CF4u ) ) cat = OT_A ;
 else if ( unlikely ( hb_in_range ( u , 0x0953u , 0x0954u ) ) ) cat = OT_SM ;
 else if ( unlikely ( hb_in_ranges ( u , 0x0A72u , 0x0A73u , 0x1CF5u , 0x1CF6u ) ) ) cat = OT_C ;
 else if ( unlikely ( hb_in_range ( u , 0x1CE2u , 0x1CE8u ) ) ) cat = OT_A ;
 else if ( unlikely ( u == 0x1CEDu ) ) cat = OT_A ;
 else if ( unlikely ( hb_in_ranges ( u , 0xA8F2u , 0xA8F7u , 0x1CE9u , 0x1CECu , 0x1CEEu , 0x1CF1u ) ) ) {
 cat = OT_Symbol ;
 ASSERT_STATIC ( ( int ) INDIC_SYLLABIC_CATEGORY_AVAGRAHA == OT_Symbol ) ;
 }
 else if ( unlikely ( hb_in_range ( u , 0x17CDu , 0x17D1u ) || u == 0x17CBu || u == 0x17D3u || u == 0x17DDu ) ) {
 cat = OT_M ;
 pos = POS_ABOVE_C ;
 }
 else if ( unlikely ( u == 0x17C6u ) ) cat = OT_N ;
 else if ( unlikely ( u == 0x17D2u ) ) cat = OT_Coeng ;
 else if ( unlikely ( hb_in_range ( u , 0x2010u , 0x2011u ) ) ) cat = OT_PLACEHOLDER ;
 else if ( unlikely ( u == 0x25CCu ) ) cat = OT_DOTTEDCIRCLE ;
 else if ( unlikely ( u == 0xA982u ) ) cat = OT_SM ;
 else if ( unlikely ( u == 0xA9BEu ) ) cat = OT_CM2 ;
 else if ( unlikely ( u == 0xA9BDu ) ) {
 cat = OT_M ;
 pos = POS_POST_C ;
 }
 if ( ( FLAG ( cat ) & CONSONANT_FLAGS ) ) {
 pos = POS_BASE_C ;
 if ( is_ra ( u ) ) cat = OT_Ra ;
 }
 else if ( cat == OT_M ) {
 pos = matra_position ( u , pos ) ;
 }
 else if ( ( FLAG ( cat ) & ( FLAG ( OT_SM ) | FLAG ( OT_VD ) | FLAG ( OT_A ) | FLAG ( OT_Symbol ) ) ) ) {
 pos = POS_SMVD ;
 }
 if ( unlikely ( u == 0x0B01u ) ) pos = POS_BEFORE_SUB ;
 info . indic_category ( ) = cat ;
 info . indic_position ( ) = pos ;
 }


static gboolean all_streams_prerolled ( GstASFDemux * demux ) {
 GstClockTime preroll_time ;
 guint i , num_no_data = 0 ;
 preroll_time = MAX ( demux -> preroll , 500 * GST_MSECOND ) ;
 for ( i = 0 ;
 i < demux -> num_streams ;
 ++ i ) {
 AsfPayload * last_payload = NULL ;
 AsfStream * stream ;
 gint last_idx ;
 stream = & demux -> stream [ i ] ;
 if ( G_UNLIKELY ( stream -> payloads -> len == 0 ) ) {
 ++ num_no_data ;
 GST_LOG_OBJECT ( stream -> pad , "no data queued" ) ;
 continue ;
 }
 for ( last_idx = stream -> payloads -> len - 1 ;
 last_idx >= 0 && ( last_payload == NULL || ! GST_CLOCK_TIME_IS_VALID ( last_payload -> ts ) ) ;
 -- last_idx ) {
 last_payload = & g_array_index ( stream -> payloads , AsfPayload , last_idx ) ;
 }
 GST_LOG_OBJECT ( stream -> pad , "checking if %" GST_TIME_FORMAT " > %" GST_TIME_FORMAT , GST_TIME_ARGS ( last_payload -> ts ) , GST_TIME_ARGS ( preroll_time ) ) ;
 if ( G_UNLIKELY ( ! GST_CLOCK_TIME_IS_VALID ( last_payload -> ts ) || last_payload -> ts <= preroll_time ) ) {
 GST_LOG_OBJECT ( stream -> pad , "not beyond preroll point yet" ) ;
 return FALSE ;
 }
 }
 if ( G_UNLIKELY ( num_no_data > 0 ) ) return FALSE ;
 return TRUE ;
 }


static int coroutine_fn sd_co_rw_vector(void *p) { SheepdogAIOCB *acb = p; int ret = 0; unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE; unsigned long idx = acb->sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE; uint64_t oid; uint64_t offset = (acb->sector_num * BDRV_SECTOR_SIZE) % SD_DATA_OBJ_SIZE; BDRVSheepdogState *s = acb->common.bs->opaque; SheepdogInode *inode = &s->inode; AIOReq *aio_req; if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) { /* * In the case we open the snapshot VDI, Sheepdog creates the * writable VDI when we do a write operation first. */ ret = sd_create_branch(s); if (ret) { acb->ret = -EIO; goto out; } } /* * Make sure we don't free the aiocb before we are done with all requests. * This additional reference is dropped at the end of this function. */ acb->nr_pending++; while (done != total) { uint8_t flags = 0; uint64_t old_oid = 0; bool create = false; oid = vid_to_data_oid(inode->data_vdi_id[idx], idx); len = MIN(total - done, SD_DATA_OBJ_SIZE - offset); switch (acb->aiocb_type) { case AIOCB_READ_UDATA: if (!inode->data_vdi_id[idx]) { qemu_iovec_memset(acb->qiov, done, 0, len); goto done; } break; case AIOCB_WRITE_UDATA: if (!inode->data_vdi_id[idx]) { create = true; } else if (!is_data_obj_writable(inode, idx)) { /* Copy-On-Write */ create = true; old_oid = oid; flags = SD_FLAG_CMD_COW; } break; case AIOCB_DISCARD_OBJ: /* * We discard the object only when the whole object is * 1) allocated 2) trimmed. Otherwise, simply skip it. */ if (len != SD_DATA_OBJ_SIZE || inode->data_vdi_id[idx] == 0) { goto done; } break; default: break; } if (create) { DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n", inode->vdi_id, oid, vid_to_data_oid(inode->data_vdi_id[idx], idx), idx); oid = vid_to_data_oid(inode->vdi_id, idx); DPRINTF("new oid %" PRIx64 "\n", oid); } aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done); if (create) { AIOReq *areq; QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) { if (areq->oid == oid) { /* * Sheepdog cannot handle simultaneous create * requests to the same object. So we cannot send * the request until the previous request * finishes. */ aio_req->flags = 0; aio_req->base_oid = 0; QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req, aio_siblings); goto done; } } } QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings); add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, create, acb->aiocb_type); done: offset = 0; idx++; done += len; } out: if (!--acb->nr_pending) { return acb->ret; } return 1; }


static qemu_irq *ppce500_init_mpic(MachineState *machine, PPCE500Params *params, MemoryRegion *ccsr, qemu_irq **irqs) { qemu_irq *mpic; DeviceState *dev = NULL; SysBusDevice *s; int i; mpic = g_new0(qemu_irq, 256); if (kvm_enabled()) { Error *err = NULL; if (machine_kernel_irqchip_allowed(machine)) { dev = ppce500_init_mpic_kvm(params, irqs, &err); } if (machine_kernel_irqchip_required(machine) && !dev) { error_reportf_err(err, "kernel_irqchip requested but unavailable: "); exit(1); } } if (!dev) { dev = ppce500_init_mpic_qemu(params, irqs); } for (i = 0; i < 256; i++) { mpic[i] = qdev_get_gpio_in(dev, i); } s = SYS_BUS_DEVICE(dev); memory_region_add_subregion(ccsr, MPC8544_MPIC_REGS_OFFSET, s->mmio[0].memory); return mpic; }


bool pyc_is_code(ut8 b, ut32 magic) {
	if ((magic == 0x00949494 || magic == 0x0099be2a || magic == 0x0099be3a || magic == 0x00999901) && (pyc_is_object ((b & ~FLAG_REF), TYPE_CODE_v0))) {
		//TYPE_CODE_V0 for Python < 1.0
		return true;
	}
	if (pyc_is_object ((b & ~FLAG_REF), TYPE_CODE_v1)) {
		return true;
	}
	return false;
}


static void do_subtitle_out(AVFormatContext *s, OutputStream *ost, InputStream *ist, AVSubtitle *sub, int64_t pts) { int subtitle_out_max_size = 1024 * 1024; int subtitle_out_size, nb, i; AVCodecContext *enc; AVPacket pkt; if (pts == AV_NOPTS_VALUE) { av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n"); if (exit_on_error) exit_program(1); return; } enc = ost->st->codec; if (!subtitle_out) { subtitle_out = av_malloc(subtitle_out_max_size); } /* Note: DVB subtitle need one packet to draw them and one other packet to clear them */ /* XXX: signal it in the codec context ? */ if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) nb = 2; else nb = 1; for (i = 0; i < nb; i++) { ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base); if (!check_recording_time(ost)) return; sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q); // start_display_time is required to be 0 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q); sub->end_display_time -= sub->start_display_time; sub->start_display_time = 0; subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out, subtitle_out_max_size, sub); if (subtitle_out_size < 0) { av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n"); exit_program(1); } av_init_packet(&pkt); pkt.data = subtitle_out; pkt.size = subtitle_out_size; pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base); pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base); if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) { /* XXX: the pts correction is handled here. Maybe handling it in the codec would be better */ if (i == 0) pkt.pts += 90 * sub->start_display_time; else pkt.pts += 90 * sub->end_display_time; } write_frame(s, &pkt, ost); subtitle_size += pkt.size; } }


void ff_build_rac_states(RangeCoder *c, int factor, int max_p){ const int64_t one= 1LL<<32; int64_t p; int last_p8, p8, i; memset(c->zero_state, 0, sizeof(c->zero_state)); memset(c-> one_state, 0, sizeof(c-> one_state)); #if 0 for(i=1; i<256; i++){ if(c->one_state[i]) continue; p= (i*one + 128) >> 8; last_p8= i; for(;;){ p+= ((one-p)*factor + one/2) >> 32; p8= (256*p + one/2) >> 32; //FIXME try without the one if(p8 <= last_p8) p8= last_p8+1; if(p8 > max_p) p8= max_p; if(p8 < last_p8) break; c->one_state[last_p8]= p8; if(p8 == last_p8) break; last_p8= p8; } } #endif #if 1 last_p8= 0; p= one/2; for(i=0; i<128; i++){ p8= (256*p + one/2) >> 32; //FIXME try without the one if(p8 <= last_p8) p8= last_p8+1; if(last_p8 && last_p8<256 && p8<=max_p) c->one_state[last_p8]= p8; p+= ((one-p)*factor + one/2) >> 32; last_p8= p8; } #endif for(i=256-max_p; i<=max_p; i++){ if(c->one_state[i]) continue; p= (i*one + 128) >> 8; p+= ((one-p)*factor + one/2) >> 32; p8= (256*p + one/2) >> 32; //FIXME try without the one if(p8 <= i) p8= i+1; if(p8 > max_p) p8= max_p; c->one_state[ i]= p8; } for(i=0; i<256; i++) c->zero_state[i]= 256-c->one_state[256-i]; #if 0 for(i=0; i<256; i++) av_log(NULL, AV_LOG_DEBUG, "%3d %3d\n", i, c->one_state[i]); #endif }


static int dissect_h245_V76Capability ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_V76Capability , V76Capability_sequence ) ;
 return offset ;
 }


trustedGenDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, uint64_t *enc_len, size_t _t) {
    LOG_INFO(__FUNCTION__);
    INIT_ERROR_STATE

    CHECK_STATE(encrypted_dkg_secret);

    SAFE_CHAR_BUF(dkg_secret, DKG_BUFER_LENGTH);

    int status = gen_dkg_poly(dkg_secret, _t);

    CHECK_STATUS("gen_dkg_poly failed")

    status = AES_encrypt(dkg_secret, encrypted_dkg_secret, 3 * BUF_LEN,
                         DKG, DECRYPTABLE, enc_len);

    CHECK_STATUS("SGX AES encrypt DKG poly failed");

    SAFE_CHAR_BUF(decr_dkg_secret, DKG_BUFER_LENGTH);

    status = AES_decrypt(encrypted_dkg_secret, *enc_len, decr_dkg_secret,
                         DKG_BUFER_LENGTH);

    CHECK_STATUS("aes decrypt dkg poly failed");

    if (strcmp(dkg_secret, decr_dkg_secret) != 0) {
        snprintf(errString, BUF_LEN,
                 "encrypted poly is not equal to decrypted poly");
        LOG_ERROR(errString);
        *errStatus = -333;
        goto clean;
    }

    SET_SUCCESS
    clean:
    ;
    LOG_INFO(__FUNCTION__ );
    LOG_INFO("SGX call completed");
}


void trustedGenerateEcdsaKeyAES(int *errStatus, char *errString,
                                uint8_t *encryptedPrivateKey, uint32_t *enc_len, char *pub_key_x, char *pub_key_y) {
    LOG_INFO(__FUNCTION__);
    INIT_ERROR_STATE

    CHECK_STATE(encryptedPrivateKey);
    CHECK_STATE(pub_key_x);
    CHECK_STATE(pub_key_y);

    RANDOM_CHAR_BUF(rand_char, 32);

    mpz_t seed;
    mpz_init(seed);
    mpz_t skey;
    mpz_init(skey);

    point Pkey = point_init();

    mpz_import(seed, 32, 1, sizeof(rand_char[0]), 0, 0, rand_char);

    mpz_mod(skey, seed, curve->p);

    signature_extract_public_key(Pkey, skey, curve);

    SAFE_CHAR_BUF(arr_x, BUF_LEN);
    mpz_get_str(arr_x, ECDSA_SKEY_BASE, Pkey->x);
    int n_zeroes = 64 - strlen(arr_x);
    for (int i = 0; i < n_zeroes; i++) {
        pub_key_x[i] = '0';
    }

    strncpy(pub_key_x + n_zeroes, arr_x, 1024 - n_zeroes);

    SAFE_CHAR_BUF(arr_y, BUF_LEN);
    mpz_get_str(arr_y, ECDSA_SKEY_BASE, Pkey->y);
    n_zeroes = 64 - strlen(arr_y);
    for (int i = 0; i < n_zeroes; i++) {
        pub_key_y[i] = '0';
    }
    strncpy(pub_key_y + n_zeroes, arr_y, 1024 - n_zeroes);

    SAFE_CHAR_BUF(skey_str, ECDSA_SKEY_LEN);SAFE_CHAR_BUF(arr_skey_str, mpz_sizeinbase(skey, ECDSA_SKEY_BASE) + 2);
    mpz_get_str(arr_skey_str, ECDSA_SKEY_BASE, skey);
    n_zeroes = 64 - strlen(arr_skey_str);
    for (int i = 0; i < n_zeroes; i++) {
        skey_str[i] = '0';
    }
    strncpy(skey_str + n_zeroes, arr_skey_str, 65 - n_zeroes);
    skey_str[ECDSA_SKEY_LEN - 1] = 0;
    snprintf(errString, BUF_LEN, "skey len is %d\n", (int) strlen(skey_str));

    int status = AES_encrypt((char *) skey_str, encryptedPrivateKey, BUF_LEN);
    CHECK_STATUS("ecdsa private key encryption failed");

    *enc_len = strlen(skey_str) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;

    status = AES_decrypt(encryptedPrivateKey, *enc_len, skey_str, ECDSA_SKEY_LEN);

    CHECK_STATUS2("ecdsa private key decr failed with status %d");

    SET_SUCCESS
    clean:
    mpz_clear(seed);
    mpz_clear(skey);
    point_clear(Pkey);
    LOG_INFO(__FUNCTION__ );
    LOG_INFO("SGX call completed");
}


void trustedGenerateSEK(int *errStatus, char *errString,
                        uint8_t *encrypted_sek, uint64_t *enc_len, char *sek_hex) {
    CALL_ONCE
    LOG_INFO(__FUNCTION__);
    INIT_ERROR_STATE

    CHECK_STATE(encrypted_sek);
    CHECK_STATE(sek_hex);

    RANDOM_CHAR_BUF(SEK_raw, SGX_AESGCM_KEY_SIZE);

    carray2Hex((uint8_t*) SEK_raw, SGX_AESGCM_KEY_SIZE, sek_hex);
    memcpy(AES_key, SEK_raw, SGX_AESGCM_KEY_SIZE);
    derive_DH_Key();

    sealHexSEK(errStatus, errString, encrypted_sek, enc_len, sek_hex);

    if (*errStatus != 0) {
        LOG_ERROR("sealHexSEK failed");
        goto clean;
    }

    SET_SUCCESS
    clean:
    LOG_INFO(__FUNCTION__ );
    LOG_INFO("SGX call completed");
}


XSetClassHint(
	Display *dpy,
	Window w,
	XClassHint *classhint)
{
	char *class_string;
	char *s;
	size_t len_nm, len_cl;

	len_nm = safestrlen(classhint->res_name);
	len_cl = safestrlen(classhint->res_class);
	if ((class_string = s = Xmalloc(len_nm + len_cl + 2))) {
	    if (len_nm) {
		strcpy(s, classhint->res_name);
		s += len_nm + 1;
	    }
	    else
		*s++ = '\0';
	    if (len_cl)
		strcpy(s, classhint->res_class);
	    else
		*s = '\0';
	    XChangeProperty(dpy, w, XA_WM_CLASS, XA_STRING, 8,
			    PropModeReplace, (unsigned char *) class_string,
			    len_nm+len_cl+2);
	    Xfree(class_string);
	}
	return 1;
}


static uint64_t unpack_timestamp(const struct efi_time *timestamp)
{
	uint64_t val = 0;
	uint16_t year = le16_to_cpu(timestamp->year);

	/* pad1, nanosecond, timezone, daylight and pad2 are meant to be zero */
	val |= ((uint64_t) timestamp->pad1 & 0xFF) << 0;
	val |= ((uint64_t) timestamp->second & 0xFF) << (1*8);
	val |= ((uint64_t) timestamp->minute & 0xFF) << (2*8);
	val |= ((uint64_t) timestamp->hour & 0xFF) << (3*8);
	val |= ((uint64_t) timestamp->day & 0xFF) << (4*8);
	val |= ((uint64_t) timestamp->month & 0xFF) << (5*8);
	val |= ((uint64_t) year) << (6*8);

	return val;
}


char **XListFontsWithInfo(
register Display *dpy,
_Xconst char *pattern,  /* null-terminated */
int maxNames,
int *actualCount,	/* RETURN */
XFontStruct **info)	/* RETURN */
{
    unsigned long nbytes;
    unsigned long reply_left;	/* unused data left in reply buffer */
    register int i;
    register XFontStruct *fs;
    unsigned int size = 0;
    XFontStruct *finfo = NULL;
    char **flist = NULL;
    xListFontsWithInfoReply reply;
    register xListFontsReq *req;
    int j;

    LockDisplay(dpy);
    GetReq(ListFontsWithInfo, req);
    req->maxNames = maxNames;
    nbytes = req->nbytes = pattern ? (CARD16) strlen (pattern) : 0;
    req->length += (nbytes + 3) >> 2;
    _XSend (dpy, pattern, nbytes);
    /* use _XSend instead of Data, since subsequent _XReply will flush buffer */

    for (i = 0; ; i++) {
	if (!_XReply (dpy, (xReply *) &reply,
		      ((SIZEOF(xListFontsWithInfoReply) -
			SIZEOF(xGenericReply)) >> 2), xFalse)) {
	    reply.nameLength = 0; /* avoid trying to read more replies */
	    reply_left = 0;
	    goto badmem;
	}
	reply_left = reply.length -
	    ((SIZEOF(xListFontsWithInfoReply) -	SIZEOF(xGenericReply)) >> 2);
	if (reply.nameLength == 0) {
	    _XEatDataWords(dpy, reply_left);
	    break;
	}
	if (reply.nReplies >= (INT_MAX - i)) /* avoid overflowing size */
	    goto badmem;
	if ((i + reply.nReplies) >= size) {
	    size = i + reply.nReplies + 1;

	    if (size >= (INT_MAX / sizeof(XFontStruct)))
		goto badmem;

	    if (finfo) {
		XFontStruct * tmp_finfo;
		char ** tmp_flist;

		tmp_finfo = Xreallocarray (finfo, size, sizeof(XFontStruct));
		if (tmp_finfo)
		    finfo = tmp_finfo;
		else
		    goto badmem;

		tmp_flist = Xreallocarray (flist, size + 1, sizeof(char *));
		if (tmp_flist)
		    flist = tmp_flist;
		else
		    goto badmem;
	    }
	    else {
		if (! (finfo = Xmallocarray(size, sizeof(XFontStruct))))
		    goto clearwire;
		if (! (flist = Xmallocarray(size + 1, sizeof(char *)))) {
		    Xfree(finfo);
		    goto clearwire;
		}
	    }
	}
	fs = &finfo[i];

	fs->ext_data 		= NULL;
	fs->per_char		= NULL;
	fs->fid 		= None;
	fs->direction 		= reply.drawDirection;
	fs->min_char_or_byte2	= reply.minCharOrByte2;
	fs->max_char_or_byte2 	= reply.maxCharOrByte2;
	fs->min_byte1 		= reply.minByte1;
	fs->max_byte1 		= reply.maxByte1;
	fs->default_char	= reply.defaultChar;
	fs->all_chars_exist 	= reply.allCharsExist;
	fs->ascent 		= cvtINT16toInt (reply.fontAscent);
	fs->descent 		= cvtINT16toInt (reply.fontDescent);

	/* XXX the next two statements won't work if short isn't 16 bits */
	fs->min_bounds = * (XCharStruct *) &reply.minBounds;
	fs->max_bounds = * (XCharStruct *) &reply.maxBounds;

	fs->n_properties = reply.nFontProps;
	fs->properties = NULL;
	if (fs->n_properties > 0) {
	    /* nFontProps is a CARD16 */
	    nbytes = reply.nFontProps * SIZEOF(xFontProp);
	    if ((nbytes >> 2) <= reply_left) {
		fs->properties = Xmallocarray (reply.nFontProps,
                                               sizeof(XFontProp));
	    }
	    if (! fs->properties)
		goto badmem;
	    _XRead32 (dpy, (long *)fs->properties, nbytes);
	    reply_left -= (nbytes >> 2);
	}

	/* nameLength is a CARD8 */
	nbytes = reply.nameLength + 1;
	if (!i)
	    nbytes++; /* make first string 1 byte longer, to match XListFonts */
	flist[i] = Xmalloc (nbytes);
	if (! flist[i]) {
	    if (finfo[i].properties) Xfree(finfo[i].properties);
	    goto badmem;
	}
	if (!i) {
	    *flist[0] = 0; /* zero to distinguish from XListFonts */
	    flist[0]++;
	}
	flist[i][reply.nameLength] = '\0';
	_XReadPad (dpy, flist[i], (long) reply.nameLength);
    }
    *info = finfo;
    *actualCount = i;
    if (flist)
	flist[i] = NULL; /* required in case XFreeFontNames is called */
    UnlockDisplay(dpy);
    SyncHandle();
    return (flist);

  badmem:
    /* Free all memory allocated by this function. */
    for (j=(i-1); (j >= 0); j--) {
        if (j == 0)
            flist[j]--;         /* was incremented above */
        Xfree(flist[j]);
        if (finfo[j].properties) Xfree(finfo[j].properties);
    }
    Xfree(flist);
    Xfree(finfo);

  clearwire:
    /* Clear the wire. */
    _XEatDataWords(dpy, reply_left);
    while ((reply.nameLength != 0) &&
	   _XReply(dpy, (xReply *) &reply,
		   ((SIZEOF(xListFontsWithInfoReply) - SIZEOF(xGenericReply))
		    >> 2), xTrue));
    UnlockDisplay(dpy);
    SyncHandle();
    *info = NULL;
    *actualCount = 0;
    return (char **) NULL;
}


void bdrv_init_with_whitelist(void) { use_bdrv_whitelist = 1; bdrv_init(); }


Mgr::QueryParams::ParseParam(const String& paramStr, Param& param)
{
    bool parsed = false;
    regmatch_t pmatch[3];
    regex_t intExpr;
    regcomp(&intExpr, "^([a-z][a-z0-9_]*)=([0-9]+((,[0-9]+))*)$", REG_EXTENDED | REG_ICASE);
    regex_t stringExpr;
    regcomp(&stringExpr, "^([a-z][a-z0-9_]*)=([^&= ]+)$", REG_EXTENDED | REG_ICASE);
    if (regexec(&intExpr, paramStr.termedBuf(), 3, pmatch, 0) == 0) {
        param.first = paramStr.substr(pmatch[1].rm_so, pmatch[1].rm_eo);
        std::vector<int> array;
        int n = pmatch[2].rm_so;
        for (int i = n; i < pmatch[2].rm_eo; ++i) {
            if (paramStr[i] == ',') {
                array.push_back(atoi(paramStr.substr(n, i).termedBuf()));
                n = i + 1;
            }
        }
        if (n < pmatch[2].rm_eo)
            array.push_back(atoi(paramStr.substr(n, pmatch[2].rm_eo).termedBuf()));
        param.second = new IntParam(array);
        parsed = true;
    } else if (regexec(&stringExpr, paramStr.termedBuf(), 3, pmatch, 0) == 0) {
        param.first = paramStr.substr(pmatch[1].rm_so, pmatch[1].rm_eo);
        param.second = new StringParam(paramStr.substr(pmatch[2].rm_so, pmatch[2].rm_eo));
        parsed = true;
    }
    regfree(&stringExpr);
    regfree(&intExpr);
    return parsed;
}


static void gen_cas_asi(DisasContext *dc, TCGv addr, TCGv val2, int insn, int rd) { TCGv val1 = gen_load_gpr(dc, rd); TCGv dst = gen_dest_gpr(dc, rd); TCGv_i32 r_asi = gen_get_asi(dc, insn); gen_helper_cas_asi(dst, cpu_env, addr, val1, val2, r_asi); tcg_temp_free_i32(r_asi); gen_store_gpr(dc, rd, dst); }


CacheManager::start(const Comm::ConnectionPointer &client, HttpRequest *request, StoreEntry *entry, const AccessLogEntry::Pointer &ale)
{
    debugs(16, 3, "CacheManager::Start: '" << entry->url() << "'" );

    Mgr::Command::Pointer cmd = ParseUrl(entry->url());
    if (!cmd) {
        const auto err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request, ale);
        err->url = xstrdup(entry->url());
        errorAppendEntry(entry, err);
        entry->expires = squid_curtime;
        return;
    }

    const char *actionName = cmd->profile->name;

    entry->expires = squid_curtime;

    debugs(16, 5, "CacheManager: " << client << " requesting '" << actionName << "'");

    /* get additional info from request headers */
    ParseHeaders(request, cmd->params);

    const char *userName = cmd->params.userName.size() ?
                           cmd->params.userName.termedBuf() : "unknown";

    /* Check password */

    if (CheckPassword(*cmd) != 0) {
        /* build error message */
        ErrorState errState(ERR_CACHE_MGR_ACCESS_DENIED, Http::scUnauthorized, request, ale);
        /* warn if user specified incorrect password */

        if (cmd->params.password.size()) {
            debugs(16, DBG_IMPORTANT, "CacheManager: " <<
                   userName << "@" <<
                   client << ": incorrect password for '" <<
                   actionName << "'" );
        } else {
            debugs(16, DBG_IMPORTANT, "CacheManager: " <<
                   userName << "@" <<
                   client << ": password needed for '" <<
                   actionName << "'" );
        }

        HttpReply *rep = errState.BuildHttpReply();

#if HAVE_AUTH_MODULE_BASIC
        /*
         * add Authenticate header using action name as a realm because
         * password depends on the action
         */
        rep->header.putAuth("Basic", actionName);
#endif
        // Allow cachemgr and other XHR scripts access to our version string
        if (request->header.has(Http::HdrType::ORIGIN)) {
            rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
#if HAVE_AUTH_MODULE_BASIC
            rep->header.putExt("Access-Control-Allow-Credentials","true");
#endif
            rep->header.putExt("Access-Control-Expose-Headers","Server");
        }

        /* store the reply */
        entry->replaceHttpReply(rep);

        entry->expires = squid_curtime;

        entry->complete();

        return;
    }

    if (request->header.has(Http::HdrType::ORIGIN)) {
        cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);
    }

    debugs(16, 2, "CacheManager: " <<
           userName << "@" <<
           client << " requesting '" <<
           actionName << "'" );

    // special case: /squid-internal-mgr/ index page
    if (!strcmp(cmd->profile->name, "index")) {
        ErrorState err(MGR_INDEX, Http::scOkay, request, ale);
        err.url = xstrdup(entry->url());
        HttpReply *rep = err.BuildHttpReply();
        if (strncmp(rep->body.content(),"Internal Error:", 15) == 0)
            rep->sline.set(Http::ProtocolVersion(1,1), Http::scNotFound);
        // Allow cachemgr and other XHR scripts access to our version string
        if (request->header.has(Http::HdrType::ORIGIN)) {
            rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
#if HAVE_AUTH_MODULE_BASIC
            rep->header.putExt("Access-Control-Allow-Credentials","true");
#endif
            rep->header.putExt("Access-Control-Expose-Headers","Server");
        }
        entry->replaceHttpReply(rep);
        entry->complete();
        return;
    }

    if (UsingSmp() && IamWorkerProcess()) {
        // is client the right connection to pass here?
        AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry, ale));
        return;
    }

    Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
    Must(action != NULL);
    action->run(entry, true);
}


void pimv1_print ( netdissect_options * ndo , register const u_char * bp , register u_int len ) {
 register const u_char * ep ;
 register u_char type ;
 ep = ( const u_char * ) ndo -> ndo_snapend ;
 if ( bp >= ep ) return ;
 ND_TCHECK ( bp [ 1 ] ) ;
 type = bp [ 1 ] ;
 ND_PRINT ( ( ndo , " %s" , tok2str ( pimv1_type_str , "[type %u]" , type ) ) ) ;
 switch ( type ) {
 case PIMV1_TYPE_QUERY : if ( ND_TTEST ( bp [ 8 ] ) ) {
 switch ( bp [ 8 ] >> 4 ) {
 case 0 : ND_PRINT ( ( ndo , " Dense-mode" ) ) ;
 break ;
 case 1 : ND_PRINT ( ( ndo , " Sparse-mode" ) ) ;
 break ;
 case 2 : ND_PRINT ( ( ndo , " Sparse-Dense-mode" ) ) ;
 break ;
 default : ND_PRINT ( ( ndo , " mode-%d" , bp [ 8 ] >> 4 ) ) ;
 break ;
 }
 }
 if ( ndo -> ndo_vflag ) {
 ND_TCHECK2 ( bp [ 10 ] , 2 ) ;
 ND_PRINT ( ( ndo , " (Hold-time " ) ) ;
 unsigned_relts_print ( ndo , EXTRACT_16BITS ( & bp [ 10 ] ) ) ;
 ND_PRINT ( ( ndo , ")" ) ) ;
 }
 break ;
 case PIMV1_TYPE_REGISTER : ND_TCHECK2 ( bp [ 8 ] , 20 ) ;
 ND_PRINT ( ( ndo , " for %s > %s" , ipaddr_string ( ndo , & bp [ 20 ] ) , ipaddr_string ( ndo , & bp [ 24 ] ) ) ) ;
 break ;
 case PIMV1_TYPE_REGISTER_STOP : ND_TCHECK2 ( bp [ 12 ] , sizeof ( struct in_addr ) ) ;
 ND_PRINT ( ( ndo , " for %s > %s" , ipaddr_string ( ndo , & bp [ 8 ] ) , ipaddr_string ( ndo , & bp [ 12 ] ) ) ) ;
 break ;
 case PIMV1_TYPE_RP_REACHABILITY : if ( ndo -> ndo_vflag ) {
 ND_TCHECK2 ( bp [ 22 ] , 2 ) ;
 ND_PRINT ( ( ndo , " group %s" , ipaddr_string ( ndo , & bp [ 8 ] ) ) ) ;
 if ( EXTRACT_32BITS ( & bp [ 12 ] ) != 0xffffffff ) ND_PRINT ( ( ndo , "/%s" , ipaddr_string ( ndo , & bp [ 12 ] ) ) ) ;
 ND_PRINT ( ( ndo , " RP %s hold " , ipaddr_string ( ndo , & bp [ 16 ] ) ) ) ;
 unsigned_relts_print ( ndo , EXTRACT_16BITS ( & bp [ 22 ] ) ) ;
 }
 break ;
 case PIMV1_TYPE_ASSERT : ND_TCHECK2 ( bp [ 16 ] , sizeof ( struct in_addr ) ) ;
 ND_PRINT ( ( ndo , " for %s > %s" , ipaddr_string ( ndo , & bp [ 16 ] ) , ipaddr_string ( ndo , & bp [ 8 ] ) ) ) ;
 if ( EXTRACT_32BITS ( & bp [ 12 ] ) != 0xffffffff ) ND_PRINT ( ( ndo , "/%s" , ipaddr_string ( ndo , & bp [ 12 ] ) ) ) ;
 ND_TCHECK2 ( bp [ 24 ] , 4 ) ;
 ND_PRINT ( ( ndo , " %s pref %d metric %d" , ( bp [ 20 ] & 0x80 ) ? "RP-tree" : "SPT" , EXTRACT_32BITS ( & bp [ 20 ] ) & 0x7fffffff , EXTRACT_32BITS ( & bp [ 24 ] ) ) ) ;
 break ;
 case PIMV1_TYPE_JOIN_PRUNE : case PIMV1_TYPE_GRAFT : case PIMV1_TYPE_GRAFT_ACK : if ( ndo -> ndo_vflag ) pimv1_join_prune_print ( ndo , & bp [ 8 ] , len - 8 ) ;
 break ;
 }
 if ( ( bp [ 4 ] >> 4 ) != 1 ) ND_PRINT ( ( ndo , " [v%d]" , bp [ 4 ] >> 4 ) ) ;
 return ;
 trunc : ND_PRINT ( ( ndo , "[|pim]" ) ) ;
 return ;
 }


int net_init_hubport(const NetClientOptions *opts, const char *name, NetClientState *peer, Error **errp) { const NetdevHubPortOptions *hubport; assert(opts->type == NET_CLIENT_OPTIONS_KIND_HUBPORT); assert(!peer); hubport = opts->u.hubport; net_hub_add_port(hubport->hubid, name); return 0; }


ClientHttpRequest::mRangeCLen()
{
    int64_t clen = 0;
    MemBuf mb;

    assert(memObject());

    mb.init();
    HttpHdrRange::iterator pos = request->range->begin();

    while (pos != request->range->end()) {
        /* account for headers for this range */
        mb.reset();
        clientPackRangeHdr(&storeEntry()->mem().freshestReply(),
                           *pos, range_iter.boundary, &mb);
        clen += mb.size;

        /* account for range content */
        clen += (*pos)->length;

        debugs(33, 6, "clientMRangeCLen: (clen += " << mb.size << " + " << (*pos)->length << ") == " << clen);
        ++pos;
    }

    /* account for the terminating boundary */
    mb.reset();

    clientPackTermBound(range_iter.boundary, &mb);

    clen += mb.size;

    mb.clean();

    return clen;
}


ClientHttpRequest::mRangeCLen()
{
    int64_t clen = 0;
    MemBuf mb;

    assert(memObject());

    mb.init();
    HttpHdrRange::iterator pos = request->range->begin();

    while (pos != request->range->end()) {
        /* account for headers for this range */
        mb.reset();
        clientPackRangeHdr(memObject()->getReply(),
                           *pos, range_iter.boundary, &mb);
        clen += mb.size;

        /* account for range content */
        clen += (*pos)->length;

        debugs(33, 6, "clientMRangeCLen: (clen += " << mb.size << " + " << (*pos)->length << ") == " << clen);
        ++pos;
    }

    /* account for the terminating boundary */
    mb.reset();

    clientPackTermBound(range_iter.boundary, &mb);

    clen += mb.size;

    mb.clean();

    return clen;
}


DEFINE_TEST ( test_read_format_mtree_nomagic_v1_form ) {
 const char reffile [ ] = "test_read_format_mtree_nomagic.mtree" ;
 char buff [ 16 ] ;
 struct archive_entry * ae ;
 struct archive * a ;
 FILE * f ;
 extract_reference_file ( reffile ) ;
 assert ( ( a = archive_read_new ( ) ) != NULL ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_support_filter_all ( a ) ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_support_format_all ( a ) ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_set_options ( a , "mtree:checkfs" ) ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_open_filename ( a , reffile , 11 ) ) ;
 f = fopen ( "file" , "wb" ) ;
 assert ( f != NULL ) ;
 assertEqualInt ( 3 , fwrite ( "hi\n" , 1 , 3 , f ) ) ;
 fclose ( f ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualInt ( archive_format ( a ) , ARCHIVE_FORMAT_MTREE ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "file" ) ;
 assertEqualInt ( archive_entry_uid ( ae ) , 18 ) ;
 assertEqualInt ( AE_IFREG , archive_entry_filetype ( ae ) ) ;
 assertEqualInt ( archive_entry_mode ( ae ) , AE_IFREG | 0123 ) ;
 assertEqualInt ( archive_entry_size ( ae ) , 3 ) ;
 assertEqualInt ( 3 , archive_read_data ( a , buff , 3 ) ) ;
 assertEqualMem ( buff , "hi\n" , 3 ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir" ) ;
 assertEqualInt ( AE_IFDIR , archive_entry_filetype ( ae ) ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir/file with space" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "file with space" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir2" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir2/dir3a" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir2/dir3a/indir3a" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir2/fullindir2" ) ;
 assertEqualInt ( archive_entry_mode ( ae ) , AE_IFREG | 0644 ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir2/indir2" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir2/dir3b" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "dir2/dir3b/indir3b" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_OK , archive_read_next_header ( a , & ae ) ) ;
 assertEqualString ( archive_entry_pathname ( ae ) , "notindir" ) ;
 assertEqualInt ( archive_entry_is_encrypted ( ae ) , 0 ) ;
 assertEqualIntA ( a , archive_read_has_encrypted_entries ( a ) , ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED ) ;
 assertEqualIntA ( a , ARCHIVE_EOF , archive_read_next_header ( a , & ae ) ) ;
 assertEqualInt ( 12 , archive_file_count ( a ) ) ;
 assertEqualInt ( ARCHIVE_OK , archive_read_close ( a ) ) ;
 assertEqualInt ( ARCHIVE_OK , archive_read_free ( a ) ) ;
 }