CloudInitSetup(const char *tmpDirPath)
{
   int deployStatus = DEPLOY_ERROR;
   const char *cloudInitTmpDirPath = "/var/run/vmware-imc";
   int forkExecResult;
   char command[1024];
   Bool cloudInitTmpDirCreated = FALSE;

   snprintf(command, sizeof(command),
            "/bin/mkdir -p %s", cloudInitTmpDirPath);
   command[sizeof(command) - 1] = '\0';

   forkExecResult = ForkExecAndWaitCommand(command);
   if (forkExecResult != 0) {
      SetDeployError("Error creating %s dir: %s",
                     cloudInitTmpDirPath,
                     strerror(errno));
      goto done;
   }

   cloudInitTmpDirCreated = TRUE;

   snprintf(command, sizeof(command),
            "/bin/rm -f %s/cust.cfg %s/nics.txt",
            cloudInitTmpDirPath, cloudInitTmpDirPath);
   command[sizeof(command) - 1] = '\0';

   forkExecResult = ForkExecAndWaitCommand(command);

   snprintf(command, sizeof(command),
            "/bin/cp %s/cust.cfg %s/cust.cfg",
            tmpDirPath, cloudInitTmpDirPath);
   command[sizeof(command) - 1] = '\0';

   forkExecResult = ForkExecAndWaitCommand(command);

   if (forkExecResult != 0) {
      SetDeployError("Error copying cust.cfg file: %s",
                     strerror(errno));
      goto done;
   }

   snprintf(command, sizeof(command),
            "/usr/bin/test -f %s/nics.txt", tmpDirPath);
   command[sizeof(command) - 1] = '\0';

   forkExecResult = ForkExecAndWaitCommand(command);

   /*
    * /usr/bin/test -f returns 0 if the file exists
    * non zero is returned if the file does not exist.
    * We need to copy the nics.txt only if it exists.
    */
   if (forkExecResult == 0) {
      snprintf(command, sizeof(command),
               "/bin/cp %s/nics.txt %s/nics.txt",
               tmpDirPath, cloudInitTmpDirPath);
      command[sizeof(command) - 1] = '\0';

      forkExecResult = ForkExecAndWaitCommand(command);
      if (forkExecResult != 0) {
         SetDeployError("Error copying nics.txt file: %s",
                        strerror(errno));
         goto done;
      }
   }

   deployStatus = DEPLOY_SUCCESS;

done:
   if (DEPLOY_SUCCESS == deployStatus) {
      TransitionState(INPROGRESS, DONE);
   } else {
      if (cloudInitTmpDirCreated) {
         snprintf(command, sizeof(command),
                  "/bin/rm -rf %s",
                  cloudInitTmpDirPath);
         command[sizeof(command) - 1] = '\0';
         ForkExecAndWaitCommand(command);
      }
      sLog(log_error, "Setting generic error status in vmx. \n");
      SetCustomizationStatusInVmx(TOOLSDEPLOYPKG_RUNNING,
                                  GUESTCUST_EVENT_CUSTOMIZE_FAILED,
                                  NULL);
      TransitionState(INPROGRESS, ERRORED);
   }

   return deployStatus;
}


static int nvdimm_plugged_device_list(Object *obj, void *opaque) { GSList **list = opaque; if (object_dynamic_cast(obj, TYPE_NVDIMM)) { *list = g_slist_append(*list, DEVICE(obj)); } object_child_foreach(obj, nvdimm_plugged_device_list, opaque); return 0; }


mbfl_string * mbfl_buffer_converter_result ( mbfl_buffer_converter * convd , mbfl_string * result ) {
 if ( convd == NULL || result == NULL ) {
 return NULL ;
 }
 result -> no_encoding = convd -> to -> no_encoding ;
 return mbfl_memory_device_result ( & convd -> device , result ) ;
 }


static int ieee80211_fragment(struct ieee80211_tx_data *tx,
			      struct sk_buff *skb, int hdrlen,
			      int frag_threshold)
{
	struct ieee80211_local *local = tx->local;
	struct ieee80211_tx_info *info;
	struct sk_buff *tmp;
	int per_fragm = frag_threshold - hdrlen - FCS_LEN;
	int pos = hdrlen + per_fragm;
	int rem = skb->len - hdrlen - per_fragm;

	if (WARN_ON(rem < 0))
		return -EINVAL;

	/* first fragment was already added to queue by caller */

	while (rem) {
		int fraglen = per_fragm;

		if (fraglen > rem)
			fraglen = rem;
		rem -= fraglen;
		tmp = dev_alloc_skb(local->tx_headroom +
				    frag_threshold +
				    tx->sdata->encrypt_headroom +
				    IEEE80211_ENCRYPT_TAILROOM);
		if (!tmp)
			return -ENOMEM;

		__skb_queue_tail(&tx->skbs, tmp);

		skb_reserve(tmp,
			    local->tx_headroom + tx->sdata->encrypt_headroom);

		/* copy control information */
		memcpy(tmp->cb, skb->cb, sizeof(tmp->cb));

		info = IEEE80211_SKB_CB(tmp);
		info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT |
				 IEEE80211_TX_CTL_FIRST_FRAGMENT);

		if (rem)
			info->flags |= IEEE80211_TX_CTL_MORE_FRAMES;

		skb_copy_queue_mapping(tmp, skb);
		tmp->priority = skb->priority;
		tmp->dev = skb->dev;

		/* copy header and data */
		memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen);
		memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen);

		pos += fraglen;
	}

	/* adjust first fragment's length */
	skb->len = hdrlen + per_fragm;
	return 0;
}


PackLinuxElf32::invert_pt_dynamic(Elf32_Dyn const *dynp)
{
    if (dt_table[Elf32_Dyn::DT_NULL]) {
        return;  // not 1st time; do not change upx_dt_init
    }
    Elf32_Dyn const *const dynp0 = dynp;
    unsigned ndx = 1+ 0;
    if (dynp)
    for (; ; ++ndx, ++dynp) {
        unsigned const d_tag = get_te32(&dynp->d_tag);
        if (d_tag < DT_NUM) {
            if (Elf32_Dyn::DT_NEEDED != d_tag
            &&  dt_table[d_tag]
            &&    get_te32(&dynp->d_val)
               != get_te32(&dynp0[-1+ dt_table[d_tag]].d_val)) {
                char msg[50]; snprintf(msg, sizeof(msg),
                    "duplicate DT_%#x: [%#x] [%#x]",
                    d_tag, -1+ dt_table[d_tag], -1+ ndx);
                throwCantPack(msg);
            }
            dt_table[d_tag] = ndx;
        }
        if (Elf32_Dyn::DT_NULL == d_tag) {
            break;  // check here so that dt_table[DT_NULL] is set
        }
    }
    upx_dt_init = 0;
         if (dt_table[Elf32_Dyn::DT_INIT])          upx_dt_init = Elf32_Dyn::DT_INIT;
    else if (dt_table[Elf32_Dyn::DT_PREINIT_ARRAY]) upx_dt_init = Elf32_Dyn::DT_PREINIT_ARRAY;
    else if (dt_table[Elf32_Dyn::DT_INIT_ARRAY])    upx_dt_init = Elf32_Dyn::DT_INIT_ARRAY;

    unsigned const z_str = dt_table[Elf32_Dyn::DT_STRSZ];
    if (z_str) {
        strtab_end = get_te32(&dynp0[-1+ z_str].d_val);
        if ((u32_t)file_size <= strtab_end) { // FIXME: weak
            char msg[50]; snprintf(msg, sizeof(msg),
                "bad DT_STRSZ %#x", strtab_end);
            throwCantPack(msg);
        }
    }
    unsigned const x_sym = dt_table[Elf32_Dyn::DT_SYMTAB];
    unsigned const x_str = dt_table[Elf32_Dyn::DT_STRTAB];
    if (x_sym && x_str) {
        upx_uint32_t const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);
        upx_uint32_t const v_str = get_te32(&dynp0[-1+ x_str].d_val);
        unsigned const  z_sym = dt_table[Elf32_Dyn::DT_SYMENT];
        unsigned const sz_sym = !z_sym ? sizeof(Elf32_Sym)
            : get_te32(&dynp0[-1+ z_sym].d_val);
        if (sz_sym < sizeof(Elf32_Sym)) {
            char msg[50]; snprintf(msg, sizeof(msg),
                "bad DT_SYMENT %x", sz_sym);
            throwCantPack(msg);
        }
        if (v_sym < v_str) {
            symnum_end = (v_str - v_sym) / sz_sym;
        }
        if (symnum_end < 1) {
            throwCantPack("bad DT_SYMTAB");
        }
    }
    // DT_HASH often ends at DT_SYMTAB
    unsigned const v_hsh = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH);
    if (v_hsh && file_image) {
        hashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_HASH);
        if (!hashtab) {
            char msg[40]; snprintf(msg, sizeof(msg),
               "bad DT_HASH %#x", v_hsh);
            throwCantPack(msg);
        }
        unsigned const nbucket = get_te32(&hashtab[0]);
        unsigned const *const buckets = &hashtab[2];
        unsigned const *const chains = &buckets[nbucket]; (void)chains;

        unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);
        if (!nbucket
        || (nbucket>>31) || (file_size/sizeof(unsigned)) <= (2*nbucket)  // FIXME: weak
        || ((v_hsh < v_sym) && (v_sym - v_hsh) < (sizeof(unsigned)*2  // headers
                + sizeof(*buckets)*nbucket  // buckets
                + sizeof(*chains) *nbucket  // chains
           ))
        ) {
            char msg[90]; snprintf(msg, sizeof(msg),
                "bad DT_HASH nbucket=%#x  len=%#x",
                nbucket, (v_sym - v_hsh));
            throwCantPack(msg);
        }
    }
    // DT_GNU_HASH often ends at DT_SYMTAB;  FIXME: not for Android?
    unsigned const v_gsh = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH);
    if (v_gsh && file_image) {
        gashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_GNU_HASH);
        if (!gashtab) {
            char msg[40]; snprintf(msg, sizeof(msg),
               "bad DT_GNU_HASH %#x", v_gsh);
            throwCantPack(msg);
        }
        unsigned const n_bucket = get_te32(&gashtab[0]);
        unsigned const n_bitmask = get_te32(&gashtab[2]);
        unsigned const gnu_shift = get_te32(&gashtab[3]);
        unsigned const *const bitmask = (unsigned const *)(void const *)&gashtab[4];
        unsigned     const *const buckets = (unsigned const *)&bitmask[n_bitmask];
        unsigned     const *const hasharr = &buckets[n_bucket]; (void)hasharr;
      //unsigned     const *const gashend = &hasharr[n_bucket];  // minimum

        unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);
        if (!n_bucket || !n_bitmask
        || (-1+ n_bitmask) & n_bitmask  // not a power of 2
        || 8*sizeof(unsigned) <= gnu_shift  // shifted result always == 0
        || (n_bucket>>30)  // fie on fuzzers
        || (n_bitmask>>30)
        || (file_size / sizeof(unsigned)) <= (n_bitmask + 2*n_bucket)  // FIXME: weak
        // FIXME: next test does work for Android?
        || ((v_gsh < v_sym) && (v_sym - v_gsh) < (sizeof(unsigned)*4  // headers
                + sizeof(*bitmask)*n_bitmask  // bitmask
                + sizeof(*buckets)*n_bucket  // buckets
                + sizeof(*hasharr)*n_bucket  // hasharr
            ))
        ) {
            char msg[90]; snprintf(msg, sizeof(msg),
                "bad DT_GNU_HASH n_bucket=%#x  n_bitmask=%#x  len=%#x",
                n_bucket, n_bitmask, v_sym - v_gsh);
            throwCantPack(msg);
        }
    }
    unsigned const e_shstrndx = get_te16(&ehdri.e_shstrndx);
    if (e_shnum <= e_shstrndx
    &&  !(0==e_shnum && 0==e_shstrndx) ) {
        char msg[40]; snprintf(msg, sizeof(msg),
            "bad .e_shstrndx %d >= .e_shnum %d", e_shstrndx, e_shnum);
        throwCantPack(msg);
    }
}


jas_stream_t *jas_stream_memopen(char *buf, int bufsize)
{
	jas_stream_t *stream;
	jas_stream_memobj_t *obj;

	JAS_DBGLOG(100, ("jas_stream_memopen(%p, %d)\n", buf, bufsize));

	if (!(stream = jas_stream_create())) {
		return 0;
	}

	/* A stream associated with a memory buffer is always opened
	for both reading and writing in binary mode. */
	stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY;

	/* Since the stream data is already resident in memory, buffering
	is not necessary. */
	/* But... It still may be faster to use buffering anyways. */
	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);

	/* Select the operations for a memory stream. */
	stream->ops_ = &jas_stream_memops;

	/* Allocate memory for the underlying memory stream object. */
	if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) {
		jas_stream_destroy(stream);
		return 0;
	}
	stream->obj_ = (void *) obj;

	/* Initialize a few important members of the memory stream object. */
	obj->myalloc_ = 0;
	obj->buf_ = 0;

	/* If the buffer size specified is nonpositive, then the buffer
	is allocated internally and automatically grown as needed. */
	if (bufsize <= 0) {
		obj->bufsize_ = 1024;
		obj->growable_ = 1;
	} else {
		obj->bufsize_ = bufsize;
		obj->growable_ = 0;
	}
	if (buf) {
		obj->buf_ = (unsigned char *) buf;
	} else {
		obj->buf_ = jas_malloc(obj->bufsize_);
		obj->myalloc_ = 1;
	}
	if (!obj->buf_) {
		jas_stream_close(stream);
		return 0;
	}
	JAS_DBGLOG(100, ("jas_stream_memopen buffer buf=%p myalloc=%d\n",
	  obj->buf_, obj->myalloc_));

	if (bufsize > 0 && buf) {
		/* If a buffer was supplied by the caller and its length is positive,
		  make the associated buffer data appear in the stream initially. */
		obj->len_ = bufsize;
	} else {
		/* The stream is initially empty. */
		obj->len_ = 0;
	}
	obj->pos_ = 0;

	return stream;
}


cifs_iovec_write(struct file *file, const struct iovec *iov,
		 unsigned long nr_segs, loff_t *poffset)
{
	unsigned long nr_pages, i;
	size_t copied, len, cur_len;
	ssize_t total_written = 0;
	loff_t offset;
	struct iov_iter it;
	struct cifsFileInfo *open_file;
	struct cifs_tcon *tcon;
	struct cifs_sb_info *cifs_sb;
	struct cifs_writedata *wdata, *tmp;
	struct list_head wdata_list;
	int rc;
	pid_t pid;

	len = iov_length(iov, nr_segs);
	if (!len)
		return 0;

	rc = generic_write_checks(file, poffset, &len, 0);
	if (rc)
		return rc;

	INIT_LIST_HEAD(&wdata_list);
	cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
	open_file = file->private_data;
	tcon = tlink_tcon(open_file->tlink);

	if (!tcon->ses->server->ops->async_writev)
		return -ENOSYS;

	offset = *poffset;

	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RWPIDFORWARD)
		pid = open_file->pid;
	else
		pid = current->tgid;

	iov_iter_init(&it, iov, nr_segs, len, 0);
	do {
		size_t save_len;

		nr_pages = get_numpages(cifs_sb->wsize, len, &cur_len);
		wdata = cifs_writedata_alloc(nr_pages,
					     cifs_uncached_writev_complete);
		if (!wdata) {
			rc = -ENOMEM;
			break;
		}

		rc = cifs_write_allocate_pages(wdata->pages, nr_pages);
		if (rc) {
			kfree(wdata);
			break;
		}

		save_len = cur_len;
		for (i = 0; i < nr_pages; i++) {
			copied = min_t(const size_t, cur_len, PAGE_SIZE);
			copied = iov_iter_copy_from_user(wdata->pages[i], &it,
							 0, copied);
			cur_len -= copied;
			iov_iter_advance(&it, copied);
		}
		cur_len = save_len - cur_len;

		wdata->sync_mode = WB_SYNC_ALL;
		wdata->nr_pages = nr_pages;
		wdata->offset = (__u64)offset;
		wdata->cfile = cifsFileInfo_get(open_file);
		wdata->pid = pid;
		wdata->bytes = cur_len;
		wdata->pagesz = PAGE_SIZE;
		wdata->tailsz = cur_len - ((nr_pages - 1) * PAGE_SIZE);
		rc = cifs_uncached_retry_writev(wdata);
		if (rc) {
			kref_put(&wdata->refcount,
				 cifs_uncached_writedata_release);
			break;
		}

		list_add_tail(&wdata->list, &wdata_list);
		offset += cur_len;
		len -= cur_len;
	} while (len > 0);

	/*
	 * If at least one write was successfully sent, then discard any rc
	 * value from the later writes. If the other write succeeds, then
	 * we'll end up returning whatever was written. If it fails, then
	 * we'll get a new rc value from that.
	 */
	if (!list_empty(&wdata_list))
		rc = 0;

	/*
	 * Wait for and collect replies for any successful sends in order of
	 * increasing offset. Once an error is hit or we get a fatal signal
	 * while waiting, then return without waiting for any more replies.
	 */
restart_loop:
	list_for_each_entry_safe(wdata, tmp, &wdata_list, list) {
		if (!rc) {
			/* FIXME: freezable too? */
			rc = wait_for_completion_killable(&wdata->done);
			if (rc)
				rc = -EINTR;
			else if (wdata->result)
				rc = wdata->result;
			else
				total_written += wdata->bytes;

			/* resend call if it's a retryable error */
			if (rc == -EAGAIN) {
				rc = cifs_uncached_retry_writev(wdata);
				goto restart_loop;
			}
		}
		list_del_init(&wdata->list);
		kref_put(&wdata->refcount, cifs_uncached_writedata_release);
	}

	if (total_written > 0)
		*poffset += total_written;

	cifs_stats_bytes_written(tcon, total_written);
	return total_written ? total_written : (ssize_t)rc;
}


TSReturnCode TSUrlHttpParamsSet ( TSMBuffer bufp , TSMLoc obj , const char * value , int length ) {
 return URLPartSet ( bufp , obj , value , length , & URL : : params_set ) ;
 }


static void pointer_event(VncState *vs, int button_mask, int x, int y)
{
    static uint32_t bmap[INPUT_BUTTON_MAX] = {
        [INPUT_BUTTON_LEFT]       = 0x01,
        [INPUT_BUTTON_MIDDLE]     = 0x02,
        [INPUT_BUTTON_RIGHT]      = 0x04,
        [INPUT_BUTTON_WHEEL_UP]   = 0x08,
        [INPUT_BUTTON_WHEEL_DOWN] = 0x10,
    };
    QemuConsole *con = vs->vd->dcl.con;
    int width = surface_width(vs->vd->ds);
    int height = surface_height(vs->vd->ds);

    if (vs->last_bmask != button_mask) {
        qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
        vs->last_bmask = button_mask;
    }

    if (vs->absolute) {
        qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
        qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
    } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
        qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
        qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
    } else {
        if (vs->last_x != -1) {
            qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
            qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
        }
        vs->last_x = x;
        vs->last_y = y;
    }
    qemu_input_event_sync();
}


static void monitor_puts(Monitor *mon, const char *str) { char c; for(;;) { assert(mon->outbuf_index < sizeof(mon->outbuf) - 1); c = *str++; if (c == '\0') break; if (c == '\n') mon->outbuf[mon->outbuf_index++] = '\r'; mon->outbuf[mon->outbuf_index++] = c; if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1) || c == '\n') monitor_flush(mon); } }


static void addFile ( const char * filename , const char * name , const char * source , UBool sourceTOC , UBool verbose ) {
 char * s ;
 uint32_t length ;
 char * fullPath = NULL ;
 if ( fileCount == fileMax ) {
 fileMax += CHUNK_FILE_COUNT ;
 files = ( File * ) uprv_realloc ( files , fileMax * sizeof ( files [ 0 ] ) ) ;
 if ( files == NULL ) {
 fprintf ( stderr , "pkgdata/gencmn: Could not allocate %u bytes for %d files\n" , ( unsigned int ) ( fileMax * sizeof ( files [ 0 ] ) ) , fileCount ) ;
 exit ( U_MEMORY_ALLOCATION_ERROR ) ;
 }
 }
 if ( ! sourceTOC ) {
 FileStream * file ;
 if ( uprv_pathIsAbsolute ( filename ) ) {
 fprintf ( stderr , "gencmn: Error: absolute path encountered. Old style paths are not supported. Use relative paths such as 'fur.res' or 'translit%cfur.res'.\n\tBad path: '%s'\n" , U_FILE_SEP_CHAR , filename ) ;
 exit ( U_ILLEGAL_ARGUMENT_ERROR ) ;
 }
 fullPath = pathToFullPath ( filename , source ) ;
 length = ( uint32_t ) ( uprv_strlen ( filename ) + 1 + uprv_strlen ( name ) + 1 ) ;
 s = allocString ( length ) ;
 uprv_strcpy ( s , name ) ;
 uprv_strcat ( s , U_TREE_ENTRY_SEP_STRING ) ;
 uprv_strcat ( s , filename ) ;
 fixDirToTreePath ( s ) ;
 files [ fileCount ] . basename = s ;
 files [ fileCount ] . basenameLength = length ;
 files [ fileCount ] . pathname = fullPath ;
 basenameTotal += length ;
 file = T_FileStream_open ( fullPath , "rb" ) ;
 if ( file == NULL ) {
 fprintf ( stderr , "gencmn: unable to open listed file %s\n" , fullPath ) ;
 exit ( U_FILE_ACCESS_ERROR ) ;
 }
 length = T_FileStream_size ( file ) ;
 if ( T_FileStream_error ( file ) || length <= 20 ) {
 fprintf ( stderr , "gencmn: unable to get length of listed file %s\n" , fullPath ) ;
 exit ( U_FILE_ACCESS_ERROR ) ;
 }
 T_FileStream_close ( file ) ;
 if ( maxSize && length > maxSize ) {
 if ( verbose ) {
 printf ( "%s ignored (size %ld > %ld)\n" , fullPath , ( long ) length , ( long ) maxSize ) ;
 }
 return ;
 }
 files [ fileCount ] . fileSize = length ;
 }
 else {
 char * t ;
 length = ( uint32_t ) ( uprv_strlen ( filename ) + 1 + uprv_strlen ( name ) + 1 ) ;
 s = allocString ( length ) ;
 uprv_strcpy ( s , name ) ;
 uprv_strcat ( s , U_TREE_ENTRY_SEP_STRING ) ;
 uprv_strcat ( s , filename ) ;
 fixDirToTreePath ( s ) ;
 files [ fileCount ] . basename = s ;
 t = files [ fileCount ] . pathname = allocString ( length ) ;
 while ( -- length > 0 ) {
 if ( * s == '.' || * s == '-' || * s == '/' ) {
 * t = '_' ;
 }
 else {
 * t = * s ;
 }
 ++ s ;
 ++ t ;
 }
 * t = 0 ;
 }
 ++ fileCount ;
 }


static void free_resources ( ) {
 if ( md_result_file && md_result_file != stdout ) my_fclose ( md_result_file , MYF ( 0 ) ) ;
 my_free ( opt_password ) ;
 my_free ( current_host ) ;
 if ( my_hash_inited ( & ignore_table ) ) my_hash_free ( & ignore_table ) ;
 if ( extended_insert ) dynstr_free ( & extended_row ) ;
 if ( insert_pat_inited ) dynstr_free ( & insert_pat ) ;
 if ( defaults_argv ) free_defaults ( defaults_argv ) ;
 mysql_library_end ( ) ;
 my_end ( my_end_arg ) ;
 }


static int iov_fault_in_pages_write(struct iovec *iov, unsigned long len)
{
	while (!iov->iov_len)
		iov++;

	while (len > 0) {
		unsigned long this_len;

		this_len = min_t(unsigned long, len, iov->iov_len);
		if (fault_in_pages_writeable(iov->iov_base, this_len))
			break;

		len -= this_len;
		iov++;
	}

	return len;
}


xfs_da3_fixhashpath(
	struct xfs_da_state	*state,
	struct xfs_da_state_path *path)
{
	struct xfs_da_state_blk	*blk;
	struct xfs_da_intnode	*node;
	struct xfs_da_node_entry *btree;
	xfs_dahash_t		lasthash=0;
	int			level;
	int			count;
	struct xfs_inode	*dp = state->args->dp;

	trace_xfs_da_fixhashpath(state->args);

	level = path->active-1;
	blk = &path->blk[ level ];
	switch (blk->magic) {
	case XFS_ATTR_LEAF_MAGIC:
		lasthash = xfs_attr_leaf_lasthash(blk->bp, &count);
		if (count == 0)
			return;
		break;
	case XFS_DIR2_LEAFN_MAGIC:
		lasthash = xfs_dir2_leafn_lasthash(dp, blk->bp, &count);
		if (count == 0)
			return;
		break;
	case XFS_DA_NODE_MAGIC:
		lasthash = xfs_da3_node_lasthash(dp, blk->bp, &count);
		if (count == 0)
			return;
		break;
	}
	for (blk--, level--; level >= 0; blk--, level--) {
		struct xfs_da3_icnode_hdr nodehdr;

		node = blk->bp->b_addr;
		dp->d_ops->node_hdr_from_disk(&nodehdr, node);
		btree = dp->d_ops->node_tree_p(node);
		if (be32_to_cpu(btree->hashval) == lasthash)
			break;
		blk->hashval = lasthash;
		btree[blk->index].hashval = cpu_to_be32(lasthash);
		xfs_trans_log_buf(state->args->trans, blk->bp,
				  XFS_DA_LOGRANGE(node, &btree[blk->index],
						  sizeof(*btree)));

		lasthash = be32_to_cpu(btree[nodehdr.count - 1].hashval);
	}
}


SPL_METHOD(MultipleIterator, next)
{
	spl_SplObjectStorage        *intern;
	spl_SplObjectStorageElement *element;
	zval                        *it;

	intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
	while (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == SUCCESS && !EG(exception)) {
		it = element->obj;
		zend_call_method_with_0_params(&it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_next, "next", NULL);
		zend_hash_move_forward_ex(&intern->storage, &intern->pos);
	}
}


  void * resize_temp(size_t size) {
    if (temp_end == 0)
      return alloc_temp(size);
    if (bottom + size <= top) {
      temp_end = bottom + size;
    } else {
      size_t s = temp_end - bottom;
      byte * p = bottom;
      check_size(size);
      new_chunk();
      memcpy(bottom, p, s);
      temp_end = bottom + size;
    }
    return bottom;
  }


SPL_METHOD(SplObjectStorage, next)
{
	spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	zend_hash_move_forward_ex(&intern->storage, &intern->pos);
	intern->index++;
} /* }}} */


START_TEST(qdict_get_str_test) { const char *p; const char *key = "key"; const char *str = "string"; qdict_put(tests_dict, key, qstring_from_str(str)); p = qdict_get_str(tests_dict, key); fail_unless(p != NULL); fail_unless(strcmp(p, str) == 0); }


void proto_register_lbmpdm ( void ) {
 static hf_register_info hf [ ] = {
 {
 & hf_lbmpdm_magic , {
 "Magic" , "lbmpdm.magic" , FT_UINT32 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_encoding , {
 "Encoding" , "lbmpdm.encoding" , FT_STRING , BASE_NONE , NULL , 0x0 , "encoding as determined by magic number" , HFILL }
 }
 , {
 & hf_lbmpdm_ver , {
 "Version" , "lbmpdm.ver" , FT_UINT8 , BASE_DEC , NULL , PDM_HDR_VER_TYPE_VER_MASK , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_type , {
 "Type" , "lbmpdm.type" , FT_UINT8 , BASE_DEC , NULL , PDM_HDR_VER_TYPE_TYPE_MASK , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_next_hdr , {
 "Next Header" , "lbmpdm.next_hdr" , FT_UINT8 , BASE_DEC_HEX , VALS ( lbmpdm_next_header ) , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_def_major_ver , {
 "Definition Major Version" , "lbmpdm.def_major_ver" , FT_UINT8 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_def_minor_ver , {
 "Definition Minor Version" , "lbmpdm.def_minor_ver" , FT_UINT8 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_def_id , {
 "Definition ID" , "lbmpdm.def_id" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_len , {
 "Length" , "lbmpdm.len" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segments , {
 "Segments" , "lbmpdm.segments" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment , {
 "Segment" , "lbmpdm.segment" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_next_hdr , {
 "Next Header" , "lbmpdm.segment.next_hdr" , FT_UINT8 , BASE_DEC_HEX , VALS ( lbmpdm_next_header ) , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_flags , {
 "Flags" , "lbmpdm.segment.flags" , FT_UINT8 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_res , {
 "Reserved" , "lbmpdm.segment.res" , FT_UINT16 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_len , {
 "Length" , "lbmpdm.segment.len" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_id , {
 "Definition ID" , "lbmpdm.segment_def.id" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_num_fields , {
 "Number Of Fields" , "lbmpdm.segment_def.num_fields" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_names_type , {
 "Field Names Type" , "lbmpdm.segment_def.field_names_type" , FT_UINT8 , BASE_HEX , VALS ( lbmpdm_field_name_type ) , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_finalized , {
 "Finalized" , "lbmpdm.segment_def.finalized" , FT_UINT8 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_msg_vers_major , {
 "Definition Major Version" , "lbmpdm.segment_def.msg_vers_major" , FT_UINT8 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_msg_vers_minor , {
 "Definition Minor Version" , "lbmpdm.segment_def.msg_vers_minor" , FT_UINT8 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_fixed_req_section_len , {
 "Fixed Required Section Length" , "lbmpdm.segment_def.fixed_req_section_len" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_info_len , {
 "Field Information Length" , "lbmpdm.segment_def.field_info_len" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field , {
 "Field Definition" , "lbmpdm.segment_def.field" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_def_len , {
 "Definition Length" , "lbmpdm.segment_def.field.def_len" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_id , {
 "ID" , "lbmpdm.segment_def.field.id" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_len , {
 "Length" , "lbmpdm.segment_def.field.len" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_fixed_str_len , {
 "Fixed String Length" , "lbmpdm.segment_def.field.fixed_str_len" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_num_arr_elem , {
 "Number Of Array Elements" , "lbmpdm.segment_def.field.num_arr_elem" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_req , {
 "Required" , "lbmpdm.segment_def.field.req" , FT_UINT8 , BASE_HEX , VALS ( lbmpdm_field_required ) , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_fixed , {
 "Fixed Length Field" , "lbmpdm.segment_def.field.fixed" , FT_UINT8 , BASE_HEX , VALS ( lbmpdm_field_fixed_length ) , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_fld_int_name , {
 "Field Integer Name" , "lbmpdm.segment_def.field.fld_int_name" , FT_INT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_str_name_len , {
 "String Name Length" , "lbmpdm.segment_def.field.str_name_len" , FT_INT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_str_name , {
 "String Name" , "lbmpdm.segment_def.field.str_name" , FT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_def_field_fld_type , {
 "Field Type" , "lbmpdm.segment_def.field.fld_type" , FT_UINT16 , BASE_DEC_HEX , VALS ( lbmpdm_field_type ) , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_offset_entry , {
 "Offset Entry" , "lbmpdm.segment_ofs.entry" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_offset_entry_id , {
 "ID" , "lbmpdm.segment_ofs.entry.id" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_offset_entry_offset , {
 "Offset" , "lbmpdm.segment_ofs.entry.offset" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_segment_data , {
 "Data" , "lbmpdm.segment.data" , FT_BYTES , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field , {
 "Field" , "lbmpdm.field" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_id , {
 "ID" , "lbmpdm.field.id" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_string_name , {
 "String Name" , "lbmpdm.field.string_name" , FT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_int_name , {
 "Integer Name" , "lbmpdm.field.int_name" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_type , {
 "Type" , "lbmpdm.field.type" , FT_UINT16 , BASE_DEC_HEX , VALS ( lbmpdm_field_type ) , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_total_length , {
 "Total Length" , "lbmpdm.field.total_length" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_length , {
 "Length" , "lbmpdm.field.length" , FT_UINT32 , BASE_DEC_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_boolean , {
 "Boolean Value" , "lbmpdm.field.value_boolean" , FT_UINT8 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_int8 , {
 "INT8 Value" , "lbmpdm.field.value_int8" , FT_INT8 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_uint8 , {
 "UINT8 Value" , "lbmpdm.field.value_uint8" , FT_UINT8 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_int16 , {
 "INT16 Value" , "lbmpdm.field.value_int16" , FT_INT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_uint16 , {
 "UINT16 Value" , "lbmpdm.field.value_uint16" , FT_UINT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_int32 , {
 "INT32 Value" , "lbmpdm.field.value_int32" , FT_INT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_uint32 , {
 "UINT32 Value" , "lbmpdm.field.value_uint32" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_int64 , {
 "INT64 Value" , "lbmpdm.field.value_int64" , FT_INT64 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_uint64 , {
 "UINT64 Value" , "lbmpdm.field.value_uint64" , FT_UINT64 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_float , {
 "FLOAT Value" , "lbmpdm.field.value_float" , FT_FLOAT , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_double , {
 "DOUBLE Value" , "lbmpdm.field.value_double" , FT_DOUBLE , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_decimal , {
 "DECIMAL Value" , "lbmpdm.field.value_decimal" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_timestamp , {
 "TIMESTAMP Value" , "lbmpdm.field.value_timestamp" , FT_ABSOLUTE_TIME , ABSOLUTE_TIME_LOCAL , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_fixed_string , {
 "FIXED STRING Value" , "lbmpdm.field.value_fixed_string" , FT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_string , {
 "STRING Value" , "lbmpdm.field.value_string" , FT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_fixed_unicode , {
 "FIXED UNICODE Value" , "lbmpdm.field.value_fixed_unicode" , FT_BYTES , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_unicode , {
 "UNICODE Value" , "lbmpdm.field.value_unicode" , FT_BYTES , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_blob , {
 "BLOB Value" , "lbmpdm.field.value_blob" , FT_BYTES , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_lbmpdm_field_value_message , {
 "MESSAGE Value" , "lbmpdm.field.value_message" , FT_BYTES , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 }
 ;
 static gint * ett [ ] = {
 & ett_lbmpdm , & ett_lbmpdm_segments , & ett_lbmpdm_segment , & ett_lbmpdm_offset_entry , & ett_lbmpdm_segment_def_field , & ett_lbmpdm_field }
 ;
 proto_lbmpdm = proto_register_protocol ( "LBMPDM Protocol" , "LBMPDM" , "lbmpdm" ) ;
 proto_register_field_array ( proto_lbmpdm , hf , array_length ( hf ) ) ;
 proto_register_subtree_array ( ett , array_length ( ett ) ) ;
 lbmpdm_definition_table = wmem_tree_new_autoreset ( wmem_epan_scope ( ) , wmem_file_scope ( ) ) ;
 }


void ppc_hash64_store_hpte(PowerPCCPU *cpu, hwaddr ptex, uint64_t pte0, uint64_t pte1) { CPUPPCState *env = &cpu->env; hwaddr offset = ptex * HASH_PTE_SIZE_64; if (env->external_htab == MMU_HASH64_KVM_MANAGED_HPT) { kvmppc_write_hpte(ptex, pte0, pte1); return; } if (env->external_htab) { stq_p(env->external_htab + offset, pte0); stq_p(env->external_htab + offset + HASH_PTE_SIZE_64 / 2, pte1); } else { hwaddr base = ppc_hash64_hpt_base(cpu); stq_phys(CPU(cpu)->as, base + offset, pte0); stq_phys(CPU(cpu)->as, base + offset + HASH_PTE_SIZE_64 / 2, pte1); } }


static int raw_cmd_copyout(int cmd, void __user *param,
				  struct floppy_raw_cmd *ptr)
{
	int ret;

	while (ptr) {
		ret = copy_to_user(param, ptr, sizeof(*ptr));
		if (ret)
			return -EFAULT;
		param += sizeof(struct floppy_raw_cmd);
		if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
			if (ptr->length >= 0 &&
			    ptr->length <= ptr->buffer_length) {
				long length = ptr->buffer_length - ptr->length;
				ret = fd_copyout(ptr->data, ptr->kernel_data,
						 length);
				if (ret)
					return ret;
			}
		}
		ptr = ptr->next;
	}

	return 0;
}


xfs_attr3_leaf_clearflag(
	struct xfs_da_args	*args)
{
	struct xfs_attr_leafblock *leaf;
	struct xfs_attr_leaf_entry *entry;
	struct xfs_attr_leaf_name_remote *name_rmt;
	struct xfs_buf		*bp;
	int			error;
#ifdef DEBUG
	struct xfs_attr3_icleaf_hdr ichdr;
	xfs_attr_leaf_name_local_t *name_loc;
	int namelen;
	char *name;
#endif /* DEBUG */

	trace_xfs_attr_leaf_clearflag(args);
	/*
	 * Set up the operation.
	 */
	error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp);
	if (error)
		return(error);

	leaf = bp->b_addr;
	entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
	ASSERT(entry->flags & XFS_ATTR_INCOMPLETE);

#ifdef DEBUG
	xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
	ASSERT(args->index < ichdr.count);
	ASSERT(args->index >= 0);

	if (entry->flags & XFS_ATTR_LOCAL) {
		name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
		namelen = name_loc->namelen;
		name = (char *)name_loc->nameval;
	} else {
		name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
		namelen = name_rmt->namelen;
		name = (char *)name_rmt->name;
	}
	ASSERT(be32_to_cpu(entry->hashval) == args->hashval);
	ASSERT(namelen == args->namelen);
	ASSERT(memcmp(name, args->name, namelen) == 0);
#endif /* DEBUG */

	entry->flags &= ~XFS_ATTR_INCOMPLETE;
	xfs_trans_log_buf(args->trans, bp,
			 XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry)));

	if (args->rmtblkno) {
		ASSERT((entry->flags & XFS_ATTR_LOCAL) == 0);
		name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
		name_rmt->valueblk = cpu_to_be32(args->rmtblkno);
		name_rmt->valuelen = cpu_to_be32(args->valuelen);
		xfs_trans_log_buf(args->trans, bp,
			 XFS_DA_LOGRANGE(leaf, name_rmt, sizeof(*name_rmt)));
	}

	/*
	 * Commit the flag value change and start the next trans in series.
	 */
	return xfs_trans_roll(&args->trans, args->dp);
}


SPL_METHOD(SplDoublyLinkedList, serialize)
{
	spl_dllist_object     *intern   = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
	smart_str              buf      = {0};
	spl_ptr_llist_element *current  = intern->llist->head, *next;
    zval                   *flags;
	php_serialize_data_t   var_hash;

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	PHP_VAR_SERIALIZE_INIT(var_hash);

	/* flags */
	MAKE_STD_ZVAL(flags);
	ZVAL_LONG(flags, intern->flags);
	php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC);
	zval_ptr_dtor(&flags);

	/* elements */
	while (current) {
		smart_str_appendc(&buf, ':');
		next = current->next;

		php_var_serialize(&buf, (zval **)&current->data, &var_hash TSRMLS_CC);

		current = next;
	}

	smart_str_0(&buf);

	/* done */
	PHP_VAR_SERIALIZE_DESTROY(var_hash);

	if (buf.c) {
		RETURN_STRINGL(buf.c, buf.len, 0);
	} else {
		RETURN_NULL();
	}

} /* }}} */


SPL_METHOD(SplDoublyLinkedList, push)
{
	zval *value;
	spl_dllist_object *intern;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) {
		return;
	}

	SEPARATE_ARG_IF_REF(value);

	intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
	spl_ptr_llist_push(intern->llist, value TSRMLS_CC);

	RETURN_TRUE;
}


xfs_attr3_leaf_getvalue(
	struct xfs_buf		*bp,
	struct xfs_da_args	*args)
{
	struct xfs_attr_leafblock *leaf;
	struct xfs_attr3_icleaf_hdr ichdr;
	struct xfs_attr_leaf_entry *entry;
	struct xfs_attr_leaf_name_local *name_loc;
	struct xfs_attr_leaf_name_remote *name_rmt;
	int			valuelen;

	leaf = bp->b_addr;
	xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
	ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8);
	ASSERT(args->index < ichdr.count);

	entry = &xfs_attr3_leaf_entryp(leaf)[args->index];
	if (entry->flags & XFS_ATTR_LOCAL) {
		name_loc = xfs_attr3_leaf_name_local(leaf, args->index);
		ASSERT(name_loc->namelen == args->namelen);
		ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0);
		valuelen = be16_to_cpu(name_loc->valuelen);
		if (args->flags & ATTR_KERNOVAL) {
			args->valuelen = valuelen;
			return 0;
		}
		if (args->valuelen < valuelen) {
			args->valuelen = valuelen;
			return XFS_ERROR(ERANGE);
		}
		args->valuelen = valuelen;
		memcpy(args->value, &name_loc->nameval[args->namelen], valuelen);
	} else {
		name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index);
		ASSERT(name_rmt->namelen == args->namelen);
		ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0);
		valuelen = be32_to_cpu(name_rmt->valuelen);
		args->rmtblkno = be32_to_cpu(name_rmt->valueblk);
		args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount,
						       valuelen);
		if (args->flags & ATTR_KERNOVAL) {
			args->valuelen = valuelen;
			return 0;
		}
		if (args->valuelen < valuelen) {
			args->valuelen = valuelen;
			return XFS_ERROR(ERANGE);
		}
		args->valuelen = valuelen;
	}
	return 0;
}


int pt_setxattr(FsContext *ctx, const char *path, const char *name, void *value, size_t size, int flags) { char *buffer; int ret; buffer = rpath(ctx, path); ret = lsetxattr(buffer, name, value, size, flags); g_free(buffer); return ret; }


bool qdict_get_bool(const QDict *qdict, const char *key) { QObject *obj = qdict_get_obj(qdict, key, QTYPE_QBOOL); return qbool_get_bool(qobject_to_qbool(obj)); }


SPL_METHOD(Array, key)
{
	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	spl_array_iterator_key(getThis(), return_value TSRMLS_CC);
} /* }}} */


pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len,
			int atomic)
{
	unsigned long copy;

	while (len > 0) {
		while (!iov->iov_len)
			iov++;
		copy = min_t(unsigned long, len, iov->iov_len);

		if (atomic) {
			if (__copy_from_user_inatomic(to, iov->iov_base, copy))
				return -EFAULT;
		} else {
			if (copy_from_user(to, iov->iov_base, copy))
				return -EFAULT;
		}
		to += copy;
		len -= copy;
		iov->iov_base += copy;
		iov->iov_len -= copy;
	}
	return 0;
}


SPL_METHOD(Array, getIteratorClass)
{
	zval *object = getThis();
	spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	RETURN_STRING(intern->ce_get_iterator->name, 1);
}


SPL_METHOD(Array, unserialize)
{
	spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);

	char *buf;
	int buf_len;
	const unsigned char *p, *s;
	php_unserialize_data_t var_hash;
	zval *pmembers, *pflags = NULL;
	HashTable *aht;
	long flags;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
		return;
	}

	if (buf_len == 0) {
		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty");
		return;
	}

	aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
	if (aht->nApplyCount > 0) {
		zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
		return;
	}

	/* storage */
	s = p = (const unsigned char*)buf;
	PHP_VAR_UNSERIALIZE_INIT(var_hash);

	if (*p!= 'x' || *++p != ':') {
		goto outexcept;
	}
	++p;

	ALLOC_INIT_ZVAL(pflags);
	if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) {
		zval_ptr_dtor(&pflags);
		goto outexcept;
	}

	--p; /* for ';' */
	flags = Z_LVAL_P(pflags);
	zval_ptr_dtor(&pflags);
	/* flags needs to be verified and we also need to verify whether the next
	 * thing we get is ';'. After that we require an 'm' or somethign else
	 * where 'm' stands for members and anything else should be an array. If
	 * neither 'a' or 'm' follows we have an error. */

	if (*p != ';') {
		goto outexcept;
	}
	++p;

	if (*p!='m') {
		if (*p!='a' && *p!='O' && *p!='C' && *p!='r') {
			goto outexcept;
		}
		intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK;
		intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK;
		zval_ptr_dtor(&intern->array);
		ALLOC_INIT_ZVAL(intern->array);
		if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) {
			goto outexcept;
		}
	}
	if (*p != ';') {
		goto outexcept;
	}
	++p;

	/* members */
	if (*p!= 'm' || *++p != ':') {
		goto outexcept;
	}
	++p;

	ALLOC_INIT_ZVAL(pmembers);
	if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) {
		zval_ptr_dtor(&pmembers);
		goto outexcept;
	}

	/* copy members */
	if (!intern->std.properties) {
		rebuild_object_properties(&intern->std);
	}
	zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));
	zval_ptr_dtor(&pmembers);

	/* done reading $serialized */

	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
	return;

outexcept:
	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
	zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
	return;

} /* }}} */


TEST_F(SQLiteUtilTests, test_column_type_determination) {
  // Correct identification of text and ints
  testTypesExpected("select path, inode from file where path like '%'",
                    TypeMap({{"path", TEXT_TYPE}, {"inode", INTEGER_TYPE}}));
  // Correctly treating BLOBs as text
  testTypesExpected("select CAST(seconds AS BLOB) as seconds FROM time",
                    TypeMap({{"seconds", TEXT_TYPE}}));
  // Correctly treating ints cast as double as doubles
  testTypesExpected("select CAST(seconds AS DOUBLE) as seconds FROM time",
                    TypeMap({{"seconds", DOUBLE_TYPE}}));
  // Correctly treating bools as ints
  testTypesExpected("select CAST(seconds AS BOOLEAN) as seconds FROM time",
                    TypeMap({{"seconds", INTEGER_TYPE}}));
  // Correctly recognizing values from columns declared double as double, even
  // if they happen to have integer value.  And also test multi-statement
  // queries.
  testTypesExpected(
      "CREATE TABLE test_types_table (username varchar(30) primary key, age "
      "double);INSERT INTO test_types_table VALUES (\"mike\", 23); SELECT age "
      "from test_types_table",
      TypeMap({{"age", DOUBLE_TYPE}}));
}


SPL_METHOD(Array, rewind)
{
	zval *object = getThis();
	spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	spl_array_rewind(intern TSRMLS_CC);
}


void CLua::init_libraries()
{
    lua_stack_cleaner clean(state());

    lua_pushcfunction(_state, lua_loadstring);
    lua_setglobal(_state, "loadstring");

    // Open Crawl bindings
    cluaopen_kills(_state);
    cluaopen_you(_state);
    cluaopen_item(_state);
    cluaopen_food(_state);
    cluaopen_crawl(_state);
    cluaopen_file(_state);
    cluaopen_moninf(_state);
    cluaopen_options(_state);
    cluaopen_travel(_state);
    cluaopen_view(_state);
    cluaopen_spells(_state);

    cluaopen_globals(_state);

    execfile("dlua/macro.lua", true, true);

    // All hook names must be chk_????
    execstring("chk_startgame = { }", "base");

    lua_register(_state, "loadfile", _clua_loadfile);
    lua_register(_state, "dofile", _clua_dofile);

    lua_register(_state, "crawl_require", _clua_require);

    execfile("dlua/util.lua", true, true);
    execfile("dlua/iter.lua", true, true);
    execfile("dlua/tags.lua", true, true);
    execfile("dlua/init.lua", true, true);

    if (managed_vm)
    {
        lua_register(_state, "pcall", _clua_guarded_pcall);
        execfile("dlua/userbase.lua", true, true);
        execfile("dlua/persist.lua", true, true);
    }
}


void mct_close_log ( ) {
 if ( ! mct_log_file ) return ;
 my_fclose ( mct_log_file , MYF ( 0 ) ) ;
 mct_log_file = NULL ;
 }


static zval *spl_array_read_dimension_ex(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
	zval **ret;

	if (check_inherited) {
		spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
		if (intern->fptr_offset_get) {
			zval *rv;
			if (!offset) {
				ALLOC_INIT_ZVAL(offset);
			} else {
				SEPARATE_ARG_IF_REF(offset);
			}
			zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", &rv, offset);
			zval_ptr_dtor(&offset);
			if (rv) {
				zval_ptr_dtor(&intern->retval);
				MAKE_STD_ZVAL(intern->retval);
				ZVAL_ZVAL(intern->retval, rv, 1, 1);
				return intern->retval;
			}
			return EG(uninitialized_zval_ptr);
		}
	}
	ret = spl_array_get_dimension_ptr_ptr(check_inherited, object, offset, type TSRMLS_CC);

	/* When in a write context,
	 * ZE has to be fooled into thinking this is in a reference set
	 * by separating (if necessary) and returning as an is_ref=1 zval (even if refcount == 1) */
	if ((type == BP_VAR_W || type == BP_VAR_RW || type == BP_VAR_UNSET) && !Z_ISREF_PP(ret) && ret != &EG(uninitialized_zval_ptr)) {
		if (Z_REFCOUNT_PP(ret) > 1) {
			zval *newval;

			/* Separate */
			MAKE_STD_ZVAL(newval);
			*newval = **ret;
			zval_copy_ctor(newval);
			Z_SET_REFCOUNT_P(newval, 1);

			/* Replace */
			Z_DELREF_PP(ret);
			*ret = newval;
		}

		Z_SET_ISREF_PP(ret);
	}

	return *ret;
} /* }}} */


SPL_METHOD(Array, current)
{
	zval *object = getThis();
	spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
	zval **entry;
	HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
		return;
	}

	if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) {
		return;
	}
	RETVAL_ZVAL(*entry, 1, 0);
}


static int opt_show_ ## section ( const char * opt , const char * arg ) {
 mark_section_show_entries ( SECTION_ID_ ## target_section_id , 1 , NULL ) ;
 return 0 ;
 }
 DEFINE_OPT_SHOW_SECTION ( chapters , CHAPTERS ) DEFINE_OPT_SHOW_SECTION ( error , ERROR ) DEFINE_OPT_SHOW_SECTION ( format , FORMAT )


static vpx_codec_err_t update_error_state ( vpx_codec_alg_priv_t * ctx , const struct vpx_internal_error_info * error ) {
 const vpx_codec_err_t res = error -> error_code ;
 if ( res != VPX_CODEC_OK ) ctx -> base . err_detail = error -> has_detail ? error -> detail : NULL ;
 return res ;
 }


bool inode_capable(const struct inode *inode, int cap)
{
	struct user_namespace *ns = current_user_ns();

	return ns_capable(ns, cap) && kuid_has_mapping(ns, inode->i_uid);
}


PHPAPI void var_push_dtor_no_addref(php_unserialize_data_t *var_hashx, zval **rval)
{
	var_entries *var_hash;

    if (!var_hashx || !*var_hashx) {
        return;
    }

    var_hash = (*var_hashx)->last_dtor;
#if VAR_ENTRIES_DBG
	fprintf(stderr, "var_push_dtor_no_addref(%ld): %d (%d)\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval), Z_REFCOUNT_PP(rval));
#endif

	if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
		var_hash = emalloc(sizeof(var_entries));
		var_hash->used_slots = 0;
		var_hash->next = 0;

		if (!(*var_hashx)->first_dtor) {
			(*var_hashx)->first_dtor = var_hash;
		} else {
			((var_entries *) (*var_hashx)->last_dtor)->next = var_hash;
		}

		(*var_hashx)->last_dtor = var_hash;
	}

	var_hash->data[var_hash->used_slots++] = *rval;
}


static void show_packet(AVFormatContext *fmt_ctx, AVPacket *pkt) { char val_str[128]; AVStream *st = fmt_ctx->streams[pkt->stream_index]; printf("[PACKET]\n"); printf("codec_type=%s\n", media_type_string(st->codec->codec_type)); printf("stream_index=%d\n", pkt->stream_index); printf("pts=%s\n", ts_value_string(val_str, sizeof(val_str), pkt->pts)); printf("pts_time=%s\n", time_value_string(val_str, sizeof(val_str), pkt->pts, &st->time_base)); printf("dts=%s\n", ts_value_string(val_str, sizeof(val_str), pkt->dts)); printf("dts_time=%s\n", time_value_string(val_str, sizeof(val_str), pkt->dts, &st->time_base)); printf("duration=%s\n", ts_value_string(val_str, sizeof(val_str), pkt->duration)); printf("duration_time=%s\n", time_value_string(val_str, sizeof(val_str), pkt->duration, &st->time_base)); printf("size=%s\n", value_string(val_str, sizeof(val_str), pkt->size, unit_byte_str)); printf("pos=%"PRId64"\n", pkt->pos); printf("flags=%c\n", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_'); printf("[/PACKET]\n"); }


MONGO_EXPORT int bson_finish( bson *b ) {
    int i;

    if( b->err & BSON_NOT_UTF8 )
        return BSON_ERROR;

    if ( ! b->finished ) {
        if ( bson_ensure_space( b, 1 ) == BSON_ERROR ) return BSON_ERROR;
        bson_append_byte( b, 0 );
        i = b->cur - b->data;
        bson_little_endian32( b->data, &i );
        b->finished = 1;
    }

    return BSON_OK;
}


static void set_default_kf_interval ( struct stream_state * stream , struct VpxEncoderConfig * global ) {
 if ( ! stream -> config . have_kf_max_dist ) {
 double framerate = ( double ) global -> framerate . num / global -> framerate . den ;
 if ( framerate > 0.0 ) stream -> config . cfg . kf_max_dist = ( unsigned int ) ( 5.0 * framerate ) ;
 }
 }


static void test_bug1644 ( ) {
 MYSQL_STMT * stmt ;
 MYSQL_RES * result ;
 MYSQL_ROW row ;
 MYSQL_BIND my_bind [ 4 ] ;
 int num ;
 my_bool isnull ;
 int rc , i ;
 char query [ MAX_TEST_QUERY_LENGTH ] ;
 myheader ( "test_bug1644" ) ;
 rc = mysql_query ( mysql , "DROP TABLE IF EXISTS foo_dfr" ) ;
 myquery ( rc ) ;
 rc = mysql_query ( mysql , "CREATE TABLE foo_dfr(col1 int, col2 int, col3 int, col4 int);
" ) ;
 myquery ( rc ) ;
 strmov ( query , "INSERT INTO foo_dfr VALUES (?, ?, ?, ? )" ) ;
 stmt = mysql_simple_prepare ( mysql , query ) ;
 check_stmt ( stmt ) ;
 verify_param_count ( stmt , 4 ) ;
 memset ( my_bind , 0 , sizeof ( my_bind ) ) ;
 num = 22 ;
 isnull = 0 ;
 for ( i = 0 ;
 i < 4 ;
 i ++ ) {
 my_bind [ i ] . buffer_type = MYSQL_TYPE_LONG ;
 my_bind [ i ] . buffer = ( void * ) & num ;
 my_bind [ i ] . is_null = & isnull ;
 }
 rc = mysql_stmt_bind_param ( stmt , my_bind ) ;
 check_execute ( stmt , rc ) ;
 rc = mysql_stmt_execute ( stmt ) ;
 check_execute ( stmt , rc ) ;
 isnull = 1 ;
 for ( i = 0 ;
 i < 4 ;
 i ++ ) my_bind [ i ] . is_null = & isnull ;
 rc = mysql_stmt_bind_param ( stmt , my_bind ) ;
 check_execute ( stmt , rc ) ;
 rc = mysql_stmt_execute ( stmt ) ;
 check_execute ( stmt , rc ) ;
 isnull = 0 ;
 num = 88 ;
 for ( i = 0 ;
 i < 4 ;
 i ++ ) my_bind [ i ] . is_null = & isnull ;
 rc = mysql_stmt_bind_param ( stmt , my_bind ) ;
 check_execute ( stmt , rc ) ;
 rc = mysql_stmt_execute ( stmt ) ;
 check_execute ( stmt , rc ) ;
 mysql_stmt_close ( stmt ) ;
 rc = mysql_query ( mysql , "SELECT * FROM foo_dfr" ) ;
 myquery ( rc ) ;
 result = mysql_store_result ( mysql ) ;
 mytest ( result ) ;
 rc = my_process_result_set ( result ) ;
 DIE_UNLESS ( rc == 3 ) ;
 mysql_data_seek ( result , 0 ) ;
 row = mysql_fetch_row ( result ) ;
 mytest ( row ) ;
 for ( i = 0 ;
 i < 4 ;
 i ++ ) {
 DIE_UNLESS ( strcmp ( row [ i ] , "22" ) == 0 ) ;
 }
 row = mysql_fetch_row ( result ) ;
 mytest ( row ) ;
 for ( i = 0 ;
 i < 4 ;
 i ++ ) {
 DIE_UNLESS ( row [ i ] == 0 ) ;
 }
 row = mysql_fetch_row ( result ) ;
 mytest ( row ) ;
 for ( i = 0 ;
 i < 4 ;
 i ++ ) {
 DIE_UNLESS ( strcmp ( row [ i ] , "88" ) == 0 ) ;
 }
 row = mysql_fetch_row ( result ) ;
 mytest_r ( row ) ;
 mysql_free_result ( result ) ;
 }


int vp8_use_as_reference ( VP8_COMP * cpi , int ref_frame_flags ) {
 if ( ref_frame_flags > 7 ) return - 1 ;
 cpi -> ref_frame_flags = ref_frame_flags ;
 return 0 ;
 }


static KVMSlot *kvm_alloc_slot(KVMState *s) { int i; for (i = 0; i < ARRAY_SIZE(s->slots); i++) { /* KVM private memory slots */ if (i >= 8 && i < 12) continue; if (s->slots[i].memory_size == 0) return &s->slots[i]; } fprintf(stderr, "%s: no free slot available\n", __func__); abort(); }


int float32_eq_signaling( float32 a, float32 b STATUS_PARAM ) { if ( ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) ) || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) ) ) { float_raise( float_flag_invalid STATUS_VAR); return 0; } return ( a == b ) || ( (bits32) ( ( a | b )<<1 ) == 0 ); }


snmp_message_decode(snmp_packet_t *snmp_packet, snmp_header_t *header, snmp_varbind_t *varbinds)
{
  uint8_t type, len, i;

  if(!snmp_ber_decode_type(snmp_packet, &type)) {
    LOG_DBG("Could not decode type\n");
    return 0;
  }

  if(type != BER_DATA_TYPE_SEQUENCE) {
    LOG_DBG("Invalid type\n");
    return 0;
  }

  if(!snmp_ber_decode_length(snmp_packet, &len)) {
    LOG_DBG("Could not decode length\n");
    return 0;
  }

  if(!snmp_ber_decode_integer(snmp_packet, &header->version)) {
    LOG_DBG("Could not decode version\n");
    return 0;
  }

  switch(header->version) {
  case SNMP_VERSION_1:
  case SNMP_VERSION_2C:
    break;
  default:
    LOG_DBG("Invalid version\n");
    return 0;
  }

  if(!snmp_ber_decode_string_len_buffer(snmp_packet, &header->community.community, &header->community.length)) {
    LOG_DBG("Could not decode community\n");
    return 0;
  }

  if(!snmp_ber_decode_type(snmp_packet, &header->pdu_type)) {
    LOG_DBG("Could not decode pdu type\n");
    return 0;
  }

  switch(header->pdu_type) {
  case BER_DATA_TYPE_PDU_GET_REQUEST:
  case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST:
  case BER_DATA_TYPE_PDU_GET_RESPONSE:
  case BER_DATA_TYPE_PDU_SET_REQUEST:
  case BER_DATA_TYPE_PDU_GET_BULK:
    break;
  default:
    LOG_DBG("Invalid version\n");
    return 0;
  }

  if(!snmp_ber_decode_length(snmp_packet, &len)) {
    LOG_DBG("Could not decode length\n");
    return 0;
  }

  if(!snmp_ber_decode_integer(snmp_packet, &header->request_id)) {
    LOG_DBG("Could not decode request id\n");
    return 0;
  }

  switch(header->pdu_type) {
  case BER_DATA_TYPE_PDU_GET_BULK:
    if(!snmp_ber_decode_integer(snmp_packet, &header->non_repeaters)) {
      LOG_DBG("Could not decode non repeaters\n");
      return 0;
    }

    if(!snmp_ber_decode_integer(snmp_packet, &header->max_repetitions)) {
      LOG_DBG("Could not decode max repetition\n");
      return 0;
    }
    break;
  default:
    if(!snmp_ber_decode_integer(snmp_packet, &header->error_status)) {
      LOG_DBG("Could not decode error status\n");
      return 0;
    }

    if(!snmp_ber_decode_integer(snmp_packet, &header->error_index)) {
      LOG_DBG("Could not decode error index\n");
      return 0;
    }
    break;
  }

  if(!snmp_ber_decode_type(snmp_packet, &type)) {
    LOG_DBG("Could not decode type\n");
    return 0;
  }

  if(type != BER_DATA_TYPE_SEQUENCE) {
    LOG_DBG("Invalid type\n");
    return 0;
  }

  if(!snmp_ber_decode_length(snmp_packet, &len)) {
    LOG_DBG("Could not decode length\n");
    return 0;
  }

  for(i = 0; snmp_packet->used > 0; ++i) {
    if(i >= SNMP_MAX_NR_VALUES) {
      LOG_DBG("OID's overflow\n");
      return 0;
    }

    if(!snmp_ber_decode_type(snmp_packet, &type)) {
      LOG_DBG("Could not decode type\n");
      return 0;
    }

    if(type != BER_DATA_TYPE_SEQUENCE) {
      LOG_DBG("Invalid (%X) type\n", type);
      return 0;
    }

    if(!snmp_ber_decode_length(snmp_packet, &len)) {
      LOG_DBG("Could not decode length\n");
      return 0;
    }

    if(!snmp_ber_decode_oid(snmp_packet, &varbinds[i].oid)) {
      LOG_DBG("Could not decode oid\n");
      return 0;
    }

    varbinds[i].value_type = *snmp_packet->in;

    switch(varbinds[i].value_type) {
    case BER_DATA_TYPE_INTEGER:
      if(!snmp_ber_decode_integer(snmp_packet, &varbinds[i].value.integer)) {
        LOG_DBG("Could not decode integer type\n");
        return 0;
      }
      break;
    case BER_DATA_TYPE_TIMETICKS:
      if(!snmp_ber_decode_timeticks(snmp_packet, &varbinds[i].value.integer)) {
        LOG_DBG("Could not decode timeticks type\n");
        return 0;
      }
      break;
    case BER_DATA_TYPE_OCTET_STRING:
      if(!snmp_ber_decode_string_len_buffer(snmp_packet, &varbinds[i].value.string.string, &varbinds[i].value.string.length)) {
        LOG_DBG("Could not decode octed string type\n");
        return 0;
      }
      break;
    case BER_DATA_TYPE_NULL:
      if(!snmp_ber_decode_null(snmp_packet)) {
        LOG_DBG("Could not decode null type\n");
        return 0;
      }
      break;
    default:
      LOG_DBG("Invalid varbind type\n");
      return 0;
    }
  }

  return 1;
}


static int pppol2tp_setsockopt(struct socket *sock, int level, int optname,
			       char __user *optval, unsigned int optlen)
{
	struct sock *sk = sock->sk;
	struct l2tp_session *session;
	struct l2tp_tunnel *tunnel;
	struct pppol2tp_session *ps;
	int val;
	int err;

	if (level != SOL_PPPOL2TP)
		return udp_prot.setsockopt(sk, level, optname, optval, optlen);

	if (optlen < sizeof(int))
		return -EINVAL;

	if (get_user(val, (int __user *)optval))
		return -EFAULT;

	err = -ENOTCONN;
	if (sk->sk_user_data == NULL)
		goto end;

	/* Get session context from the socket */
	err = -EBADF;
	session = pppol2tp_sock_to_session(sk);
	if (session == NULL)
		goto end;

	/* Special case: if session_id == 0x0000, treat as operation on tunnel
	 */
	ps = l2tp_session_priv(session);
	if ((session->session_id == 0) &&
	    (session->peer_session_id == 0)) {
		err = -EBADF;
		tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
		if (tunnel == NULL)
			goto end_put_sess;

		err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val);
		sock_put(ps->tunnel_sock);
	} else
		err = pppol2tp_session_setsockopt(sk, session, optname, val);

	err = 0;

end_put_sess:
	sock_put(sk);
end:
	return err;
}


PHP_MINIT_FUNCTION(exif)
{
	REGISTER_INI_ENTRIES();
	if (zend_hash_exists(&module_registry, "mbstring", sizeof("mbstring"))) {
		REGISTER_LONG_CONSTANT("EXIF_USE_MBSTRING", 1, CONST_CS | CONST_PERSISTENT);
	} else {
		REGISTER_LONG_CONSTANT("EXIF_USE_MBSTRING", 0, CONST_CS | CONST_PERSISTENT);
	}
	return SUCCESS;
}


static int qcow_create(const char *filename, QemuOpts *opts, Error **errp) { int header_size, backing_filename_len, l1_size, shift, i; QCowHeader header; uint8_t *tmp; int64_t total_size = 0; char *backing_file = NULL; Error *local_err = NULL; int ret; BlockBackend *qcow_blk; const char *encryptfmt = NULL; QDict *options; QDict *encryptopts = NULL; QCryptoBlockCreateOptions *crypto_opts = NULL; QCryptoBlock *crypto = NULL; /* Read out options */ total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0), BDRV_SECTOR_SIZE); if (total_size == 0) { error_setg(errp, "Image size is too small, cannot be zero length"); ret = -EINVAL; goto cleanup; } backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE); encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT); if (encryptfmt) { if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) { error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and " BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive"); ret = -EINVAL; goto cleanup; } } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) { encryptfmt = "aes"; } ret = bdrv_create_file(filename, opts, &local_err); if (ret < 0) { error_propagate(errp, local_err); goto cleanup; } qcow_blk = blk_new_open(filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, &local_err); if (qcow_blk == NULL) { error_propagate(errp, local_err); ret = -EIO; goto cleanup; } blk_set_allow_write_beyond_eof(qcow_blk, true); ret = blk_truncate(qcow_blk, 0, PREALLOC_MODE_OFF, errp); if (ret < 0) { goto exit; } memset(&header, 0, sizeof(header)); header.magic = cpu_to_be32(QCOW_MAGIC); header.version = cpu_to_be32(QCOW_VERSION); header.size = cpu_to_be64(total_size); header_size = sizeof(header); backing_filename_len = 0; if (backing_file) { if (strcmp(backing_file, "fat:")) { header.backing_file_offset = cpu_to_be64(header_size); backing_filename_len = strlen(backing_file); header.backing_file_size = cpu_to_be32(backing_filename_len); header_size += backing_filename_len; } else { /* special backing file for vvfat */ g_free(backing_file); backing_file = NULL; } header.cluster_bits = 9; /* 512 byte cluster to avoid copying unmodified sectors */ header.l2_bits = 12; /* 32 KB L2 tables */ } else { header.cluster_bits = 12; /* 4 KB clusters */ header.l2_bits = 9; /* 4 KB L2 tables */ } header_size = (header_size + 7) & ~7; shift = header.cluster_bits + header.l2_bits; l1_size = (total_size + (1LL << shift) - 1) >> shift; header.l1_table_offset = cpu_to_be64(header_size); options = qemu_opts_to_qdict(opts, NULL); qdict_extract_subqdict(options, &encryptopts, "encrypt."); QDECREF(options); if (encryptfmt) { if (!g_str_equal(encryptfmt, "aes")) { error_setg(errp, "Unknown encryption format '%s', expected 'aes'", encryptfmt); ret = -EINVAL; goto exit; } header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES); crypto_opts = block_crypto_create_opts_init( Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp); if (!crypto_opts) { ret = -EINVAL; goto exit; } crypto = qcrypto_block_create(crypto_opts, "encrypt.", NULL, NULL, NULL, errp); if (!crypto) { ret = -EINVAL; goto exit; } } else { header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE); } /* write all the data */ ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0); if (ret != sizeof(header)) { goto exit; } if (backing_file) { ret = blk_pwrite(qcow_blk, sizeof(header), backing_file, backing_filename_len, 0); if (ret != backing_filename_len) { goto exit; } } tmp = g_malloc0(BDRV_SECTOR_SIZE); for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE); i++) { ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i, tmp, BDRV_SECTOR_SIZE, 0); if (ret != BDRV_SECTOR_SIZE) { g_free(tmp); goto exit; } } g_free(tmp); ret = 0; exit: blk_unref(qcow_blk); cleanup: QDECREF(encryptopts); qcrypto_block_free(crypto); qapi_free_QCryptoBlockCreateOptions(crypto_opts); g_free(backing_file); return ret; }


static int x8_decode_intra_mb(IntraX8Context* const w, const int chroma){ MpegEncContext * const s= w->s; uint8_t * scantable; int final,run,level; int ac_mode,dc_mode,est_run,dc_level; int pos,n; int zeros_only; int use_quant_matrix; int sign; assert(w->orient<12); s->dsp.clear_block(s->block[0]); if(chroma){ dc_mode=2; }else{ dc_mode=!!w->est_run;//0,1 } if(x8_get_dc_rlf(w, dc_mode, &dc_level, &final)) return -1; n=0; zeros_only=0; if(!final){//decode ac use_quant_matrix=w->use_quant_matrix; if(chroma){ ac_mode = 1; est_run = 64;//not used }else{ if (w->raw_orient < 3){ use_quant_matrix = 0; } if(w->raw_orient > 4){ ac_mode = 0; est_run = 64; }else{ if(w->est_run > 1){ ac_mode = 2; est_run=w->est_run; }else{ ac_mode = 3; est_run = 64; } } } x8_select_ac_table(w,ac_mode); /*scantable_selector[12]={0,2,0,1,1,1,0,2,2,0,1,2};<- -> 10'01' 00'10' 10'00' 01'01' 01'00' 10'00 =>0x928548 */ scantable = w->scantable[ (0x928548>>(2*w->orient))&3 ].permutated; pos=0; do { n++; if( n >= est_run ){ ac_mode=3; x8_select_ac_table(w,3); } x8_get_ac_rlf(w,ac_mode,&run,&level,&final); pos+=run+1; if(pos>63){ //this also handles vlc error in x8_get_ac_rlf return -1; } level= (level+1) * w->dquant; level+= w->qsum; sign = - get_bits1(&s->gb); level = (level ^ sign) - sign; if(use_quant_matrix){ level = (level*quant_table[pos])>>8; } s->block[0][ scantable[pos] ]=level; }while(!final); s->block_last_index[0]=pos; }else{//DC only s->block_last_index[0]=0; if(w->flat_dc && ((unsigned)(dc_level+1)) < 3){//[-1;1] int32_t divide_quant= !chroma ? w->divide_quant_dc_luma: w->divide_quant_dc_chroma; int32_t dc_quant = !chroma ? w->quant: w->quant_dc_chroma; //original intent dc_level+=predicted_dc/quant; but it got lost somewhere in the rounding dc_level+= (w->predicted_dc*divide_quant + (1<<12) )>>13; dsp_x8_put_solidcolor( av_clip_uint8((dc_level*dc_quant+4)>>3), s->dest[chroma], s->current_picture.f.linesize[!!chroma]); goto block_placed; } zeros_only = (dc_level == 0); } if(!chroma){ s->block[0][0] = dc_level*w->quant; }else{ s->block[0][0] = dc_level*w->quant_dc_chroma; } //there is !zero_only check in the original, but dc_level check is enough if( (unsigned int)(dc_level+1) >= 3 && (w->edges&3) != 3 ){ int direction; /*ac_comp_direction[orient] = { 0, 3, 3, 1, 1, 0, 0, 0, 2, 2, 2, 1 };<- -> 01'10' 10'10' 00'00' 00'01' 01'11' 11'00 =>0x6A017C */ direction= (0x6A017C>>(w->orient*2))&3; if (direction != 3){ x8_ac_compensation(w, direction, s->block[0][0]);//modify block_last[] } } if(w->flat_dc){ dsp_x8_put_solidcolor(w->predicted_dc, s->dest[chroma], s->current_picture.f.linesize[!!chroma]); }else{ w->dsp.spatial_compensation[w->orient]( s->edge_emu_buffer, s->dest[chroma], s->current_picture.f.linesize[!!chroma] ); } if(!zeros_only) s->dsp.idct_add ( s->dest[chroma], s->current_picture.f.linesize[!!chroma], s->block[0] ); block_placed: if(!chroma){ x8_update_predictions(w,w->orient,n); } if(s->loop_filter){ uint8_t* ptr = s->dest[chroma]; int linesize = s->current_picture.f.linesize[!!chroma]; if(!( (w->edges&2) || ( zeros_only && (w->orient|4)==4 ) )){ w->dsp.h_loop_filter(ptr, linesize, w->quant); } if(!( (w->edges&1) || ( zeros_only && (w->orient|8)==8 ) )){ w->dsp.v_loop_filter(ptr, linesize, w->quant); } } return 0; }


static int exif_scan_JPEG_header(image_info_type *ImageInfo TSRMLS_DC)
{
	int section, sn;
	int marker = 0, last_marker = M_PSEUDO, comment_correction=1;
	unsigned int ll, lh;
	uchar *Data;
	size_t fpos, size, got, itemlen;
	jpeg_sof_info  sof_info;

	for(section=0;;section++) {
#ifdef EXIF_DEBUG
		fpos = php_stream_tell(ImageInfo->infile);
		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Needing section %d @ 0x%08X", ImageInfo->file.count, fpos);
#endif

		/* get marker byte, swallowing possible padding                           */
		/* some software does not count the length bytes of COM section           */
		/* one company doing so is very much envolved in JPEG... so we accept too */
		if (last_marker==M_COM && comment_correction) {
			comment_correction = 2;
		}
		do {
			if ((marker = php_stream_getc(ImageInfo->infile)) == EOF) {
				EXIF_ERRLOG_CORRUPT(ImageInfo)
				return FALSE;
			}
			if (last_marker==M_COM && comment_correction>0) {
				if (marker!=0xFF) {
					marker = 0xff;
					comment_correction--;
				} else  {
					last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */
				}
			}
		} while (marker == 0xff);
		if (last_marker==M_COM && !comment_correction) {
			exif_error_docref("exif_read_data#error_mcom" EXIFERR_CC, ImageInfo, E_NOTICE, "Image has corrupt COM section: some software set wrong length information");
		}
		if (last_marker==M_COM && comment_correction)
			return M_EOI; /* ah illegal: char after COM section not 0xFF */

		fpos = php_stream_tell(ImageInfo->infile);

		if (marker == 0xff) {
			/* 0xff is legal padding, but if we get that many, something's wrong. */
			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "To many padding bytes");
			return FALSE;
		}

		/* Read the length of the section. */
		if ((lh = php_stream_getc(ImageInfo->infile)) == EOF) {
			EXIF_ERRLOG_CORRUPT(ImageInfo)
			return FALSE;
		}
		if ((ll = php_stream_getc(ImageInfo->infile)) == EOF) {
			EXIF_ERRLOG_CORRUPT(ImageInfo)
			return FALSE;
		}

		itemlen = (lh << 8) | ll;

		if (itemlen < 2) {
#ifdef EXIF_DEBUG
			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s, Section length: 0x%02X%02X", EXIF_ERROR_CORRUPT, lh, ll);
#else
			EXIF_ERRLOG_CORRUPT(ImageInfo)
#endif
			return FALSE;
		}

		sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, NULL);
		Data = ImageInfo->file.list[sn].data;

		/* Store first two pre-read bytes. */
		Data[0] = (uchar)lh;
		Data[1] = (uchar)ll;

		got = php_stream_read(ImageInfo->infile, (char*)(Data+2), itemlen-2); /* Read the whole section. */
		if (got != itemlen-2) {
			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error reading from file: got=x%04X(=%d) != itemlen-2=x%04X(=%d)", got, got, itemlen-2, itemlen-2);
			return FALSE;
		}

#ifdef EXIF_DEBUG
		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process section(x%02X=%s) @ x%04X + x%04X(=%d)", marker, exif_get_markername(marker), fpos, itemlen, itemlen);
#endif
		switch(marker) {
			case M_SOS:   /* stop before hitting compressed data  */
				/* If reading entire image is requested, read the rest of the data. */
				if (ImageInfo->read_all) {
					/* Determine how much file is left. */
					fpos = php_stream_tell(ImageInfo->infile);
					size = ImageInfo->FileSize - fpos;
					sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, NULL);
					Data = ImageInfo->file.list[sn].data;
					got = php_stream_read(ImageInfo->infile, (char*)Data, size);
					if (got != size) {
						EXIF_ERRLOG_FILEEOF(ImageInfo)
						return FALSE;
					}
				}
				return TRUE;

			case M_EOI:   /* in case it's a tables-only JPEG stream */
				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "No image in jpeg!");
				return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? TRUE : FALSE;

			case M_COM: /* Comment section */
				exif_process_COM(ImageInfo, (char *)Data, itemlen TSRMLS_CC);
				break;

			case M_EXIF:
				if (!(ImageInfo->sections_found&FOUND_IFD0)) {
					/*ImageInfo->sections_found |= FOUND_EXIF;*/
					/* Seen files from some 'U-lead' software with Vivitar scanner
					   that uses marker 31 later in the file (no clue what for!) */
					exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos TSRMLS_CC);
				}
				break;

			case M_APP12:
				exif_process_APP12(ImageInfo, (char *)Data, itemlen TSRMLS_CC);
				break;

			case M_SOF0:
			case M_SOF1:
			case M_SOF2:
			case M_SOF3:
			case M_SOF5:
			case M_SOF6:
			case M_SOF7:
			case M_SOF9:
			case M_SOF10:
			case M_SOF11:
			case M_SOF13:
			case M_SOF14:
			case M_SOF15:
				if ((itemlen - 2) < 6) {
					return FALSE;
				}

				exif_process_SOFn(Data, marker, &sof_info);
				ImageInfo->Width  = sof_info.width;
				ImageInfo->Height = sof_info.height;
				if (sof_info.num_components == 3) {
					ImageInfo->IsColor = 1;
				} else {
					ImageInfo->IsColor = 0;
				}
				break;
			default:
				/* skip any other marker silently. */
				break;
		}

		/* keep track of last marker */
		last_marker = marker;
	}
#ifdef EXIF_DEBUG
	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Done");
#endif
	return TRUE;
}


void pointZZ_pAdd(PointZZ_p * rop, const PointZZ_p * op1, const PointZZ_p * op2, const CurveZZ_p * curve) {
    mpz_t xdiff, ydiff, lambda;
    mpz_inits(xdiff, ydiff, lambda, NULL);

    // calculate lambda
    mpz_sub(ydiff, op2->y, op1->y);
    mpz_sub(xdiff, op2->x, op1->x);
    mpz_invert(xdiff, xdiff, curve->p);  // TODO check status
    mpz_mul(lambda, ydiff, xdiff);
    mpz_mod(lambda, lambda, curve->p);

    // calculate resulting x coord
    mpz_mul(rop->x, lambda, lambda);
    mpz_sub(rop->x, rop->x, op1->x);
    mpz_sub(rop->x, rop->x, op2->x);
    mpz_mod(rop->x, rop->x, curve->p);

    //calculate resulting y coord
    mpz_sub(rop->y, op1->x, rop->x);
    mpz_mul(rop->y, lambda, rop->y);
    mpz_sub(rop->y, rop->y, op1->y);
    mpz_mod(rop->y, rop->y, curve->p);

    mpz_clears(xdiff, ydiff, lambda, NULL);
}


mountpoint_last(struct nameidata *nd, struct path *path)
{
	int error = 0;
	struct dentry *dentry;
	struct dentry *dir = nd->path.dentry;

	/* If we're in rcuwalk, drop out of it to handle last component */
	if (nd->flags & LOOKUP_RCU) {
		if (unlazy_walk(nd, NULL)) {
			error = -ECHILD;
			goto out;
		}
	}

	nd->flags &= ~LOOKUP_PARENT;

	if (unlikely(nd->last_type != LAST_NORM)) {
		error = handle_dots(nd, nd->last_type);
		if (error)
			goto out;
		dentry = dget(nd->path.dentry);
		goto done;
	}

	mutex_lock(&dir->d_inode->i_mutex);
	dentry = d_lookup(dir, &nd->last);
	if (!dentry) {
		/*
		 * No cached dentry. Mounted dentries are pinned in the cache,
		 * so that means that this dentry is probably a symlink or the
		 * path doesn't actually point to a mounted dentry.
		 */
		dentry = d_alloc(dir, &nd->last);
		if (!dentry) {
			error = -ENOMEM;
			mutex_unlock(&dir->d_inode->i_mutex);
			goto out;
		}
		dentry = lookup_real(dir->d_inode, dentry, nd->flags);
		error = PTR_ERR(dentry);
		if (IS_ERR(dentry)) {
			mutex_unlock(&dir->d_inode->i_mutex);
			goto out;
		}
	}
	mutex_unlock(&dir->d_inode->i_mutex);

done:
	if (!dentry->d_inode || d_is_negative(dentry)) {
		error = -ENOENT;
		dput(dentry);
		goto out;
	}
	path->dentry = dentry;
	path->mnt = mntget(nd->path.mnt);
	if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW))
		return 1;
	follow_mount(path);
	error = 0;
out:
	terminate_walk(nd);
	return error;
}


static int avi_read_header(AVFormatContext *s) { AVIContext *avi = s->priv_data; AVIOContext *pb = s->pb; unsigned int tag, tag1, handler; int codec_type, stream_index, frame_period; unsigned int size; int i; AVStream *st; AVIStream *ast = NULL; int avih_width = 0, avih_height = 0; int amv_file_format = 0; uint64_t list_end = 0; int64_t pos; int ret; AVDictionaryEntry *dict_entry; avi->stream_index = -1; ret = get_riff(s, pb); if (ret < 0) return ret; av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml); avi->io_fsize = avi->fsize = avio_size(pb); if (avi->fsize <= 0 || avi->fsize < avi->riff_end) avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end; /* first list tag */ stream_index = -1; codec_type = -1; frame_period = 0; for (;;) { if (avio_feof(pb)) goto fail; tag = avio_rl32(pb); size = avio_rl32(pb); print_tag("tag", tag, size); switch (tag) { case MKTAG('L', 'I', 'S', 'T'): list_end = avio_tell(pb) + size; /* Ignored, except at start of video packets. */ tag1 = avio_rl32(pb); print_tag("list", tag1, 0); if (tag1 == MKTAG('m', 'o', 'v', 'i')) { avi->movi_list = avio_tell(pb) - 4; if (size) avi->movi_end = avi->movi_list + size + (size & 1); else avi->movi_end = avi->fsize; av_log(NULL, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end); goto end_of_header; } else if (tag1 == MKTAG('I', 'N', 'F', 'O')) ff_read_riff_info(s, size - 4); else if (tag1 == MKTAG('n', 'c', 'd', 't')) avi_read_nikon(s, list_end); break; case MKTAG('I', 'D', 'I', 'T'): { unsigned char date[64] = { 0 }; size += (size & 1); size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1)); avio_skip(pb, size); avi_metadata_creation_time(&s->metadata, date); break; case MKTAG('d', 'm', 'l', 'h'): avi->is_odml = 1; avio_skip(pb, size + (size & 1)); break; case MKTAG('a', 'm', 'v', 'h'): amv_file_format = 1; case MKTAG('a', 'v', 'i', 'h'): /* AVI header */ /* using frame_period is bad idea */ frame_period = avio_rl32(pb); avio_rl32(pb); /* max. bytes per second */ avio_rl32(pb); avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX; avio_skip(pb, 2 * 4); avio_rl32(pb); avio_rl32(pb); avih_width = avio_rl32(pb); avih_height = avio_rl32(pb); avio_skip(pb, size - 10 * 4); break; case MKTAG('s', 't', 'r', 'h'): /* stream header */ tag1 = avio_rl32(pb); handler = avio_rl32(pb); /* codec tag */ if (tag1 == MKTAG('p', 'a', 'd', 's')) { avio_skip(pb, size - 8); break; } else { stream_index++; st = avformat_new_stream(s, NULL); if (!st) goto fail; st->id = stream_index; ast = av_mallocz(sizeof(AVIStream)); if (!ast) goto fail; st->priv_data = ast; if (amv_file_format) tag1 = stream_index ? MKTAG('a', 'u', 'd', 's') : MKTAG('v', 'i', 'd', 's'); print_tag("strh", tag1, -1); if (tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')) { int64_t dv_dur; /* After some consideration -- I don't think we * have to support anything but DV in type1 AVIs. */ if (s->nb_streams != 1) goto fail; if (handler != MKTAG('d', 'v', 's', 'd') && handler != MKTAG('d', 'v', 'h', 'd') && handler != MKTAG('d', 'v', 's', 'l')) goto fail; ast = s->streams[0]->priv_data; av_freep(&s->streams[0]->codecpar->extradata); av_freep(&s->streams[0]->codecpar); #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS av_freep(&s->streams[0]->codec); FF_ENABLE_DEPRECATION_WARNINGS #endif if (s->streams[0]->info) av_freep(&s->streams[0]->info->duration_error); av_freep(&s->streams[0]->info); if (s->streams[0]->internal) av_freep(&s->streams[0]->internal->avctx); av_freep(&s->streams[0]->internal); av_freep(&s->streams[0]); s->nb_streams = 0; if (CONFIG_DV_DEMUXER) { avi->dv_demux = avpriv_dv_init_demux(s); if (!avi->dv_demux) goto fail; } else goto fail; s->streams[0]->priv_data = ast; avio_skip(pb, 3 * 4); ast->scale = avio_rl32(pb); ast->rate = avio_rl32(pb); avio_skip(pb, 4); /* start time */ dv_dur = avio_rl32(pb); if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) { dv_dur *= AV_TIME_BASE; s->duration = av_rescale(dv_dur, ast->scale, ast->rate); /* else, leave duration alone; timing estimation in utils.c * will make a guess based on bitrate. */ stream_index = s->nb_streams - 1; avio_skip(pb, size - 9 * 4); break; av_assert0(stream_index < s->nb_streams); ast->handler = handler; avio_rl32(pb); /* flags */ avio_rl16(pb); /* priority */ avio_rl16(pb); /* language */ avio_rl32(pb); /* initial frame */ ast->scale = avio_rl32(pb); ast->rate = avio_rl32(pb); if (!(ast->scale && ast->rate)) { av_log(s, AV_LOG_WARNING, "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. " "(This file has been generated by broken software.)\n", ast->scale, ast->rate); if (frame_period) { ast->rate = 1000000; ast->scale = frame_period; } else { ast->rate = 25; ast->scale = 1; avpriv_set_pts_info(st, 64, ast->scale, ast->rate); ast->cum_len = avio_rl32(pb); /* start */ st->nb_frames = avio_rl32(pb); st->start_time = 0; avio_rl32(pb); /* buffer size */ avio_rl32(pb); /* quality */ if (ast->cum_len*ast->scale/ast->rate > 3600) { av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n"); ast->cum_len = 0; ast->sample_size = avio_rl32(pb); ast->cum_len *= FFMAX(1, ast->sample_size); av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n", ast->rate, ast->scale, ast->sample_size); switch (tag1) { case MKTAG('v', 'i', 'd', 's'): codec_type = AVMEDIA_TYPE_VIDEO; ast->sample_size = 0; st->avg_frame_rate = av_inv_q(st->time_base); break; case MKTAG('a', 'u', 'd', 's'): codec_type = AVMEDIA_TYPE_AUDIO; break; case MKTAG('t', 'x', 't', 's'): codec_type = AVMEDIA_TYPE_SUBTITLE; break; case MKTAG('d', 'a', 't', 's'): codec_type = AVMEDIA_TYPE_DATA; break; default: av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1); if (ast->sample_size < 0) { if (s->error_recognition & AV_EF_EXPLODE) { av_log(s, AV_LOG_ERROR, "Invalid sample_size %d at stream %d\n", ast->sample_size, stream_index); goto fail; av_log(s, AV_LOG_WARNING, "Invalid sample_size %d at stream %d " "setting it to 0\n", ast->sample_size, stream_index); ast->sample_size = 0; if (ast->sample_size == 0) { st->duration = st->nb_frames; if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) { av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n"); st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end); ast->frame_offset = ast->cum_len; avio_skip(pb, size - 12 * 4); break; case MKTAG('s', 't', 'r', 'f'): /* stream header */ if (!size) break; if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) { avio_skip(pb, size); } else { uint64_t cur_pos = avio_tell(pb); unsigned esize; if (cur_pos < list_end) size = FFMIN(size, list_end - cur_pos); st = s->streams[stream_index]; if (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN) { avio_skip(pb, size); break; switch (codec_type) { case AVMEDIA_TYPE_VIDEO: if (amv_file_format) { st->codecpar->width = avih_width; st->codecpar->height = avih_height; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_AMV; avio_skip(pb, size); break; tag1 = ff_get_bmp_header(pb, st, &esize); if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D', 'X', 'S', 'A')) { st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; st->codecpar->codec_tag = tag1; st->codecpar->codec_id = AV_CODEC_ID_XSUB; break; if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) { if (esize == size-1 && (esize&1)) { st->codecpar->extradata_size = esize - 10 * 4; } else st->codecpar->extradata_size = size - 10 * 4; if (ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); // FIXME: check if the encoder really did this correctly if (st->codecpar->extradata_size & 1) avio_r8(pb); /* Extract palette from extradata if bpp <= 8. * This code assumes that extradata contains only palette. * This is true for all paletted codecs implemented in * FFmpeg. */ if (st->codecpar->extradata_size && (st->codecpar->bits_per_coded_sample <= 8)) { int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2; const uint8_t *pal_src; pal_size = FFMIN(pal_size, st->codecpar->extradata_size); pal_src = st->codecpar->extradata + st->codecpar->extradata_size - pal_size; /* Exclude the "BottomUp" field from the palette */ if (pal_src - st->codecpar->extradata >= 9 && !memcmp(st->codecpar->extradata + st->codecpar->extradata_size - 9, "BottomUp", 9)) pal_src -= 9; for (i = 0; i < pal_size / 4; i++) ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i); ast->has_pal = 1; print_tag("video", tag1, 0); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_tag = tag1; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1); /* If codec is not found yet, try with the mov tags. */ if (!st->codecpar->codec_id) { char tag_buf[32]; av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1); st->codecpar->codec_id = ff_codec_get_id(ff_codec_movvideo_tags, tag1); if (st->codecpar->codec_id) av_log(s, AV_LOG_WARNING, "mov tag found in avi (fourcc %s)\n", tag_buf); /* This is needed to get the pict type which is necessary * for generating correct pts. */ st->need_parsing = AVSTREAM_PARSE_HEADERS; if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 && ast->handler == MKTAG('X', 'V', 'I', 'D')) st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D'); if (st->codecpar->codec_tag == MKTAG('V', 'S', 'S', 'H')) st->need_parsing = AVSTREAM_PARSE_FULL; if (st->codecpar->codec_id == AV_CODEC_ID_RV40) st->need_parsing = AVSTREAM_PARSE_NONE; if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 && st->codecpar->extradata_size < 1U << 30) { st->codecpar->extradata_size += 9; if ((ret = av_reallocp(&st->codecpar->extradata, st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE)) < 0) { st->codecpar->extradata_size = 0; return ret; } else memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9, "BottomUp", 9); st->codecpar->height = FFABS(st->codecpar->height); // avio_skip(pb, size - 5 * 4); break; case AVMEDIA_TYPE_AUDIO: ret = ff_get_wav_header(s, pb, st->codecpar, size, 0); if (ret < 0) return ret; ast->dshow_block_align = st->codecpar->block_align; if (ast->sample_size && st->codecpar->block_align && ast->sample_size != st->codecpar->block_align) { av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codecpar->block_align); ast->sample_size = st->codecpar->block_align; /* 2-aligned * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */ if (size & 1) avio_skip(pb, 1); /* Force parsing as several audio frames can be in * one packet and timestamps refer to packet start. */ st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; /* ADTS header is in extradata, AAC without header must be * stored as exact frames. Parser not needed and it will * fail. */ if (st->codecpar->codec_id == AV_CODEC_ID_AAC && st->codecpar->extradata_size) st->need_parsing = AVSTREAM_PARSE_NONE; // The flac parser does not work with AVSTREAM_PARSE_TIMESTAMPS if (st->codecpar->codec_id == AV_CODEC_ID_FLAC) st->need_parsing = AVSTREAM_PARSE_NONE; /* AVI files with Xan DPCM audio (wrongly) declare PCM * audio in the header but have Axan as stream_code_tag. */ if (ast->handler == AV_RL32("Axan")) { st->codecpar->codec_id = AV_CODEC_ID_XAN_DPCM; st->codecpar->codec_tag = 0; ast->dshow_block_align = 0; if (amv_file_format) { st->codecpar->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV; ast->dshow_block_align = 0; if ((st->codecpar->codec_id == AV_CODEC_ID_AAC || st->codecpar->codec_id == AV_CODEC_ID_FLAC || st->codecpar->codec_id == AV_CODEC_ID_MP2 ) && ast->dshow_block_align <= 4 && ast->dshow_block_align) { av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align); ast->dshow_block_align = 0; if (st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 || st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 || st->codecpar->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) { av_log(s, AV_LOG_DEBUG, "overriding sample_size\n"); ast->sample_size = 0; break; case AVMEDIA_TYPE_SUBTITLE: st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; st->request_probe= 1; avio_skip(pb, size); break; default: st->codecpar->codec_type = AVMEDIA_TYPE_DATA; st->codecpar->codec_id = AV_CODEC_ID_NONE; st->codecpar->codec_tag = 0; avio_skip(pb, size); break; break; case MKTAG('s', 't', 'r', 'd'): if (stream_index >= (unsigned)s->nb_streams || s->streams[stream_index]->codecpar->extradata_size || s->streams[stream_index]->codecpar->codec_tag == MKTAG('H','2','6','4')) { avio_skip(pb, size); } else { uint64_t cur_pos = avio_tell(pb); if (cur_pos < list_end) size = FFMIN(size, list_end - cur_pos); st = s->streams[stream_index]; if (size<(1<<30)) { av_log(s, AV_LOG_WARNING, "New extradata in strd chunk, freeing previous one.\n"); if (ff_get_extradata(s, st->codecpar, pb, size) < 0) return AVERROR(ENOMEM); if (st->codecpar->extradata_size & 1) //FIXME check if the encoder really did this correctly avio_r8(pb); ret = avi_extract_stream_metadata(s, st); if (ret < 0) { av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n"); break; case MKTAG('i', 'n', 'd', 'x'): pos = avio_tell(pb); if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml && read_braindead_odml_indx(s, 0) < 0 && (s->error_recognition & AV_EF_EXPLODE)) goto fail; avio_seek(pb, pos + size, SEEK_SET); break; case MKTAG('v', 'p', 'r', 'p'): if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) { AVRational active, active_aspect; st = s->streams[stream_index]; avio_rl32(pb); avio_rl32(pb); avio_rl32(pb); avio_rl32(pb); avio_rl32(pb); active_aspect.den = avio_rl16(pb); active_aspect.num = avio_rl16(pb); active.num = avio_rl32(pb); active.den = avio_rl32(pb); avio_rl32(pb); // nbFieldsPerFrame if (active_aspect.num && active_aspect.den && active.num && active.den) { st->sample_aspect_ratio = av_div_q(active_aspect, active); av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den); size -= 9 * 4; avio_skip(pb, size); break; case MKTAG('s', 't', 'r', 'n'): if (s->nb_streams) { ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size); if (ret < 0) return ret; break; default: if (size > 1000000) { char tag_buf[32]; av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag); av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, " "tag %s has size %u, " "I will ignore it and try to continue anyway.\n", tag_buf, size); if (s->error_recognition & AV_EF_EXPLODE) goto fail; avi->movi_list = avio_tell(pb) - 4; avi->movi_end = avi->fsize; goto end_of_header; /* Do not fail for very large idx1 tags */ case MKTAG('i', 'd', 'x', '1'): /* skip tag */ size += (size & 1); avio_skip(pb, size); break; end_of_header: /* check stream number */ if (stream_index != s->nb_streams - 1) { fail: return AVERROR_INVALIDDATA; if (!avi->index_loaded && pb->seekable) avi_load_index(s); calculate_bitrate(s); avi->index_loaded |= 1; if ((ret = guess_ni_flag(s)) < 0) return ret; avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS); dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0); if (dict_entry && !strcmp(dict_entry->value, "PotEncoder")) for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if ( st->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO || st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) st->need_parsing = AVSTREAM_PARSE_FULL; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->nb_index_entries) break; // DV-in-AVI cannot be non-interleaved, if set this must be // a mis-detection. if (avi->dv_demux) avi->non_interleaved = 0; if (i == s->nb_streams && avi->non_interleaved) { av_log(s, AV_LOG_WARNING, "Non-interleaved AVI without index, switching to interleaved\n"); avi->non_interleaved = 0; if (avi->non_interleaved) { av_log(s, AV_LOG_INFO, "non-interleaved AVI\n"); clean_index(s); ff_metadata_conv_ctx(s, NULL, avi_metadata_conv); ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv); return 0;


static inline float to_float(uint8_t exp, int16_t mantissa) { return ((float) (mantissa * scale_factors[exp])); }


static void cirrus_mmio_blt_write ( CirrusVGAState * s , unsigned address , uint8_t value ) {
 trace_vga_cirrus_write_blt ( address , value ) ;
 switch ( address ) {
 case ( CIRRUS_MMIO_BLTBGCOLOR + 0 ) : cirrus_vga_write_gr ( s , 0x00 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTBGCOLOR + 1 ) : cirrus_vga_write_gr ( s , 0x10 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTBGCOLOR + 2 ) : cirrus_vga_write_gr ( s , 0x12 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTBGCOLOR + 3 ) : cirrus_vga_write_gr ( s , 0x14 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTFGCOLOR + 0 ) : cirrus_vga_write_gr ( s , 0x01 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTFGCOLOR + 1 ) : cirrus_vga_write_gr ( s , 0x11 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTFGCOLOR + 2 ) : cirrus_vga_write_gr ( s , 0x13 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTFGCOLOR + 3 ) : cirrus_vga_write_gr ( s , 0x15 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTWIDTH + 0 ) : cirrus_vga_write_gr ( s , 0x20 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTWIDTH + 1 ) : cirrus_vga_write_gr ( s , 0x21 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTHEIGHT + 0 ) : cirrus_vga_write_gr ( s , 0x22 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTHEIGHT + 1 ) : cirrus_vga_write_gr ( s , 0x23 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTDESTPITCH + 0 ) : cirrus_vga_write_gr ( s , 0x24 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTDESTPITCH + 1 ) : cirrus_vga_write_gr ( s , 0x25 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTSRCPITCH + 0 ) : cirrus_vga_write_gr ( s , 0x26 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTSRCPITCH + 1 ) : cirrus_vga_write_gr ( s , 0x27 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTDESTADDR + 0 ) : cirrus_vga_write_gr ( s , 0x28 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTDESTADDR + 1 ) : cirrus_vga_write_gr ( s , 0x29 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTDESTADDR + 2 ) : cirrus_vga_write_gr ( s , 0x2a , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTDESTADDR + 3 ) : break ;
 case ( CIRRUS_MMIO_BLTSRCADDR + 0 ) : cirrus_vga_write_gr ( s , 0x2c , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTSRCADDR + 1 ) : cirrus_vga_write_gr ( s , 0x2d , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTSRCADDR + 2 ) : cirrus_vga_write_gr ( s , 0x2e , value ) ;
 break ;
 case CIRRUS_MMIO_BLTWRITEMASK : cirrus_vga_write_gr ( s , 0x2f , value ) ;
 break ;
 case CIRRUS_MMIO_BLTMODE : cirrus_vga_write_gr ( s , 0x30 , value ) ;
 break ;
 case CIRRUS_MMIO_BLTROP : cirrus_vga_write_gr ( s , 0x32 , value ) ;
 break ;
 case CIRRUS_MMIO_BLTMODEEXT : cirrus_vga_write_gr ( s , 0x33 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTTRANSPARENTCOLOR + 0 ) : cirrus_vga_write_gr ( s , 0x34 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTTRANSPARENTCOLOR + 1 ) : cirrus_vga_write_gr ( s , 0x35 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK + 0 ) : cirrus_vga_write_gr ( s , 0x38 , value ) ;
 break ;
 case ( CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK + 1 ) : cirrus_vga_write_gr ( s , 0x39 , value ) ;
 break ;
 case CIRRUS_MMIO_BLTSTATUS : cirrus_vga_write_gr ( s , 0x31 , value ) ;
 break ;
 default : # ifdef DEBUG_CIRRUS printf ( "cirrus: mmio write - addr 0x%04x val 0x%02x (ignored)\n" , address , value ) ;
 # endif break ;
 }
 }


static int svq1_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; MpegEncContext *s=avctx->priv_data; uint8_t *current, *previous; int result, i, x, y, width, height; AVFrame *pict = data; svq1_pmv *pmv; /* initialize bit buffer */ init_get_bits(&s->gb,buf,buf_size*8); /* decode frame header */ s->f_code = get_bits (&s->gb, 22); if ((s->f_code & ~0x70) || !(s->f_code & 0x60)) return -1; /* swap some header bytes (why?) */ if (s->f_code != 0x20) { uint32_t *src = (uint32_t *) (buf + 4); for (i=0; i < 4; i++) { src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i]; } } result = svq1_decode_frame_header (&s->gb, s); if (result != 0) { av_dlog(s->avctx, "Error in svq1_decode_frame_header %i\n",result); return result; } //FIXME this avoids some confusion for "B frames" without 2 references //this should be removed after libavcodec can handle more flexible picture types & ordering if(s->pict_type==AV_PICTURE_TYPE_B && s->last_picture_ptr==NULL) return buf_size; if( (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==AV_PICTURE_TYPE_B) ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=AV_PICTURE_TYPE_I) || avctx->skip_frame >= AVDISCARD_ALL) return buf_size; if(MPV_frame_start(s, avctx) < 0) return -1; pmv = av_malloc((FFALIGN(s->width, 16)/8 + 3) * sizeof(*pmv)); if (!pmv) return -1; /* decode y, u and v components */ for (i=0; i < 3; i++) { int linesize; if (i == 0) { width = FFALIGN(s->width, 16); height = FFALIGN(s->height, 16); linesize= s->linesize; } else { if(s->flags&CODEC_FLAG_GRAY) break; width = FFALIGN(s->width/4, 16); height = FFALIGN(s->height/4, 16); linesize= s->uvlinesize; } current = s->current_picture.f.data[i]; if(s->pict_type==AV_PICTURE_TYPE_B){ previous = s->next_picture.f.data[i]; }else{ previous = s->last_picture.f.data[i]; } if (s->pict_type == AV_PICTURE_TYPE_I) { /* keyframe */ for (y=0; y < height; y+=16) { for (x=0; x < width; x+=16) { result = svq1_decode_block_intra (&s->gb, &current[x], linesize); if (result != 0) { av_log(s->avctx, AV_LOG_INFO, "Error in svq1_decode_block %i (keyframe)\n",result); goto err; } } current += 16*linesize; } } else { /* delta frame */ memset (pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv)); for (y=0; y < height; y+=16) { for (x=0; x < width; x+=16) { result = svq1_decode_delta_block (s, &s->gb, &current[x], previous, linesize, pmv, x, y); if (result != 0) { av_dlog(s->avctx, "Error in svq1_decode_delta_block %i\n",result); goto err; } } pmv[0].x = pmv[0].y = 0; current += 16*linesize; } } } *pict = *(AVFrame*)&s->current_picture; MPV_frame_end(s); *data_size=sizeof(AVFrame); result = buf_size; err: av_free(pmv); return result; }


PHPAPI void  php_pcre_grep_impl(pcre_cache_entry *pce, zval *input, zval *return_value, long flags TSRMLS_DC) /* {{{ */
{
	zval		   **entry;				/* An entry in the input array */
	pcre_extra		*extra = pce->extra;/* Holds results of studying */
	pcre_extra		 extra_data;		/* Used locally for exec options */
	int				*offsets;			/* Array of subpattern offsets */
	int				 size_offsets;		/* Size of the offsets array */
	int				 count = 0;			/* Count of matched subpatterns */
	char			*string_key;
	ulong			 num_key;
	zend_bool		 invert;			/* Whether to return non-matching
										   entries */
	int				 rc;

	invert = flags & PREG_GREP_INVERT ? 1 : 0;

	if (extra == NULL) {
		extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
		extra = &extra_data;
	}
	extra->match_limit = PCRE_G(backtrack_limit);
	extra->match_limit_recursion = PCRE_G(recursion_limit);

	/* Calculate the size of the offsets array, and allocate memory for it. */
	rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &size_offsets);
	if (rc < 0) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
		RETURN_FALSE;
	}
	size_offsets = (size_offsets + 1) * 3;
	offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);

	/* Initialize return array */
	array_init(return_value);

	PCRE_G(error_code) = PHP_PCRE_NO_ERROR;

	/* Go through the input array */
	zend_hash_internal_pointer_reset(Z_ARRVAL_P(input));
	while (zend_hash_get_current_data(Z_ARRVAL_P(input), (void **)&entry) == SUCCESS) {
		zval subject = **entry;

		if (Z_TYPE_PP(entry) != IS_STRING) {
			zval_copy_ctor(&subject);
			convert_to_string(&subject);
		}

		/* Perform the match */
		count = pcre_exec(pce->re, extra, Z_STRVAL(subject),
						  Z_STRLEN(subject), 0,
						  0, offsets, size_offsets);

		/* Check for too many substrings condition. */
		if (count == 0) {
			php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Matched, but too many substrings");
			count = size_offsets/3;
		} else if (count < 0 && count != PCRE_ERROR_NOMATCH) {
			pcre_handle_exec_error(count TSRMLS_CC);
			break;
		}

		/* If the entry fits our requirements */
		if ((count > 0 && !invert) || (count == PCRE_ERROR_NOMATCH && invert)) {

			Z_ADDREF_PP(entry);

			/* Add to return array */
			switch (zend_hash_get_current_key(Z_ARRVAL_P(input), &string_key, &num_key, 0))
			{
				case HASH_KEY_IS_STRING:
					zend_hash_update(Z_ARRVAL_P(return_value), string_key,
									 strlen(string_key)+1, entry, sizeof(zval *), NULL);
					break;

				case HASH_KEY_IS_LONG:
					zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry,
										   sizeof(zval *), NULL);
					break;
			}
		}

		if (Z_TYPE_PP(entry) != IS_STRING) {
			zval_dtor(&subject);
		}

		zend_hash_move_forward(Z_ARRVAL_P(input));
	}
	zend_hash_internal_pointer_reset(Z_ARRVAL_P(input));
	/* Clean up */
	efree(offsets);
}