static void h225_stat_init ( stat_tap_table_ui * new_stat , new_stat_tap_gui_init_cb gui_callback , void * gui_data ) {
 int num_fields = sizeof ( h225_stat_fields ) / sizeof ( stat_tap_table_item ) ;
 stat_tap_table * table = new_stat_tap_init_table ( "H.225 Messages and Message Reasons" , num_fields , 0 , NULL , gui_callback , gui_data ) ;
 int row_idx = 0 , msg_idx ;
 stat_tap_table_item_type items [ sizeof ( h225_stat_fields ) / sizeof ( stat_tap_table_item ) ] ;
 new_stat_tap_add_table ( new_stat , table ) ;
 items [ MESSAGE_TYPE_COLUMN ] . type = TABLE_ITEM_STRING ;
 items [ COUNT_COLUMN ] . type = TABLE_ITEM_UINT ;
 items [ COUNT_COLUMN ] . value . uint_value = 0 ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = h225_RasMessage_vals [ msg_idx ] . strptr ? h225_RasMessage_vals [ msg_idx ] . strptr : "Unknown RAS message" ;
 ras_msg_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( h225_RasMessage_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = T_h323_message_body_vals [ msg_idx ] . strptr ? T_h323_message_body_vals [ msg_idx ] . strptr : "Unknown CS message" ;
 cs_msg_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( T_h323_message_body_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = GatekeeperRejectReason_vals [ msg_idx ] . strptr ? GatekeeperRejectReason_vals [ msg_idx ] . strptr : "Unknown gatekeeper reject reason" ;
 grj_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( GatekeeperRejectReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = RegistrationRejectReason_vals [ msg_idx ] . strptr ? RegistrationRejectReason_vals [ msg_idx ] . strptr : "Unknown registration reject reason" ;
 rrj_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( RegistrationRejectReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = UnregRequestReason_vals [ msg_idx ] . strptr ? UnregRequestReason_vals [ msg_idx ] . strptr : "Unknown unregistration request reason" ;
 urq_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( UnregRequestReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = UnregRejectReason_vals [ msg_idx ] . strptr ? UnregRejectReason_vals [ msg_idx ] . strptr : "Unknown unregistration reject reason" ;
 urj_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( UnregRejectReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = AdmissionRejectReason_vals [ msg_idx ] . strptr ? AdmissionRejectReason_vals [ msg_idx ] . strptr : "Unknown admission reject reason" ;
 arj_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( AdmissionRejectReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = BandRejectReason_vals [ msg_idx ] . strptr ? BandRejectReason_vals [ msg_idx ] . strptr : "Unknown band reject reason" ;
 brj_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( BandRejectReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = DisengageReason_vals [ msg_idx ] . strptr ? DisengageReason_vals [ msg_idx ] . strptr : "Unknown disengage reason" ;
 drq_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( DisengageReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = DisengageRejectReason_vals [ msg_idx ] . strptr ? DisengageRejectReason_vals [ msg_idx ] . strptr : "Unknown disengage reject reason" ;
 drj_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( DisengageRejectReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = LocationRejectReason_vals [ msg_idx ] . strptr ? LocationRejectReason_vals [ msg_idx ] . strptr : "Unknown location reject reason" ;
 lrj_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( LocationRejectReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = InfoRequestNakReason_vals [ msg_idx ] . strptr ? InfoRequestNakReason_vals [ msg_idx ] . strptr : "Unknown info request nak reason" ;
 irqnak_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( InfoRequestNakReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = h225_ReleaseCompleteReason_vals [ msg_idx ] . strptr ? h225_ReleaseCompleteReason_vals [ msg_idx ] . strptr : "Unknown release complete reason" ;
 rel_cmp_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( h225_ReleaseCompleteReason_vals [ msg_idx ] . strptr ) ;
 msg_idx = 0 ;
 do {
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = FacilityReason_vals [ msg_idx ] . strptr ? FacilityReason_vals [ msg_idx ] . strptr : "Unknown facility reason" ;
 facility_reason_idx [ msg_idx ] = row_idx ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 row_idx ++ ;
 msg_idx ++ ;
 }
 while ( FacilityReason_vals [ msg_idx ] . strptr ) ;
 items [ MESSAGE_TYPE_COLUMN ] . value . string_value = "Unknown H.225 message" ;
 new_stat_tap_init_table_row ( table , row_idx , num_fields , items ) ;
 other_idx = row_idx ;
 }


int user_update(struct key *key, const void *data, size_t datalen)
{
	struct user_key_payload *upayload, *zap;
	int ret;

	ret = -EINVAL;
	if (datalen <= 0 || datalen > 32767 || !data)
		goto error;

	/* construct a replacement payload */
	ret = -ENOMEM;
	upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL);
	if (!upayload)
		goto error;

	upayload->datalen = datalen;
	memcpy(upayload->data, data, datalen);

	/* check the quota and attach the new data */
	zap = upayload;

	ret = key_payload_reserve(key, datalen);

	if (ret == 0) {
		/* attach the new data, displacing the old */
		zap = key->payload.data;
		rcu_assign_pointer(key->payload.data, upayload);
		key->expiry = 0;
	}

	kfree_rcu(zap, rcu);

error:
	return ret;
}


static jas_image_cmpt_t * jas_image_cmpt_create ( uint_fast32_t tlx , uint_fast32_t tly , uint_fast32_t hstep , uint_fast32_t vstep , uint_fast32_t width , uint_fast32_t height , uint_fast16_t depth , bool sgnd , uint_fast32_t inmem ) {
 jas_image_cmpt_t * cmpt ;
 long size ;
 if ( ! ( cmpt = jas_malloc ( sizeof ( jas_image_cmpt_t ) ) ) ) {
 return 0 ;
 }
 cmpt -> type_ = JAS_IMAGE_CT_UNKNOWN ;
 cmpt -> tlx_ = tlx ;
 cmpt -> tly_ = tly ;
 cmpt -> hstep_ = hstep ;
 cmpt -> vstep_ = vstep ;
 cmpt -> width_ = width ;
 cmpt -> height_ = height ;
 cmpt -> prec_ = depth ;
 cmpt -> sgnd_ = sgnd ;
 cmpt -> stream_ = 0 ;
 cmpt -> cps_ = ( depth + 7 ) / 8 ;
 size = cmpt -> width_ * cmpt -> height_ * cmpt -> cps_ ;
 cmpt -> stream_ = ( inmem ) ? jas_stream_memopen ( 0 , size ) : jas_stream_tmpfile ( ) ;
 if ( ! cmpt -> stream_ ) {
 jas_image_cmpt_destroy ( cmpt ) ;
 return 0 ;
 }
 if ( jas_stream_seek ( cmpt -> stream_ , size - 1 , SEEK_SET ) < 0 || jas_stream_putc ( cmpt -> stream_ , 0 ) == EOF || jas_stream_seek ( cmpt -> stream_ , 0 , SEEK_SET ) < 0 ) {
 jas_image_cmpt_destroy ( cmpt ) ;
 return 0 ;
 }
 return cmpt ;
 }


    protected final GF2Polynomial[] invertMatrix(GF2Polynomial[] matrix)
    {
        GF2Polynomial[] a = new GF2Polynomial[matrix.length];
        GF2Polynomial[] inv = new GF2Polynomial[matrix.length];
        GF2Polynomial dummy;
        int i, j;
        // initialize a as a copy of matrix and inv as E(inheitsmatrix)
        for (i = 0; i < mDegree; i++)
        {
            try
            {
                a[i] = new GF2Polynomial(matrix[i]);
                inv[i] = new GF2Polynomial(mDegree);
                inv[i].setBit(mDegree - 1 - i);
            }
            catch (RuntimeException BDNEExc)
            {
                BDNEExc.printStackTrace();
            }
        }
        // construct triangle matrix so that for each a[i] the first i bits are
        // zero
        for (i = 0; i < mDegree - 1; i++)
        {
            // find column where bit i is set
            j = i;
            while ((j < mDegree) && !a[j].testBit(mDegree - 1 - i))
            {
                j++;
            }
            if (j >= mDegree)
            {
                throw new RuntimeException(
                    "GF2nField.invertMatrix: Matrix cannot be inverted!");
            }
            if (i != j)
            { // swap a[i]/a[j] and inv[i]/inv[j]
                dummy = a[i];
                a[i] = a[j];
                a[j] = dummy;
                dummy = inv[i];
                inv[i] = inv[j];
                inv[j] = dummy;
            }
            for (j = i + 1; j < mDegree; j++)
            { // add column i to all columns>i
                // having their i-th bit set
                if (a[j].testBit(mDegree - 1 - i))
                {
                    a[j].addToThis(a[i]);
                    inv[j].addToThis(inv[i]);
                }
            }
        }
        // construct Einheitsmatrix from a
        for (i = mDegree - 1; i > 0; i--)
        {
            for (j = i - 1; j >= 0; j--)
            { // eliminate the i-th bit in all
                // columns < i
                if (a[j].testBit(mDegree - 1 - i))
                {
                    a[j].addToThis(a[i]);
                    inv[j].addToThis(inv[i]);
                }
            }
        }
        return inv;
    }


static int dissect_h225_FastStart ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence_of ( tvb , offset , actx , tree , hf_index , ett_h225_FastStart , FastStart_sequence_of ) ;
 return offset ;
 }


void CSecurityTLS::shutdown(bool needbye)
{
  if (session && needbye)
    if (gnutls_bye(session, GNUTLS_SHUT_RDWR) != GNUTLS_E_SUCCESS)
      vlog.error("gnutls_bye failed");

  if (anon_cred) {
    gnutls_anon_free_client_credentials(anon_cred);
    anon_cred = 0;
  }

  if (cert_cred) {
    gnutls_certificate_free_credentials(cert_cred);
    cert_cred = 0;
  }

  if (session) {
    gnutls_deinit(session);
    session = 0;

    gnutls_global_deinit();
  }
}


static void parse_error(JSONParserContext *ctxt, QObject *token, const char *msg, ...) { fprintf(stderr, "parse error: %s\n", msg); }


void kvm_arch_update_guest_debug(CPUState *env, struct kvm_guest_debug *dbg) { const uint8_t type_code[] = { [GDB_BREAKPOINT_HW] = 0x0, [GDB_WATCHPOINT_WRITE] = 0x1, [GDB_WATCHPOINT_ACCESS] = 0x3 }; const uint8_t len_code[] = { [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2 }; int n; if (kvm_sw_breakpoints_active(env)) dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP; if (nb_hw_breakpoint > 0) { dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP; dbg->arch.debugreg[7] = 0x0600; for (n = 0; n < nb_hw_breakpoint; n++) { dbg->arch.debugreg[n] = hw_breakpoint[n].addr; dbg->arch.debugreg[7] |= (2 << (n * 2)) | (type_code[hw_breakpoint[n].type] << (16 + n*4)) | ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4)); } } /* Legal xcr0 for loading */ env->xcr0 = 1; }


static int iwl_process_add_sta_resp(struct iwl_priv *priv,
				    struct iwl_addsta_cmd *addsta,
				    struct iwl_rx_packet *pkt)
{
	u8 sta_id = addsta->sta.sta_id;
	unsigned long flags;
	int ret = -EIO;

	if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) {
		IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n",
			pkt->hdr.flags);
		return ret;
	}

	IWL_DEBUG_INFO(priv, "Processing response for adding station %u\n",
		       sta_id);

	spin_lock_irqsave(&priv->shrd->sta_lock, flags);

	switch (pkt->u.add_sta.status) {
	case ADD_STA_SUCCESS_MSK:
		IWL_DEBUG_INFO(priv, "REPLY_ADD_STA PASSED\n");
		iwl_sta_ucode_activate(priv, sta_id);
		ret = 0;
		break;
	case ADD_STA_NO_ROOM_IN_TABLE:
		IWL_ERR(priv, "Adding station %d failed, no room in table.\n",
			sta_id);
		break;
	case ADD_STA_NO_BLOCK_ACK_RESOURCE:
		IWL_ERR(priv, "Adding station %d failed, no block ack "
			"resource.\n", sta_id);
		break;
	case ADD_STA_MODIFY_NON_EXIST_STA:
		IWL_ERR(priv, "Attempting to modify non-existing station %d\n",
			sta_id);
		break;
	default:
		IWL_DEBUG_ASSOC(priv, "Received REPLY_ADD_STA:(0x%08X)\n",
				pkt->u.add_sta.status);
		break;
	}

	IWL_DEBUG_INFO(priv, "%s station id %u addr %pM\n",
		       priv->stations[sta_id].sta.mode ==
		       STA_CONTROL_MODIFY_MSK ?  "Modified" : "Added",
		       sta_id, priv->stations[sta_id].sta.sta.addr);

	/*
	 * XXX: The MAC address in the command buffer is often changed from
	 * the original sent to the device. That is, the MAC address
	 * written to the command buffer often is not the same MAC address
	 * read from the command buffer when the command returns. This
	 * issue has not yet been resolved and this debugging is left to
	 * observe the problem.
	 */
	IWL_DEBUG_INFO(priv, "%s station according to cmd buffer %pM\n",
		       priv->stations[sta_id].sta.mode ==
		       STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
		       addsta->sta.addr);
	spin_unlock_irqrestore(&priv->shrd->sta_lock, flags);

	return ret;
}


static int iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id)
{
	if (sta_id >= IWLAGN_STATION_COUNT) {
		IWL_ERR(priv, "invalid sta_id %u", sta_id);
		return -EINVAL;
	}
	if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE))
		IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u "
			"addr %pM\n",
			sta_id, priv->stations[sta_id].sta.sta.addr);

	if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) {
		IWL_DEBUG_ASSOC(priv,
				"STA id %u addr %pM already present in uCode "
				"(according to driver)\n",
				sta_id, priv->stations[sta_id].sta.sta.addr);
	} else {
		priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE;
		IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n",
				sta_id, priv->stations[sta_id].sta.sta.addr);
	}
	return 0;
}


void SSecurityTLS::shutdown()
{
  if (session) {
    if (gnutls_bye(session, GNUTLS_SHUT_RDWR) != GNUTLS_E_SUCCESS) {
      /* FIXME: Treat as non-fatal error */
      vlog.error("TLS session wasn't terminated gracefully");
    }
  }

  if (dh_params) {
    gnutls_dh_params_deinit(dh_params);
    dh_params = 0;
  }

  if (anon_cred) {
    gnutls_anon_free_server_credentials(anon_cred);
    anon_cred = 0;
  }

  if (cert_cred) {
    gnutls_certificate_free_credentials(cert_cred);
    cert_cred = 0;
  }

  if (session) {
    gnutls_deinit(session);
    session = 0;

    gnutls_global_deinit();
  }
}


static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
	struct cftype *cft, struct eventfd_ctx *eventfd)
{
	struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
	struct mem_cgroup_thresholds *thresholds;
	struct mem_cgroup_threshold_ary *new;
	int type = MEMFILE_TYPE(cft->private);
	u64 usage;
	int i, j, size;

	mutex_lock(&memcg->thresholds_lock);
	if (type == _MEM)
		thresholds = &memcg->thresholds;
	else if (type == _MEMSWAP)
		thresholds = &memcg->memsw_thresholds;
	else
		BUG();

	/*
	 * Something went wrong if we trying to unregister a threshold
	 * if we don't have thresholds
	 */
	BUG_ON(!thresholds);

	if (!thresholds->primary)
		goto unlock;

	usage = mem_cgroup_usage(memcg, type == _MEMSWAP);

	/* Check if a threshold crossed before removing */
	__mem_cgroup_threshold(memcg, type == _MEMSWAP);

	/* Calculate new number of threshold */
	size = 0;
	for (i = 0; i < thresholds->primary->size; i++) {
		if (thresholds->primary->entries[i].eventfd != eventfd)
			size++;
	}

	new = thresholds->spare;

	/* Set thresholds array to NULL if we don't have thresholds */
	if (!size) {
		kfree(new);
		new = NULL;
		goto swap_buffers;
	}

	new->size = size;

	/* Copy thresholds and find current threshold */
	new->current_threshold = -1;
	for (i = 0, j = 0; i < thresholds->primary->size; i++) {
		if (thresholds->primary->entries[i].eventfd == eventfd)
			continue;

		new->entries[j] = thresholds->primary->entries[i];
		if (new->entries[j].threshold < usage) {
			/*
			 * new->current_threshold will not be used
			 * until rcu_assign_pointer(), so it's safe to increment
			 * it here.
			 */
			++new->current_threshold;
		}
		j++;
	}

swap_buffers:
	/* Swap primary and spare array */
	thresholds->spare = thresholds->primary;
	rcu_assign_pointer(thresholds->primary, new);

	/* To be sure that nobody uses thresholds */
	synchronize_rcu();
unlock:
	mutex_unlock(&memcg->thresholds_lock);
}


int main(void) {
    char *output = NULL;
    CuSuite* suite = CuSuiteNew();
    CuSuiteSetup(suite, NULL, NULL);
    SUITE_ADD_TEST(suite, testDefault);
    SUITE_ADD_TEST(suite, testNoLoad);
    SUITE_ADD_TEST(suite, testNoAutoload);
    SUITE_ADD_TEST(suite, testInvalidLens);
    SUITE_ADD_TEST(suite, testLoadSave);
    SUITE_ADD_TEST(suite, testLoadDefined);
    SUITE_ADD_TEST(suite, testDefvarExpr);
    SUITE_ADD_TEST(suite, testReloadChanged);
    SUITE_ADD_TEST(suite, testReloadDirty);
    SUITE_ADD_TEST(suite, testReloadDeleted);
    SUITE_ADD_TEST(suite, testReloadDeletedMeta);
    SUITE_ADD_TEST(suite, testReloadExternalMod);
    SUITE_ADD_TEST(suite, testReloadAfterSaveNewfile);
    SUITE_ADD_TEST(suite, testParseErrorReported);
    SUITE_ADD_TEST(suite, testLoadExclWithRoot);
    SUITE_ADD_TEST(suite, testLoadTrailingExcl);

    abs_top_srcdir = getenv("abs_top_srcdir");
    if (abs_top_srcdir == NULL)
        die("env var abs_top_srcdir must be set");

    abs_top_builddir = getenv("abs_top_builddir");
    if (abs_top_builddir == NULL)
        die("env var abs_top_builddir must be set");

    if (asprintf(&root, "%s/tests/root", abs_top_srcdir) < 0) {
        die("failed to set root");
    }

    if (asprintf(&loadpath, "%s/lenses", abs_top_srcdir) < 0) {
        die("failed to set loadpath");
    }

    CuSuiteRun(suite);
    CuSuiteSummary(suite, &output);
    CuSuiteDetails(suite, &output);
    printf("%s\n", output);
    free(output);
    return suite->failCount;
}


int64_t url_fseek(ByteIOContext *s, int64_t offset, int whence) { int64_t offset1; int64_t pos; int force = whence & AVSEEK_FORCE; whence &= ~AVSEEK_FORCE; if(!s) return AVERROR(EINVAL); pos = s->pos - (s->write_flag ? 0 : (s->buf_end - s->buffer)); if (whence != SEEK_CUR && whence != SEEK_SET) return AVERROR(EINVAL); if (whence == SEEK_CUR) { offset1 = pos + (s->buf_ptr - s->buffer); if (offset == 0) return offset1; offset += offset1; } offset1 = offset - pos; if (!s->must_flush && offset1 >= 0 && offset1 <= (s->buf_end - s->buffer)) { /* can do the seek inside the buffer */ s->buf_ptr = s->buffer + offset1; } else if(s->is_streamed && !s->write_flag && offset1 >= 0 && (whence != SEEK_END || force)) { while(s->pos < offset && !s->eof_reached) fill_buffer(s); if (s->eof_reached) return AVERROR_EOF; s->buf_ptr = s->buf_end + offset - s->pos; } else { int64_t res = AVERROR(EPIPE); #if CONFIG_MUXERS || CONFIG_NETWORK if (s->write_flag) { flush_buffer(s); s->must_flush = 1; } #endif /* CONFIG_MUXERS || CONFIG_NETWORK */ if (!s->seek || (res = s->seek(s->opaque, offset, SEEK_SET)) < 0) return res; if (!s->write_flag) s->buf_end = s->buffer; s->buf_ptr = s->buffer; s->pos = offset; } s->eof_reached = 0; return offset; }


int ff_listen_connect(int fd, const struct sockaddr *addr, socklen_t addrlen, int timeout, URLContext *h) { struct pollfd p = {fd, POLLOUT, 0}; int ret; socklen_t optlen; ff_socket_nonblock(fd, 1); while ((ret = connect(fd, addr, addrlen))) { ret = ff_neterrno(); switch (ret) { case AVERROR(EINTR): if (ff_check_interrupt(&h->interrupt_callback)) return AVERROR_EXIT; continue; case AVERROR(EINPROGRESS): case AVERROR(EAGAIN): while (timeout--) { if (ff_check_interrupt(&h->interrupt_callback)) return AVERROR_EXIT; ret = poll(&p, 1, 100); if (ret > 0) break; } if (ret <= 0) return AVERROR(ETIMEDOUT); optlen = sizeof(ret); if (getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen)) ret = AVUNERROR(ff_neterrno()); if (ret != 0) { char errbuf[100]; ret = AVERROR(ret); av_strerror(ret, errbuf, sizeof(errbuf)); av_log(h, AV_LOG_ERROR, "Connection to %s failed: %s\n", h->filename, errbuf); } default: return ret; } } return ret; }


int transform_save(struct augeas *aug, struct tree *xfm,
                   const char *path, struct tree *tree) {
    FILE *fp = NULL;
    char *augnew = NULL, *augorig = NULL, *augsave = NULL;
    char *augorig_canon = NULL;
    int   augorig_exists;
    int   copy_if_rename_fails = 0;
    char *text = NULL;
    const char *filename = path + strlen(AUGEAS_FILES_TREE) + 1;
    const char *err_status = NULL;
    char *dyn_err_status = NULL;
    struct lns_error *err = NULL;
    const char *lens_name;
    struct lens *lens = xfm_lens(aug, xfm, &lens_name);
    int result = -1, r;
    bool force_reload;

    errno = 0;

    if (lens == NULL) {
        err_status = "lens_name";
        goto done;
    }

    copy_if_rename_fails =
        aug_get(aug, AUGEAS_COPY_IF_RENAME_FAILS, NULL) == 1;

    if (asprintf(&augorig, "%s%s", aug->root, filename) == -1) {
        augorig = NULL;
        goto done;
    }

    if (access(augorig, R_OK) == 0) {
        text = xread_file(augorig);
    } else {
        text = strdup("");
    }

    if (text == NULL) {
        err_status = "put_read";
        goto done;
    }

    text = append_newline(text, strlen(text));

    augorig_canon = canonicalize_file_name(augorig);
    augorig_exists = 1;
    if (augorig_canon == NULL) {
        if (errno == ENOENT) {
            augorig_canon = augorig;
            augorig_exists = 0;
        } else {
            err_status = "canon_augorig";
            goto done;
        }
    }

    /* Figure out where to put the .augnew file. If we need to rename it
       later on, put it next to augorig_canon */
    if (aug->flags & AUG_SAVE_NEWFILE) {
        if (xasprintf(&augnew, "%s" EXT_AUGNEW, augorig) < 0) {
            err_status = "augnew_oom";
            goto done;
        }
    } else {
        if (xasprintf(&augnew, "%s" EXT_AUGNEW, augorig_canon) < 0) {
            err_status = "augnew_oom";
            goto done;
        }
    }

    // FIXME: We might have to create intermediate directories
    // to be able to write augnew, but we have no idea what permissions
    // etc. they should get. Just the process default ?
    fp = fopen(augnew, "w");
    if (fp == NULL) {
        err_status = "open_augnew";
        goto done;
    }

    if (augorig_exists) {
        if (transfer_file_attrs(augorig_canon, augnew, &err_status) != 0) {
            err_status = "xfer_attrs";
            goto done;
        }
    }

    if (tree != NULL)
        lns_put(fp, lens, tree->children, text, &err);

    if (ferror(fp)) {
        err_status = "error_augnew";
        goto done;
    }

    if (fflush(fp) != 0) {
        err_status = "flush_augnew";
        goto done;
    }

    if (fsync(fileno(fp)) < 0) {
        err_status = "sync_augnew";
        goto done;
    }

    if (fclose(fp) != 0) {
        err_status = "close_augnew";
        fp = NULL;
        goto done;
    }

    fp = NULL;

    if (err != NULL) {
        err_status = err->pos >= 0 ? "parse_skel_failed" : "put_failed";
        unlink(augnew);
        goto done;
    }

    {
        char *new_text = xread_file(augnew);
        int same = 0;
        if (new_text == NULL) {
            err_status = "read_augnew";
            goto done;
        }
        same = STREQ(text, new_text);
        FREE(new_text);
        if (same) {
            result = 0;
            unlink(augnew);
            goto done;
        } else if (aug->flags & AUG_SAVE_NOOP) {
            result = 1;
            unlink(augnew);
            goto done;
        }
    }

    if (!(aug->flags & AUG_SAVE_NEWFILE)) {
        if (augorig_exists && (aug->flags & AUG_SAVE_BACKUP)) {
            r = asprintf(&augsave, "%s%s" EXT_AUGSAVE, aug->root, filename);
            if (r == -1) {
                augsave = NULL;
                goto done;
            }

            r = clone_file(augorig_canon, augsave, &err_status, 1);
            if (r != 0) {
                dyn_err_status = strappend(err_status, "_augsave");
                goto done;
            }
        }
        r = clone_file(augnew, augorig_canon, &err_status,
                       copy_if_rename_fails);
        if (r != 0) {
            dyn_err_status = strappend(err_status, "_augnew");
            goto done;
        }
    }
    result = 1;

 done:
    force_reload = aug->flags & AUG_SAVE_NEWFILE;
    r = add_file_info(aug, path, lens, lens_name, augorig, force_reload);
    if (r < 0) {
        err_status = "file_info";
        result = -1;
    }
    if (result > 0) {
        r = file_saved_event(aug, path);
        if (r < 0) {
            err_status = "saved_event";
            result = -1;
        }
    }
    {
        const char *emsg =
            dyn_err_status == NULL ? err_status : dyn_err_status;
        store_error(aug, filename, path, emsg, errno, err, text);
    }
    free(dyn_err_status);
    lens_release(lens);
    free(text);
    free(augnew);
    if (augorig_canon != augorig)
        free(augorig_canon);
    free(augorig);
    free(augsave);
    free_lns_error(err);

    if (fp != NULL)
        fclose(fp);
    return result;
}


hugetlbfs_fill_super(struct super_block *sb, void *data, int silent)
{
	struct inode * inode;
	struct dentry * root;
	int ret;
	struct hugetlbfs_config config;
	struct hugetlbfs_sb_info *sbinfo;

	save_mount_options(sb, data);

	config.nr_blocks = -1; /* No limit on size by default */
	config.nr_inodes = -1; /* No limit on number of inodes by default */
	config.uid = current_fsuid();
	config.gid = current_fsgid();
	config.mode = 0755;
	config.hstate = &default_hstate;
	ret = hugetlbfs_parse_options(data, &config);
	if (ret)
		return ret;

	sbinfo = kmalloc(sizeof(struct hugetlbfs_sb_info), GFP_KERNEL);
	if (!sbinfo)
		return -ENOMEM;
	sb->s_fs_info = sbinfo;
	sbinfo->hstate = config.hstate;
	spin_lock_init(&sbinfo->stat_lock);
	sbinfo->max_blocks = config.nr_blocks;
	sbinfo->free_blocks = config.nr_blocks;
	sbinfo->max_inodes = config.nr_inodes;
	sbinfo->free_inodes = config.nr_inodes;
	sb->s_maxbytes = MAX_LFS_FILESIZE;
	sb->s_blocksize = huge_page_size(config.hstate);
	sb->s_blocksize_bits = huge_page_shift(config.hstate);
	sb->s_magic = HUGETLBFS_MAGIC;
	sb->s_op = &hugetlbfs_ops;
	sb->s_time_gran = 1;
	inode = hugetlbfs_get_root(sb, &config);
	if (!inode)
		goto out_free;

	root = d_alloc_root(inode);
	if (!root) {
		iput(inode);
		goto out_free;
	}
	sb->s_root = root;
	return 0;
out_free:
	kfree(sbinfo);
	return -ENOMEM;
}


void SVMConverter::ImplConvertFromSVM1( SvStream& rIStm, GDIMetaFile& rMtf )
{
    const sal_uLong         nPos = rIStm.Tell();
    const SvStreamEndian    nOldFormat = rIStm.GetEndian();

    rIStm.SetEndian( SvStreamEndian::LITTLE );

    char    aCode[ 5 ];
    Size    aPrefSz;

    // read header
    rIStm.ReadBytes(aCode, sizeof(aCode));  // Identifier
    sal_Int16 nSize(0);
    rIStm.ReadInt16( nSize );                                 // Size
    sal_Int16 nVersion(0);
    rIStm.ReadInt16( nVersion );                              // Version
    sal_Int32 nTmp32(0);
    rIStm.ReadInt32( nTmp32 );
    aPrefSz.Width() = nTmp32;                       // PrefSize.Width()
    rIStm.ReadInt32( nTmp32 );
    aPrefSz.Height() = nTmp32;                      // PrefSize.Height()

    // check header-magic and version
    if( rIStm.GetError()
        || ( memcmp( aCode, "SVGDI", sizeof( aCode ) ) != 0 )
        || ( nVersion != 200 ) )
    {
        rIStm.SetError( SVSTREAM_FILEFORMAT_ERROR );
        rIStm.SetEndian( nOldFormat );
        rIStm.Seek( nPos );
        return;
    }

    LineInfo            aLineInfo( LineStyle::NONE, 0 );
    std::stack<std::unique_ptr<LineInfo>> aLIStack;
    ScopedVclPtrInstance< VirtualDevice > aFontVDev;
    rtl_TextEncoding    eActualCharSet = osl_getThreadTextEncoding();
    bool                bFatLine = false;

    tools::Polygon     aActionPoly;
    Rectangle   aRect;
    Point       aPt, aPt1;
    Size        aSz;
    Color       aActionColor;

    sal_uInt32  nUnicodeCommentStreamPos = 0;
    sal_Int32       nUnicodeCommentActionNumber = 0;

    rMtf.SetPrefSize(aPrefSz);

    MapMode aMapMode;
    if (ImplReadMapMode(rIStm, aMapMode))           // MapMode
        rMtf.SetPrefMapMode(aMapMode);

    sal_Int32 nActions(0);
    rIStm.ReadInt32(nActions);                      // Action count
    if (nActions < 0)
    {
        SAL_WARN("vcl.gdi", "svm claims negative action count (" << nActions << ")");
        nActions = 0;
    }

    const size_t nMinActionSize = sizeof(sal_uInt16) + sizeof(sal_Int32);
    const size_t nMaxPossibleActions = rIStm.remainingSize() / nMinActionSize;
    if (static_cast<sal_uInt32>(nActions) > nMaxPossibleActions)
    {
        SAL_WARN("vcl.gdi", "svm claims more actions (" << nActions << ") than stream could provide, truncating");
        nActions = nMaxPossibleActions;
    }

    size_t nLastPolygonAction(0);

    for (sal_Int32 i = 0; i < nActions && rIStm.good(); ++i)
    {
        sal_Int16 nType(0);
        rIStm.ReadInt16(nType);
        sal_Int32 nActBegin = rIStm.Tell();
        sal_Int32 nActionSize(0);
        rIStm.ReadInt32(nActionSize);

        SAL_WARN_IF( ( nType > 33 ) && ( nType < 1024 ), "vcl.gdi", "Unknown GDIMetaAction while converting!" );

        switch( nType )
        {
            case GDI_PIXEL_ACTION:
            {
                ReadPair( rIStm, aPt );
                ImplReadColor( rIStm, aActionColor );
                rMtf.AddAction( new MetaPixelAction( aPt, aActionColor ) );
            }
            break;

            case GDI_POINT_ACTION:
            {
                ReadPair( rIStm, aPt );
                rMtf.AddAction( new MetaPointAction( aPt ) );
            }
            break;

            case GDI_LINE_ACTION:
            {
                ReadPair( rIStm, aPt );
                ReadPair( rIStm, aPt1 );
                rMtf.AddAction( new MetaLineAction( aPt, aPt1, aLineInfo ) );
            }
            break;

            case GDI_LINEJOIN_ACTION :
            {
                sal_Int16 nLineJoin(0);
                rIStm.ReadInt16( nLineJoin );
                aLineInfo.SetLineJoin((basegfx::B2DLineJoin)nLineJoin);
            }
            break;

            case GDI_LINECAP_ACTION :
            {
                sal_Int16 nLineCap(0);
                rIStm.ReadInt16( nLineCap );
                aLineInfo.SetLineCap((css::drawing::LineCap)nLineCap);
            }
            break;

            case GDI_LINEDASHDOT_ACTION :
            {
                sal_Int16 a(0);
                sal_Int32 b(0);

                rIStm.ReadInt16( a ); aLineInfo.SetDashCount(a);
                rIStm.ReadInt32( b ); aLineInfo.SetDashLen(b);
                rIStm.ReadInt16( a ); aLineInfo.SetDotCount(a);
                rIStm.ReadInt32( b ); aLineInfo.SetDotLen(b);
                rIStm.ReadInt32( b ); aLineInfo.SetDistance(b);

                if(((aLineInfo.GetDashCount() && aLineInfo.GetDashLen())
                    || (aLineInfo.GetDotCount() && aLineInfo.GetDotLen()))
                    && aLineInfo.GetDistance())
                {
                    aLineInfo.SetStyle(LineStyle::Dash);
                }
            }
            break;

            case GDI_EXTENDEDPOLYGON_ACTION :
            {
                // read the tools::PolyPolygon in every case
                tools::PolyPolygon aInputPolyPolygon;
                ImplReadExtendedPolyPolygonAction(rIStm, aInputPolyPolygon);

                // now check if it can be set somewhere
                if(nLastPolygonAction < rMtf.GetActionSize())
                {
                    MetaPolyLineAction* pPolyLineAction = dynamic_cast< MetaPolyLineAction* >(rMtf.GetAction(nLastPolygonAction));

                    if(pPolyLineAction)
                    {
                        // replace MetaPolyLineAction when we have a single polygon. Do not rely on the
                        // same point count; the originally written GDI_POLYLINE_ACTION may have been
                        // Subdivided for better quality for older usages
                        if(1 == aInputPolyPolygon.Count())
                        {
                            MetaAction* pAction = rMtf.ReplaceAction(
                                new MetaPolyLineAction(
                                    aInputPolyPolygon.GetObject(0),
                                    pPolyLineAction->GetLineInfo()),
                                nLastPolygonAction);
                            if(pAction)
                                pAction->Delete();
                        }
                    }
                    else
                    {
                        MetaPolyPolygonAction* pPolyPolygonAction = dynamic_cast< MetaPolyPolygonAction* >(rMtf.GetAction(nLastPolygonAction));

                        if(pPolyPolygonAction)
                        {
                            // replace MetaPolyPolygonAction when we have a curved polygon. Do rely on the
                            // same sub-polygon count
                            if(pPolyPolygonAction->GetPolyPolygon().Count() == aInputPolyPolygon.Count())
                            {
                                MetaAction* pAction = rMtf.ReplaceAction(
                                    new MetaPolyPolygonAction(
                                        aInputPolyPolygon),
                                    nLastPolygonAction);
                                if(pAction)
                                    pAction->Delete();
                            }
                        }
                        else
                        {
                            MetaPolygonAction* pPolygonAction = dynamic_cast< MetaPolygonAction* >(rMtf.GetAction(nLastPolygonAction));

                            if(pPolygonAction)
                            {
                                // replace MetaPolygonAction
                                if(1 == aInputPolyPolygon.Count())
                                {
                                    MetaAction* pAction = rMtf.ReplaceAction(
                                        new MetaPolygonAction(
                                            aInputPolyPolygon.GetObject(0)),
                                        nLastPolygonAction);
                                    if(pAction)
                                        pAction->Delete();
                                }
                            }
                        }
                    }
                }
            }
            break;

            case GDI_RECT_ACTION:
            {
                ImplReadRect( rIStm, aRect );
                sal_Int32 nTmp(0), nTmp1(0);
                rIStm.ReadInt32( nTmp ).ReadInt32( nTmp1 );

                if( nTmp || nTmp1 )
                    rMtf.AddAction( new MetaRoundRectAction( aRect, nTmp, nTmp1 ) );
                else
                {
                    rMtf.AddAction( new MetaRectAction( aRect ) );

                    if( bFatLine )
                        rMtf.AddAction( new MetaPolyLineAction( aRect, aLineInfo ) );
                }
            }
            break;

            case GDI_ELLIPSE_ACTION:
            {
                ImplReadRect( rIStm, aRect );

                if( bFatLine )
                {
                    const tools::Polygon aPoly( aRect.Center(), aRect.GetWidth() >> 1, aRect.GetHeight() >> 1 );

                    rMtf.AddAction( new MetaPushAction( PushFlags::LINECOLOR ) );
                    rMtf.AddAction( new MetaLineColorAction( COL_TRANSPARENT, false ) );
                    rMtf.AddAction( new MetaPolygonAction( aPoly ) );
                    rMtf.AddAction( new MetaPopAction() );
                    rMtf.AddAction( new MetaPolyLineAction( aPoly, aLineInfo ) );
                }
                else
                    rMtf.AddAction( new MetaEllipseAction( aRect ) );
            }
            break;

            case GDI_ARC_ACTION:
            {
                ImplReadRect( rIStm, aRect );
                ReadPair( rIStm, aPt );
                ReadPair( rIStm, aPt1 );

                if( bFatLine )
                {
                    const tools::Polygon aPoly( aRect, aPt, aPt1, PolyStyle::Arc );

                    rMtf.AddAction( new MetaPushAction( PushFlags::LINECOLOR ) );
                    rMtf.AddAction( new MetaLineColorAction( COL_TRANSPARENT, false ) );
                    rMtf.AddAction( new MetaPolygonAction( aPoly ) );
                    rMtf.AddAction( new MetaPopAction() );
                    rMtf.AddAction( new MetaPolyLineAction( aPoly, aLineInfo ) );
                }
                else
                    rMtf.AddAction( new MetaArcAction( aRect, aPt, aPt1 ) );
            }
            break;

            case GDI_PIE_ACTION:
            {
                ImplReadRect( rIStm, aRect );
                ReadPair( rIStm, aPt );
                ReadPair( rIStm, aPt1 );

                if( bFatLine )
                {
                    const tools::Polygon aPoly( aRect, aPt, aPt1, PolyStyle::Pie );

                    rMtf.AddAction( new MetaPushAction( PushFlags::LINECOLOR ) );
                    rMtf.AddAction( new MetaLineColorAction( COL_TRANSPARENT, false ) );
                    rMtf.AddAction( new MetaPolygonAction( aPoly ) );
                    rMtf.AddAction( new MetaPopAction() );
                    rMtf.AddAction( new MetaPolyLineAction( aPoly, aLineInfo ) );
                }
                else
                    rMtf.AddAction( new MetaPieAction( aRect, aPt, aPt1 ) );
            }
            break;

            case GDI_INVERTRECT_ACTION:
            case GDI_HIGHLIGHTRECT_ACTION:
            {
                ImplReadRect( rIStm, aRect );
                rMtf.AddAction( new MetaPushAction( PushFlags::RASTEROP ) );
                rMtf.AddAction( new MetaRasterOpAction( RasterOp::Invert ) );
                rMtf.AddAction( new MetaRectAction( aRect ) );
                rMtf.AddAction( new MetaPopAction() );
            }
            break;

            case GDI_POLYLINE_ACTION:
            {
                if (ImplReadPoly(rIStm, aActionPoly))
                {
                    nLastPolygonAction = rMtf.GetActionSize();

                    if( bFatLine )
                        rMtf.AddAction( new MetaPolyLineAction( aActionPoly, aLineInfo ) );
                    else
                        rMtf.AddAction( new MetaPolyLineAction( aActionPoly ) );
                }
            }
            break;

            case GDI_POLYGON_ACTION:
            {
                if (ImplReadPoly(rIStm, aActionPoly))
                {
                    if( bFatLine )
                    {
                        rMtf.AddAction( new MetaPushAction( PushFlags::LINECOLOR ) );
                        rMtf.AddAction( new MetaLineColorAction( COL_TRANSPARENT, false ) );
                        rMtf.AddAction( new MetaPolygonAction( aActionPoly ) );
                        rMtf.AddAction( new MetaPopAction() );
                        rMtf.AddAction( new MetaPolyLineAction( aActionPoly, aLineInfo ) );
                    }
                    else
                    {
                        nLastPolygonAction = rMtf.GetActionSize();
                        rMtf.AddAction( new MetaPolygonAction( aActionPoly ) );
                    }
                }
            }
            break;

            case GDI_POLYPOLYGON_ACTION:
            {
                tools::PolyPolygon aPolyPoly;

                if (ImplReadPolyPoly(rIStm, aPolyPoly))
                {
                    if( bFatLine )
                    {
                        rMtf.AddAction( new MetaPushAction( PushFlags::LINECOLOR ) );
                        rMtf.AddAction( new MetaLineColorAction( COL_TRANSPARENT, false ) );
                        rMtf.AddAction( new MetaPolyPolygonAction( aPolyPoly ) );
                        rMtf.AddAction( new MetaPopAction() );

                        for( sal_uInt16 nPoly = 0, nCount = aPolyPoly.Count(); nPoly < nCount; nPoly++ )
                            rMtf.AddAction( new MetaPolyLineAction( aPolyPoly[ nPoly ], aLineInfo ) );
                    }
                    else
                    {
                        nLastPolygonAction = rMtf.GetActionSize();
                        rMtf.AddAction( new MetaPolyPolygonAction( aPolyPoly ) );
                    }
                }
            }
            break;

            case GDI_FONT_ACTION:
            {
                vcl::Font   aFont;
                char        aName[LF_FACESIZE+1];

                ImplReadColor( rIStm, aActionColor ); aFont.SetColor( aActionColor );
                ImplReadColor( rIStm, aActionColor ); aFont.SetFillColor( aActionColor );
                size_t nRet = rIStm.ReadBytes(aName, LF_FACESIZE);
                aName[nRet] = 0;
                aFont.SetFamilyName( OUString( aName, strlen(aName), rIStm.GetStreamCharSet() ) );

                sal_Int32 nWidth(0), nHeight(0);
                rIStm.ReadInt32(nWidth).ReadInt32(nHeight);
                sal_Int16 nCharOrient(0), nLineOrient(0);
                rIStm.ReadInt16(nCharOrient).ReadInt16(nLineOrient);
                sal_Int16 nCharSet(0), nFamily(0), nPitch(0), nAlign(0), nWeight(0), nUnderline(0), nStrikeout(0);
                rIStm.ReadInt16(nCharSet).ReadInt16(nFamily).ReadInt16(nPitch).ReadInt16(nAlign).ReadInt16(nWeight).ReadInt16(nUnderline).ReadInt16(nStrikeout);
                bool bItalic(false), bOutline(false), bShadow(false), bTransparent(false);
                rIStm.ReadCharAsBool(bItalic).ReadCharAsBool(bOutline).ReadCharAsBool(bShadow).ReadCharAsBool(bTransparent);

                aFont.SetFontSize( Size( nWidth, nHeight ) );
                aFont.SetCharSet( (rtl_TextEncoding) nCharSet );
                aFont.SetFamily( (FontFamily) nFamily );
                aFont.SetPitch( (FontPitch) nPitch );
                aFont.SetAlignment( (FontAlign) nAlign );
                aFont.SetWeight( ( nWeight == 1 ) ? WEIGHT_LIGHT : ( nWeight == 2 ) ? WEIGHT_NORMAL :
                                 ( nWeight == 3 ) ? WEIGHT_BOLD : WEIGHT_DONTKNOW );
                aFont.SetUnderline( (FontLineStyle) nUnderline );
                aFont.SetStrikeout( (FontStrikeout) nStrikeout );
                aFont.SetItalic( bItalic ? ITALIC_NORMAL : ITALIC_NONE );
                aFont.SetOutline( bOutline );
                aFont.SetShadow( bShadow );
                aFont.SetOrientation( nLineOrient );
                aFont.SetTransparent( bTransparent );

                eActualCharSet = aFont.GetCharSet();
                if ( eActualCharSet == RTL_TEXTENCODING_DONTKNOW )
                    eActualCharSet = osl_getThreadTextEncoding();

                rMtf.AddAction( new MetaFontAction( aFont ) );
                rMtf.AddAction( new MetaTextAlignAction( aFont.GetAlignment() ) );
                rMtf.AddAction( new MetaTextColorAction( aFont.GetColor() ) );
                rMtf.AddAction( new MetaTextFillColorAction( aFont.GetFillColor(), !aFont.IsTransparent() ) );

                // #106172# Track font relevant data in shadow VDev
                aFontVDev->SetFont( aFont );
            }
            break;

            case GDI_TEXT_ACTION:
            {
                sal_Int32 nIndex(0), nLen(0), nTmp(0);

                ReadPair( rIStm, aPt ).ReadInt32( nIndex ).ReadInt32( nLen ).ReadInt32( nTmp );
                if (nTmp > 0)
                {
                    OString aByteStr = read_uInt8s_ToOString(rIStm, nTmp);
                    sal_uInt8 nTerminator = 0;
                    rIStm.ReadUChar( nTerminator );
                    SAL_WARN_IF( nTerminator != 0, "vcl.gdi", "expected string to be NULL terminated" );

                    OUString aStr(OStringToOUString(aByteStr, eActualCharSet));
                    if ( nUnicodeCommentActionNumber == i )
                        ImplReadUnicodeComment( nUnicodeCommentStreamPos, rIStm, aStr );
                    rMtf.AddAction( new MetaTextAction( aPt, aStr, nIndex, nLen ) );
                }
                rIStm.Seek( nActBegin + nActionSize );
            }
            break;

            case GDI_TEXTARRAY_ACTION:
            {
                sal_Int32 nIndex(0), nLen(0), nAryLen(0), nTmp(0);

                ReadPair( rIStm, aPt ).ReadInt32( nIndex ).ReadInt32( nLen ).ReadInt32( nTmp ).ReadInt32( nAryLen );
                if (nTmp > 0)
                {
                    OString aByteStr = read_uInt8s_ToOString(rIStm, nTmp);
                    sal_uInt8 nTerminator = 0;
                    rIStm.ReadUChar( nTerminator );
                    SAL_WARN_IF( nTerminator != 0, "vcl.gdi", "expected string to be NULL terminated" );

                    OUString aStr(OStringToOUString(aByteStr, eActualCharSet));

                    std::unique_ptr<long[]> pDXAry;
                    sal_Int32 nDXAryLen = 0;
                    if (nAryLen > 0)
                    {
                        const size_t nMinRecordSize = sizeof(sal_Int32);
                        const size_t nMaxRecords = rIStm.remainingSize() / nMinRecordSize;
                        if (static_cast<sal_uInt32>(nAryLen) > nMaxRecords)
                        {
                            SAL_WARN("vcl.gdi", "Parsing error: " << nMaxRecords <<
                                     " max possible entries, but " << nAryLen << " claimed, truncating");
                            nAryLen = nMaxRecords;
                        }

                        sal_Int32 nStrLen( aStr.getLength() );

                        nDXAryLen = std::max(nAryLen, nStrLen);

                        if (nDXAryLen < nLen)
                        {
                            //MetaTextArrayAction ctor expects pDXAry to be >= nLen if set, so if this can't
                            //be achieved, don't read it, it's utterly broken.
                            SAL_WARN("vcl.gdi", "dxary too short, discarding completely");
                            rIStm.SeekRel(sizeof(sal_Int32) * nDXAryLen);
                            nLen = 0;
                            nIndex = 0;
                        }
                        else
                        {
                            pDXAry.reset(new long[nDXAryLen]);

                            for (sal_Int32 j = 0; j < nAryLen; ++j)
                                rIStm.ReadInt32( nTmp ), pDXAry[ j ] = nTmp;

                            // #106172# Add last DX array elem, if missing
                            if( nAryLen != nStrLen )
                            {
                                if (nAryLen+1 == nStrLen && nIndex >= 0)
                                {
                                    std::unique_ptr<long[]> pTmpAry(new long[nStrLen]);

                                    aFontVDev->GetTextArray( aStr, pTmpAry.get(), nIndex, nLen );

                                    // now, the difference between the
                                    // last and the second last DX array
                                    // is the advancement for the last
                                    // glyph. Thus, to complete our meta
                                    // action's DX array, just add that
                                    // difference to last elem and store
                                    // in very last.
                                    if( nStrLen > 1 )
                                        pDXAry[ nStrLen-3 ] = pDXAry[ nStrLen-2 ] + pTmpAry[ nStrLen-1 ] - pTmpAry[ nStrLen-2 ];
                                    else
                                        pDXAry[ nStrLen-1 ] = pTmpAry[ nStrLen-1 ]; // len=1: 0th position taken to be 0
                                }
#ifdef DBG_UTIL
                                else
                                    OSL_FAIL("More than one DX array element missing on SVM import");
#endif
                            }
                        }
                    }
                    if ( nUnicodeCommentActionNumber == i )
                        ImplReadUnicodeComment( nUnicodeCommentStreamPos, rIStm, aStr );
                    rMtf.AddAction( new MetaTextArrayAction( aPt, aStr, pDXAry.get(), nIndex, nLen ) );
                }
                rIStm.Seek( nActBegin + nActionSize );
            }
            break;

            case GDI_STRETCHTEXT_ACTION:
            {
                sal_Int32 nIndex(0), nLen(0), nWidth(0), nTmp(0);

                ReadPair( rIStm, aPt ).ReadInt32( nIndex ).ReadInt32( nLen ).ReadInt32( nTmp ).ReadInt32( nWidth );
                if (nTmp > 0)
                {
                    OString aByteStr = read_uInt8s_ToOString(rIStm, nTmp);
                    sal_uInt8 nTerminator = 0;
                    rIStm.ReadUChar( nTerminator );
                    SAL_WARN_IF( nTerminator != 0, "vcl.gdi", "expected string to be NULL terminated" );

                    OUString aStr(OStringToOUString(aByteStr, eActualCharSet));
                    if ( nUnicodeCommentActionNumber == i )
                        ImplReadUnicodeComment( nUnicodeCommentStreamPos, rIStm, aStr );
                    rMtf.AddAction( new MetaStretchTextAction( aPt, nWidth, aStr, nIndex, nLen ) );
                }
                rIStm.Seek( nActBegin + nActionSize );
            }
            break;

            case GDI_BITMAP_ACTION:
            {
                Bitmap aBmp;

                ReadPair( rIStm, aPt );
                ReadDIB(aBmp, rIStm, true);
                rMtf.AddAction( new MetaBmpAction( aPt, aBmp ) );
            }
            break;

            case GDI_BITMAPSCALE_ACTION:
            {
                Bitmap aBmp;

                ReadPair( rIStm, aPt );
                ReadPair( rIStm, aSz );
                ReadDIB(aBmp, rIStm, true);
                rMtf.AddAction( new MetaBmpScaleAction( aPt, aSz, aBmp ) );
            }
            break;

            case GDI_BITMAPSCALEPART_ACTION:
            {
                Bitmap  aBmp;
                Size    aSz2;

                ReadPair( rIStm, aPt );
                ReadPair( rIStm, aSz );
                ReadPair( rIStm, aPt1 );
                ReadPair( rIStm, aSz2 );
                ReadDIB(aBmp, rIStm, true);
                rMtf.AddAction( new MetaBmpScalePartAction( aPt, aSz, aPt1, aSz2, aBmp ) );
            }
            break;

            case GDI_PEN_ACTION:
            {
                sal_Int32 nPenWidth;
                sal_Int16 nPenStyle;

                ImplReadColor( rIStm, aActionColor );
                rIStm.ReadInt32( nPenWidth ).ReadInt16( nPenStyle );

                aLineInfo.SetStyle( nPenStyle ? LineStyle::Solid : LineStyle::NONE );
                aLineInfo.SetWidth( nPenWidth );
                bFatLine = nPenStyle && !aLineInfo.IsDefault();

                rMtf.AddAction( new MetaLineColorAction( aActionColor, nPenStyle != 0 ) );
            }
            break;

            case GDI_FILLBRUSH_ACTION:
            {
                sal_Int16 nBrushStyle;

                ImplReadColor( rIStm, aActionColor );
                rIStm.SeekRel( 6 );
                rIStm.ReadInt16( nBrushStyle );
                rMtf.AddAction( new MetaFillColorAction( aActionColor, nBrushStyle != 0 ) );
                rIStm.SeekRel( 2 );
            }
            break;

            case GDI_MAPMODE_ACTION:
            {
                if (ImplReadMapMode(rIStm, aMapMode))
                {
                    rMtf.AddAction(new MetaMapModeAction(aMapMode));

                    // #106172# Track font relevant data in shadow VDev
                    aFontVDev->SetMapMode(aMapMode);
                };
            }
            break;

            case GDI_CLIPREGION_ACTION:
            {
                vcl::Region  aRegion;
                sal_Int16   nRegType;
                sal_Int16   bIntersect;
                bool    bClip = false;

                rIStm.ReadInt16( nRegType ).ReadInt16( bIntersect );
                ImplReadRect( rIStm, aRect );

                switch( nRegType )
                {
                    case 0:
                    break;

                    case 1:
                    {
                        Rectangle aRegRect;

                        ImplReadRect( rIStm, aRegRect );
                        aRegion = vcl::Region( aRegRect );
                        bClip = true;
                    }
                    break;

                    case 2:
                    {
                        if (ImplReadPoly(rIStm, aActionPoly))
                        {
                            aRegion = vcl::Region( aActionPoly );
                            bClip = true;
                        }
                    }
                    break;

                    case 3:
                    {
                        bool bSuccess = true;
                        tools::PolyPolygon aPolyPoly;
                        sal_Int32 nPolyCount32(0);
                        rIStm.ReadInt32(nPolyCount32);
                        sal_uInt16 nPolyCount(nPolyCount32);

                        for (sal_uInt16 j = 0; j < nPolyCount && rIStm.good(); ++j)
                        {
                            if (!ImplReadPoly(rIStm, aActionPoly))
                            {
                                bSuccess = false;
                                break;
                            }
                            aPolyPoly.Insert(aActionPoly);
                        }

                        if (bSuccess)
                        {
                            aRegion = vcl::Region( aPolyPoly );
                            bClip = true;
                        }
                    }
                    break;
                }

                if( bIntersect )
                    aRegion.Intersect( aRect );

                rMtf.AddAction( new MetaClipRegionAction( aRegion, bClip ) );
            }
            break;

            case GDI_MOVECLIPREGION_ACTION:
            {
                sal_Int32 nTmp(0), nTmp1(0);
                rIStm.ReadInt32( nTmp ).ReadInt32( nTmp1 );
                rMtf.AddAction( new MetaMoveClipRegionAction( nTmp, nTmp1 ) );
            }
            break;

            case GDI_ISECTCLIPREGION_ACTION:
            {
                ImplReadRect( rIStm, aRect );
                rMtf.AddAction( new MetaISectRectClipRegionAction( aRect ) );
            }
            break;

            case GDI_RASTEROP_ACTION:
            {
                RasterOp    eRasterOp;
                sal_Int16       nRasterOp;

                rIStm.ReadInt16( nRasterOp );

                switch( nRasterOp )
                {
                    case 1:
                        eRasterOp = RasterOp::Invert;
                    break;

                    case 4:
                    case 5:
                        eRasterOp = RasterOp::Xor;
                    break;

                    default:
                        eRasterOp = RasterOp::OverPaint;
                    break;
                }

                rMtf.AddAction( new MetaRasterOpAction( eRasterOp ) );
            }
            break;

            case GDI_PUSH_ACTION:
            {
                aLIStack.push(o3tl::make_unique<LineInfo>(aLineInfo));
                rMtf.AddAction( new MetaPushAction( PushFlags::ALL ) );

                // #106172# Track font relevant data in shadow VDev
                aFontVDev->Push();
            }
            break;

            case GDI_POP_ACTION:
            {

                std::unique_ptr<LineInfo> xLineInfo;
                if (!aLIStack.empty())
                {
                    xLineInfo = std::move(aLIStack.top());
                    aLIStack.pop();
                }

                // restore line info
                if (xLineInfo)
                {
                    aLineInfo = *xLineInfo;
                    xLineInfo.reset();
                    bFatLine = ( LineStyle::NONE != aLineInfo.GetStyle() ) && !aLineInfo.IsDefault();
                }

                rMtf.AddAction( new MetaPopAction() );

                // #106172# Track font relevant data in shadow VDev
                aFontVDev->Pop();
            }
            break;

            case GDI_GRADIENT_ACTION:
            {
                Color   aStartCol;
                Color   aEndCol;
                sal_Int16   nStyle;
                sal_Int16   nAngle;
                sal_Int16   nBorder;
                sal_Int16   nOfsX;
                sal_Int16   nOfsY;
                sal_Int16   nIntensityStart;
                sal_Int16   nIntensityEnd;

                ImplReadRect( rIStm, aRect );
                rIStm.ReadInt16( nStyle );
                ImplReadColor( rIStm, aStartCol );
                ImplReadColor( rIStm, aEndCol );
                rIStm.ReadInt16( nAngle ).ReadInt16( nBorder ).ReadInt16( nOfsX ).ReadInt16( nOfsY ).ReadInt16( nIntensityStart ).ReadInt16( nIntensityEnd );

                Gradient aGrad( (GradientStyle) nStyle, aStartCol, aEndCol );

                aGrad.SetAngle( nAngle );
                aGrad.SetBorder( nBorder );
                aGrad.SetOfsX( nOfsX );
                aGrad.SetOfsY( nOfsY );
                aGrad.SetStartIntensity( nIntensityStart );
                aGrad.SetEndIntensity( nIntensityEnd );
                rMtf.AddAction( new MetaGradientAction( aRect, aGrad ) );
            }
            break;

            case GDI_TRANSPARENT_COMMENT:
            {
                tools::PolyPolygon aPolyPoly;
                sal_Int32       nFollowingActionCount;
                sal_Int16       nTrans;

                ReadPolyPolygon( rIStm, aPolyPoly );
                rIStm.ReadInt16( nTrans ).ReadInt32( nFollowingActionCount );
                ImplSkipActions( rIStm, nFollowingActionCount );
                rMtf.AddAction( new MetaTransparentAction( aPolyPoly, nTrans ) );

                i += nFollowingActionCount;
            }
            break;

            case GDI_FLOATTRANSPARENT_COMMENT:
            {
                GDIMetaFile aMtf;
                Point       aPos;
                Size        aSize;
                Gradient    aGradient;
                sal_Int32       nFollowingActionCount;

                ReadGDIMetaFile( rIStm, aMtf );
                ReadPair( rIStm, aPos );
                ReadPair( rIStm, aSize );
                ReadGradient( rIStm, aGradient );
                rIStm.ReadInt32( nFollowingActionCount );
                ImplSkipActions( rIStm, nFollowingActionCount );
                rMtf.AddAction( new MetaFloatTransparentAction( aMtf, aPos, aSize, aGradient ) );

                i += nFollowingActionCount;
            }
            break;

            case GDI_HATCH_COMMENT:
            {
                tools::PolyPolygon aPolyPoly;
                Hatch       aHatch;
                sal_Int32       nFollowingActionCount;

                ReadPolyPolygon( rIStm, aPolyPoly );
                ReadHatch( rIStm, aHatch );
                rIStm.ReadInt32( nFollowingActionCount );
                ImplSkipActions( rIStm, nFollowingActionCount );
                rMtf.AddAction( new MetaHatchAction( aPolyPoly, aHatch ) );

                i += nFollowingActionCount;
            }
            break;

            case GDI_REFPOINT_COMMENT:
            {
                Point   aRefPoint;
                bool    bSet;
                sal_Int32   nFollowingActionCount;

                ReadPair( rIStm, aRefPoint );
                rIStm.ReadCharAsBool( bSet ).ReadInt32( nFollowingActionCount );
                ImplSkipActions( rIStm, nFollowingActionCount );
                rMtf.AddAction( new MetaRefPointAction( aRefPoint, bSet ) );

                i += nFollowingActionCount;

                // #106172# Track font relevant data in shadow VDev
                if( bSet )
                    aFontVDev->SetRefPoint( aRefPoint );
                else
                    aFontVDev->SetRefPoint();
            }
            break;

            case GDI_TEXTLINECOLOR_COMMENT:
            {
                Color   aColor;
                bool    bSet;
                sal_Int32   nFollowingActionCount;

                ReadColor( rIStm, aColor );
                rIStm.ReadCharAsBool( bSet ).ReadInt32( nFollowingActionCount );
                ImplSkipActions( rIStm, nFollowingActionCount );
                rMtf.AddAction( new MetaTextLineColorAction( aColor, bSet ) );

                i += nFollowingActionCount;
            }
            break;

            case GDI_TEXTLINE_COMMENT:
            {
                Point   aStartPt;
                sal_Int32  nWidth(0);
                sal_uInt32 nStrikeout(0);
                sal_uInt32 nUnderline(0);
                sal_Int32  nFollowingActionCount(0);

                ReadPair( rIStm, aStartPt );
                rIStm.ReadInt32(nWidth ).ReadUInt32(nStrikeout).ReadUInt32(nUnderline).ReadInt32(nFollowingActionCount);
                ImplSkipActions(rIStm, nFollowingActionCount);
                rMtf.AddAction( new MetaTextLineAction( aStartPt, nWidth,
                                                        (FontStrikeout) nStrikeout,
                                                        (FontLineStyle) nUnderline,
                                                        LINESTYLE_NONE ) );

                i += nFollowingActionCount;
            }
            break;

            case GDI_GRADIENTEX_COMMENT:
            {
                tools::PolyPolygon aPolyPoly;
                Gradient    aGradient;
                sal_Int32       nFollowingActionCount;

                ReadPolyPolygon( rIStm, aPolyPoly );
                ReadGradient( rIStm, aGradient );
                rIStm.ReadInt32( nFollowingActionCount );
                ImplSkipActions( rIStm, nFollowingActionCount );
                rMtf.AddAction( new MetaGradientExAction( aPolyPoly, aGradient ) );

                i += nFollowingActionCount;
            }
            break;

            case GDI_COMMENT_COMMENT:
            {
                sal_Int32   nValue;
                sal_uInt32  nDataSize;
                std::vector<sal_uInt8> aData;
                sal_Int32       nFollowingActionCount;

                OString aComment = read_uInt16_lenPrefixed_uInt8s_ToOString(rIStm);
                rIStm.ReadInt32( nValue ).ReadUInt32( nDataSize );

                if (nDataSize)
                {
                    aData.resize(nDataSize);
                    nDataSize = rIStm.ReadBytes(aData.data(), nDataSize);
                }

                rIStm.ReadInt32( nFollowingActionCount );
                ImplSkipActions( rIStm, nFollowingActionCount );
                rMtf.AddAction(new MetaCommentAction(aComment, nValue, aData.data(), nDataSize));

                i += nFollowingActionCount;
            }
            break;

            case GDI_UNICODE_COMMENT:
            {
                nUnicodeCommentActionNumber = i + 1;
                nUnicodeCommentStreamPos = rIStm.Tell() - 6;
                if (nActionSize < 4)
                    rIStm.SetError(SVSTREAM_FILEFORMAT_ERROR);
                else
                    rIStm.SeekRel(nActionSize - 4);
            }
            break;

            default:
                if (nActionSize < 4)
                    rIStm.SetError(SVSTREAM_FILEFORMAT_ERROR);
                else
                    rIStm.SeekRel(nActionSize - 4);
            break;
        }
    }

    rIStm.SetEndian( nOldFormat );
}


void TSTextLogObjectFlush ( TSTextLogObject the_object ) {
 sdk_assert ( sdk_sanity_check_iocore_structure ( the_object ) == TS_SUCCESS ) ;
 ( ( TextLogObject * ) the_object ) -> force_new_buffer ( ) ;
 }


setup_listen(void)
{
  char port[256];
  int error = 0;

  if (g_lis_trans != 0)
  {
    trans_delete(g_lis_trans);
  }
  if (g_use_unix_socket)
  {
    g_lis_trans = trans_create(2, 8192, 8192);
    g_snprintf(port, 255, "/tmp/xrdp_chansrv_socket_%d", 7200 + g_display_num);
  }
  else
  {
    g_lis_trans = trans_create(1, 8192, 8192);
    g_snprintf(port, 255, "%d", 7200 + g_display_num);
  }
  g_lis_trans->trans_conn_in = my_trans_conn_in;
  error = trans_listen(g_lis_trans, port);
  if (error != 0)
  {
    LOG(0, ("setup_listen: trans_listen failed for port %s", port));
    return 1;
  }
  return 0;
}


g_init(const char* app_name)
{
#if defined(_WIN32)
  WSADATA wsadata;

  WSAStartup(2, &wsadata);
#endif
  setlocale(LC_CTYPE, "");
  if (app_name != 0)
  {
    if (app_name[0] != 0)
    {
      snprintf(g_temp_base, sizeof(g_temp_base), "/tmp/%s-XXXXXX", app_name);
      if (mkdtemp(g_temp_base) == 0)
      {
        printf("g_init: mkdtemp failed [%s]\n", g_temp_base);
      }
    }
  }
}


bool WebContents::SendIPCMessageToFrame(bool internal,
                                        int32_t frame_id,
                                        const std::string& channel,
                                        v8::Local<v8::Value> args) {
  v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  blink::CloneableMessage message;
  if (!gin::ConvertFromV8(isolate, args, &message)) {
    isolate->ThrowException(v8::Exception::Error(
        gin::StringToV8(isolate, "Failed to serialize arguments")));
    return false;
  }
  auto frames = web_contents()->GetAllFrames();
  auto iter = std::find_if(frames.begin(), frames.end(), [frame_id](auto* f) {
    return f->GetRoutingID() == frame_id;
  });
  if (iter == frames.end())
    return false;
  if (!(*iter)->IsRenderFrameLive())
    return false;

  mojo::AssociatedRemote<mojom::ElectronRenderer> electron_renderer;
  (*iter)->GetRemoteAssociatedInterfaces()->GetInterface(&electron_renderer);
  electron_renderer->Message(internal, channel, std::move(message),
                             0 /* sender_id */);
  return true;
}


static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska) { EbmlList *blocks_list; MatroskaBlock *blocks; int i, res; res = ebml_parse(matroska, matroska_cluster_incremental_parsing, &matroska->current_cluster); if (res == 1) { /* New Cluster */ if (matroska->current_cluster_pos) ebml_level_end(matroska); ebml_free(matroska_cluster, &matroska->current_cluster); memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster)); matroska->current_cluster_num_blocks = 0; matroska->current_cluster_pos = avio_tell(matroska->ctx->pb); matroska->prev_pkt = NULL; /* sizeof the ID which was already read */ if (matroska->current_id) matroska->current_cluster_pos -= 4; res = ebml_parse(matroska, matroska_clusters_incremental, &matroska->current_cluster); /* Try parsing the block again. */ if (res == 1) res = ebml_parse(matroska, matroska_cluster_incremental_parsing, &matroska->current_cluster); } if (!res && matroska->current_cluster_num_blocks < matroska->current_cluster.blocks.nb_elem) { blocks_list = &matroska->current_cluster.blocks; blocks = blocks_list->elem; matroska->current_cluster_num_blocks = blocks_list->nb_elem; i = blocks_list->nb_elem - 1; if (blocks[i].bin.size > 0 && blocks[i].bin.data) { int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1; uint8_t* additional = blocks[i].additional.size > 0 ? blocks[i].additional.data : NULL; if (!blocks[i].non_simple) blocks[i].duration = 0; res = matroska_parse_block(matroska, blocks[i].bin.data, blocks[i].bin.size, blocks[i].bin.pos, matroska->current_cluster.timecode, blocks[i].duration, is_keyframe, additional, blocks[i].additional_id, blocks[i].additional.size, matroska->current_cluster_pos); } } if (res < 0) matroska->done = 1; return res; }


g_execvp(const char* p1, char* args[])
{
#if defined(_WIN32)
  return 0;
#else
  return execvp(p1, args);
#endif
}


g_fork(void)
{
#if defined(_WIN32)
  return 0;
#else
  int rv;

  rv = fork();
  if (rv == 0) /* child */
  {
    g_strncpy(g_temp_base, g_temp_base_org, 127);
    if (mkdtemp(g_temp_base) == 0)
    {
      printf("g_fork: mkdtemp failed [%s]\n", g_temp_base);
    }
  }
  return rv;
#endif
}


static unsigned virtio_s390_get_features ( void * opaque ) {
 VirtIOS390Device * dev = ( VirtIOS390Device * ) opaque ;
 return dev -> host_features ;
 }


static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
{
	return HUGETLBFS_SB(inode->i_sb)->spool;
}


decode_coeffs_b_generic(VP56RangeCoder *c, int16_t *coef, int n_coeffs, int is_tx32x32, int is8bitsperpixel, int bpp, unsigned (*cnt)[6][3], unsigned (*eob)[6][2], uint8_t (*p)[6][11], int nnz, const int16_t *scan, const int16_t (*nb)[2], const int16_t *band_counts, const int16_t *qmul) { int i = 0, band = 0, band_left = band_counts[band]; uint8_t *tp = p[0][nnz]; uint8_t cache[1024]; do { int val, rc; val = vp56_rac_get_prob_branchy(c, tp[0]); // eob eob[band][nnz][val]++; if (!val) break; skip_eob: if (!vp56_rac_get_prob_branchy(c, tp[1])) { // zero cnt[band][nnz][0]++; if (!--band_left) band_left = band_counts[++band]; cache[scan[i]] = 0; nnz = (1 + cache[nb[i][0]] + cache[nb[i][1]]) >> 1; tp = p[band][nnz]; if (++i == n_coeffs) break; //invalid input; blocks should end with EOB goto skip_eob; } rc = scan[i]; if (!vp56_rac_get_prob_branchy(c, tp[2])) { // one cnt[band][nnz][1]++; val = 1; cache[rc] = 1; } else { // fill in p[3-10] (model fill) - only once per frame for each pos if (!tp[3]) memcpy(&tp[3], ff_vp9_model_pareto8[tp[2]], 8); cnt[band][nnz][2]++; if (!vp56_rac_get_prob_branchy(c, tp[3])) { // 2, 3, 4 if (!vp56_rac_get_prob_branchy(c, tp[4])) { cache[rc] = val = 2; } else { val = 3 + vp56_rac_get_prob(c, tp[5]); cache[rc] = 3; } } else if (!vp56_rac_get_prob_branchy(c, tp[6])) { // cat1/2 cache[rc] = 4; if (!vp56_rac_get_prob_branchy(c, tp[7])) { val = vp56_rac_get_prob(c, 159) + 5; } else { val = (vp56_rac_get_prob(c, 165) << 1) + 7; val += vp56_rac_get_prob(c, 145); } } else { // cat 3-6 cache[rc] = 5; if (!vp56_rac_get_prob_branchy(c, tp[8])) { if (!vp56_rac_get_prob_branchy(c, tp[9])) { val = 11 + (vp56_rac_get_prob(c, 173) << 2); val += (vp56_rac_get_prob(c, 148) << 1); val += vp56_rac_get_prob(c, 140); } else { val = 19 + (vp56_rac_get_prob(c, 176) << 3); val += (vp56_rac_get_prob(c, 155) << 2); val += (vp56_rac_get_prob(c, 140) << 1); val += vp56_rac_get_prob(c, 135); } } else if (!vp56_rac_get_prob_branchy(c, tp[10])) { val = (vp56_rac_get_prob(c, 180) << 4) + 35; val += (vp56_rac_get_prob(c, 157) << 3); val += (vp56_rac_get_prob(c, 141) << 2); val += (vp56_rac_get_prob(c, 134) << 1); val += vp56_rac_get_prob(c, 130); } else { val = 67; if (!is8bitsperpixel) { if (bpp == 12) { val += vp56_rac_get_prob(c, 255) << 17; val += vp56_rac_get_prob(c, 255) << 16; } val += (vp56_rac_get_prob(c, 255) << 15); val += (vp56_rac_get_prob(c, 255) << 14); } val += (vp56_rac_get_prob(c, 254) << 13); val += (vp56_rac_get_prob(c, 254) << 12); val += (vp56_rac_get_prob(c, 254) << 11); val += (vp56_rac_get_prob(c, 252) << 10); val += (vp56_rac_get_prob(c, 249) << 9); val += (vp56_rac_get_prob(c, 243) << 8); val += (vp56_rac_get_prob(c, 230) << 7); val += (vp56_rac_get_prob(c, 196) << 6); val += (vp56_rac_get_prob(c, 177) << 5); val += (vp56_rac_get_prob(c, 153) << 4); val += (vp56_rac_get_prob(c, 140) << 3); val += (vp56_rac_get_prob(c, 133) << 2); val += (vp56_rac_get_prob(c, 130) << 1); val += vp56_rac_get_prob(c, 129); } } } #define STORE_COEF(c, i, v) do { \ if (is8bitsperpixel) { \ c[i] = v; \ } else { \ AV_WN32A(&c[i * 2], v); \ } \ } while (0) if (!--band_left) band_left = band_counts[++band]; if (is_tx32x32) STORE_COEF(coef, rc, ((vp8_rac_get(c) ? -val : val) * qmul[!!i]) / 2); else STORE_COEF(coef, rc, (vp8_rac_get(c) ? -val : val) * qmul[!!i]); nnz = (1 + cache[nb[i][0]] + cache[nb[i][1]]) >> 1; tp = p[band][nnz]; } while (++i < n_coeffs); return i; }


static const char * update_rule_action ( cmd_parms * cmd , directory_config * dcfg , const char * p1 , const char * p2 , int offset ) {
 char * my_error_msg = NULL ;
 msre_rule * rule = NULL ;
 msre_actionset * new_actionset = NULL ;
 msre_ruleset * ruleset = dcfg -> ruleset ;
 extern msc_engine * modsecurity ;
 if ( ( ruleset == NULL ) || ( ruleset == NOT_SET_P ) ) {
 return NULL ;
 }
 # ifdef DEBUG_CONF ap_log_perror ( APLOG_MARK , APLOG_STARTUP | APLOG_NOERRNO , 0 , cmd -> pool , "Update rule id=\"%s\" with action \"%s\"." , p1 , p2 ) ;
 # endif rule = msre_ruleset_fetch_rule ( ruleset , p1 , offset ) ;
 if ( rule == NULL ) {
 # ifdef DEBUG_CONF ap_log_perror ( APLOG_MARK , APLOG_STARTUP | APLOG_NOERRNO , 0 , cmd -> pool , "Update rule id=\"%s\" with action \"%s\" failed: Rule not found." , p1 , p2 ) ;
 # endif return NULL ;
 }
 if ( rule -> actionset == NULL ) {
 return apr_psprintf ( cmd -> pool , "ModSecurity: Attempt to update action for rule \"%s\" failed: Rule does not have an actionset." , p1 ) ;
 }
 new_actionset = msre_actionset_create ( modsecurity -> msre , p2 , & my_error_msg ) ;
 if ( new_actionset == NULL ) return FATAL_ERROR ;
 if ( my_error_msg != NULL ) return my_error_msg ;
 if ( ( new_actionset -> id != NOT_SET_P ) && ( rule -> actionset -> id != NULL ) && ( strcmp ( rule -> actionset -> id , new_actionset -> id ) != 0 ) ) {
 return apr_psprintf ( cmd -> pool , "ModSecurity: Rule IDs cannot be updated via SecRuleUpdateActionById." ) ;
 }
 if ( ( new_actionset -> phase != NOT_SET ) && ( rule -> actionset -> phase != new_actionset -> phase ) ) {
 return apr_psprintf ( cmd -> pool , "ModSecurity: Rule phases cannot be updated via SecRuleUpdateActionById." ) ;
 }
 # ifdef DEBUG_CONF {
 char * actions = msre_actionset_generate_action_string ( ruleset -> mp , rule -> actionset ) ;
 ap_log_perror ( APLOG_MARK , APLOG_STARTUP | APLOG_NOERRNO , 0 , cmd -> pool , "Update rule %pp id=\"%s\" old action: \"%s\"" , rule , ( rule -> actionset -> id == NOT_SET_P ? "(none)" : rule -> actionset -> id ) , actions ) ;
 }
 # endif rule -> actionset = msre_actionset_merge ( modsecurity -> msre , rule -> actionset , new_actionset , 1 ) ;
 msre_actionset_set_defaults ( rule -> actionset ) ;
 rule -> unparsed = msre_rule_generate_unparsed ( ruleset -> mp , rule , NULL , NULL , NULL ) ;
 # ifdef DEBUG_CONF {
 char * actions = msre_actionset_generate_action_string ( ruleset -> mp , rule -> actionset ) ;
 ap_log_perror ( APLOG_MARK , APLOG_STARTUP | APLOG_NOERRNO , 0 , cmd -> pool , "Update rule %pp id=\"%s\" new action: \"%s\"" , rule , ( rule -> actionset -> id == NOT_SET_P ? "(none)" : rule -> actionset -> id ) , actions ) ;
 }
 # endif return NULL ;
 }


static int search_request_new ( int type , const char * const name , int flags , evdns_callback_type user_callback , void * user_arg ) {
 assert ( type == TYPE_A || type == TYPE_AAAA ) ;
 if ( ( ( flags & DNS_QUERY_NO_SEARCH ) == 0 ) && global_search_state && global_search_state -> num_domains ) {
 struct request * req ;
 if ( string_num_dots ( name ) >= global_search_state -> ndots ) {
 req = request_new ( type , name , flags , user_callback , user_arg ) ;
 if ( ! req ) return 1 ;
 req -> search_index = - 1 ;
 }
 else {
 char * const new_name = search_make_new ( global_search_state , 0 , name ) ;
 if ( ! new_name ) return 1 ;
 req = request_new ( type , new_name , flags , user_callback , user_arg ) ;
 free ( new_name ) ;
 if ( ! req ) return 1 ;
 req -> search_index = 0 ;
 }
 req -> search_origname = strdup ( name ) ;
 req -> search_state = global_search_state ;
 req -> search_flags = flags ;
 global_search_state -> refcount ++ ;
 request_submit ( req ) ;
 return 0 ;
 }
 else {
 struct request * const req = request_new ( type , name , flags , user_callback , user_arg ) ;
 if ( ! req ) return 1 ;
 request_submit ( req ) ;
 return 0 ;
 }
 }


static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream)
{
	unsigned int header_len;

	// The first field at the start of a level 3 header is supposed to
	// indicate word size, with the idea being that the header format
	// can be extended beyond 32-bit words in the future. In practise,
	// nothing supports anything other than 32-bit (4 bytes), and neither
	// do we.

	if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) {
		return 0;
	}

	// Read the full header.

	if (!extend_raw_data(header, stream,
	                     LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) {
		return 0;
	}

	// Read the header length field (including extended headers), and
	// extend to this full length. Because this is a 32-bit value,
	// we must place a sensible limit on the amount of data that will
	// be read, to avoid possibly allocating gigabytes of memory.

	header_len = lha_decode_uint32(&RAW_DATA(header, 24));

	if (header_len > LEVEL_3_MAX_HEADER_LEN) {
		return 0;
	}

	if (!extend_raw_data(header, stream,
	                     header_len - RAW_DATA_LEN(header))) {
		return 0;
	}

	// Compression method:

	memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5);
	(*header)->compress_method[5] = '\0';

	// File lengths:

	(*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7));
	(*header)->length = lha_decode_uint32(&RAW_DATA(header, 11));

	// Unix-style timestamp.

	(*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15));

	// CRC.

	(*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21));

	// OS type:

	(*header)->os_type = RAW_DATA(header, 23);

	if (!decode_extended_headers(header, 28)) {
		return 0;
	}

	return 1;
}


static Int decGetInt ( const decNumber * dn ) {
 Int theInt ;
 const Unit * up ;
 Int got ;
 Int ilength = dn -> digits + dn -> exponent ;
 Flag neg = decNumberIsNegative ( dn ) ;
 # if DEC_MAX_EMAX > 999999999 # error GetInt may need updating [ for Emax ] # endif # if DEC_MIN_EMIN < - 999999999 # error GetInt may need updating [ for Emin ] # endif if ( ISZERO ( dn ) ) return 0 ;
 up = dn -> lsu ;
 theInt = 0 ;
 if ( dn -> exponent >= 0 ) {
 got = dn -> exponent ;
 }
 else {
 Int count = - dn -> exponent ;
 for ( ;
 count >= DECDPUN ;
 up ++ ) {
 if ( * up != 0 ) return BADINT ;
 count -= DECDPUN ;
 }
 if ( count == 0 ) got = 0 ;
 else {
 Int rem ;
 # if DECDPUN <= 4 theInt = QUOT10 ( * up , count ) ;
 rem = * up - theInt * powers [ count ] ;
 # else rem = * up % powers [ count ] ;
 theInt = * up / powers [ count ] ;
 # endif if ( rem != 0 ) return BADINT ;
 got = DECDPUN - count ;
 up ++ ;
 }
 }
 if ( got == 0 ) {
 theInt = * up ;
 got += DECDPUN ;
 up ++ ;
 }
 if ( ilength < 11 ) {
 Int save = theInt ;
 for ( ;
 got < ilength ;
 up ++ ) {
 theInt += * up * powers [ got ] ;
 got += DECDPUN ;
 }
 if ( ilength == 10 ) {
 if ( theInt / ( Int ) powers [ got - DECDPUN ] != ( Int ) * ( up - 1 ) ) ilength = 11 ;
 else if ( neg && theInt > 1999999997 ) ilength = 11 ;
 else if ( ! neg && theInt > 999999999 ) ilength = 11 ;
 if ( ilength == 11 ) theInt = save ;
 }
 }
 if ( ilength > 10 ) {
 if ( theInt & 1 ) return BIGODD ;
 return BIGEVEN ;
 }
 if ( neg ) theInt = - theInt ;
 return theInt ;
 }


  const std::string& get_id() const {
    ceph_assert(t != Wildcard && t != Tenant);
    return u.id;
  }


static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
	struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
	struct nfs_getaclargs args = {
		.fh = NFS_FH(inode),
		.acl_pages = pages,
		.acl_len = buflen,
	};
	struct nfs_getaclres res = {
		.acl_len = buflen,
	};
	void *resp_buf;
	struct rpc_message msg = {
		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
		.rpc_argp = &args,
		.rpc_resp = &res,
	};
	int ret = -ENOMEM, npages, i, acl_len = 0;

	npages = (buflen + PAGE_SIZE - 1) >> PAGE_SHIFT;
	/* As long as we're doing a round trip to the server anyway,
	 * let's be prepared for a page of acl data. */
	if (npages == 0)
		npages = 1;

	for (i = 0; i < npages; i++) {
		pages[i] = alloc_page(GFP_KERNEL);
		if (!pages[i])
			goto out_free;
	}
	if (npages > 1) {
		/* for decoding across pages */
		res.acl_scratch = alloc_page(GFP_KERNEL);
		if (!res.acl_scratch)
			goto out_free;
	}
	args.acl_len = npages * PAGE_SIZE;
	args.acl_pgbase = 0;
	/* Let decode_getfacl know not to fail if the ACL data is larger than
	 * the page we send as a guess */
	if (buf == NULL)
		res.acl_flags |= NFS4_ACL_LEN_REQUEST;
	resp_buf = page_address(pages[0]);

	dprintk("%s  buf %p buflen %zu npages %d args.acl_len %zu\n",
		__func__, buf, buflen, npages, args.acl_len);
	ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
			     &msg, &args.seq_args, &res.seq_res, 0);
	if (ret)
		goto out_free;

	acl_len = res.acl_len - res.acl_data_offset;
	if (acl_len > args.acl_len)
		nfs4_write_cached_acl(inode, NULL, acl_len);
	else
		nfs4_write_cached_acl(inode, resp_buf + res.acl_data_offset,
				      acl_len);
	if (buf) {
		ret = -ERANGE;
		if (acl_len > buflen)
			goto out_free;
		_copy_from_pages(buf, pages, res.acl_data_offset,
				res.acl_len);
	}
	ret = acl_len;
out_free:
	for (i = 0; i < npages; i++)
		if (pages[i])
			__free_page(pages[i]);
	if (res.acl_scratch)
		__free_page(res.acl_scratch);
	return ret;
}


  const std::string& get_tenant() const {
    ceph_assert(t != Wildcard);
    return u.tenant;
  }


int ff_MPV_common_frame_size_change ( MpegEncContext * s ) {
 int i , err = 0 ;
 if ( s -> slice_context_count > 1 ) {
 for ( i = 0 ;
 i < s -> slice_context_count ;
 i ++ ) {
 free_duplicate_context ( s -> thread_context [ i ] ) ;
 }
 for ( i = 1 ;
 i < s -> slice_context_count ;
 i ++ ) {
 av_freep ( & s -> thread_context [ i ] ) ;
 }
 }
 else free_duplicate_context ( s ) ;
 free_context_frame ( s ) ;
 if ( s -> picture ) for ( i = 0 ;
 i < s -> picture_count ;
 i ++ ) {
 s -> picture [ i ] . needs_realloc = 1 ;
 }
 s -> last_picture_ptr = s -> next_picture_ptr = s -> current_picture_ptr = NULL ;
 if ( s -> codec_id == AV_CODEC_ID_MPEG2VIDEO && ! s -> progressive_sequence ) s -> mb_height = ( s -> height + 31 ) / 32 * 2 ;
 else if ( s -> codec_id != AV_CODEC_ID_H264 ) s -> mb_height = ( s -> height + 15 ) / 16 ;
 if ( ( s -> width || s -> height ) && av_image_check_size ( s -> width , s -> height , 0 , s -> avctx ) ) return AVERROR_INVALIDDATA ;
 if ( ( err = init_context_frame ( s ) ) ) goto fail ;
 s -> thread_context [ 0 ] = s ;
 if ( s -> width && s -> height ) {
 int nb_slices = s -> slice_context_count ;
 if ( nb_slices > 1 ) {
 for ( i = 1 ;
 i < nb_slices ;
 i ++ ) {
 s -> thread_context [ i ] = av_malloc ( sizeof ( MpegEncContext ) ) ;
 memcpy ( s -> thread_context [ i ] , s , sizeof ( MpegEncContext ) ) ;
 }
 for ( i = 0 ;
 i < nb_slices ;
 i ++ ) {
 if ( init_duplicate_context ( s -> thread_context [ i ] ) < 0 ) goto fail ;
 s -> thread_context [ i ] -> start_mb_y = ( s -> mb_height * ( i ) + nb_slices / 2 ) / nb_slices ;
 s -> thread_context [ i ] -> end_mb_y = ( s -> mb_height * ( i + 1 ) + nb_slices / 2 ) / nb_slices ;
 }
 }
 else {
 if ( init_duplicate_context ( s ) < 0 ) goto fail ;
 s -> start_mb_y = 0 ;
 s -> end_mb_y = s -> mb_height ;
 }
 s -> slice_context_count = nb_slices ;
 }
 return 0 ;
 fail : ff_MPV_common_end ( s ) ;
 return err ;
 }


xmlDictComputeBigKey(const xmlChar* data, int namelen) {
    uint32_t hash;
    int i;

    if (namelen <= 0 || data == NULL) return(0);

    hash = 0;

    for (i = 0;i < namelen; i++) {
        hash += data[i];
	hash += (hash << 10);
	hash ^= (hash >> 6);
    }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);

    return hash;
}


static int theora_decode_header(AVCodecContext *avctx, GetBitContext gb) { Vp3DecodeContext *s = avctx->priv_data; s->theora = get_bits_long(&gb, 24); av_log(avctx, AV_LOG_INFO, "Theora bitstream version %X\n", s->theora); /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */ /* but previous versions have the image flipped relative to vp3 */ if (s->theora < 0x030200) { s->flipped_image = 1; av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n"); } s->width = get_bits(&gb, 16) << 4; s->height = get_bits(&gb, 16) << 4; if(avcodec_check_dimensions(avctx, s->width, s->height)){ av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height); s->width= s->height= 0; return -1; } if (s->theora >= 0x030400) { skip_bits(&gb, 32); /* total number of superblocks in a frame */ // fixme, the next field is 36bits long skip_bits(&gb, 32); /* total number of blocks in a frame */ skip_bits(&gb, 4); /* total number of blocks in a frame */ skip_bits(&gb, 32); /* total number of macroblocks in a frame */ skip_bits(&gb, 24); /* frame width */ skip_bits(&gb, 24); /* frame height */ } else { skip_bits(&gb, 24); /* frame width */ skip_bits(&gb, 24); /* frame height */ } skip_bits(&gb, 8); /* offset x */ skip_bits(&gb, 8); /* offset y */ skip_bits(&gb, 32); /* fps numerator */ skip_bits(&gb, 32); /* fps denumerator */ skip_bits(&gb, 24); /* aspect numerator */ skip_bits(&gb, 24); /* aspect denumerator */ if (s->theora < 0x030200) skip_bits(&gb, 5); /* keyframe frequency force */ skip_bits(&gb, 8); /* colorspace */ if (s->theora >= 0x030400) skip_bits(&gb, 2); /* pixel format: 420,res,422,444 */ skip_bits(&gb, 24); /* bitrate */ skip_bits(&gb, 6); /* quality hint */ if (s->theora >= 0x030200) { skip_bits(&gb, 5); /* keyframe frequency force */ if (s->theora < 0x030400) skip_bits(&gb, 5); /* spare bits */ } // align_get_bits(&gb); avctx->width = s->width; avctx->height = s->height; return 0; }


static void dumpTablespaces ( PGconn * conn ) {
 PGresult * res ;
 int i ;
 if ( server_version >= 90600 ) res = executeQuery ( conn , "SELECT oid, spcname, " "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, " "pg_catalog.pg_tablespace_location(oid), " "(SELECT pg_catalog.array_agg(acl) FROM (SELECT pg_catalog.unnest(coalesce(spcacl,pg_catalog.acldefault('t',spcowner))) AS acl " "EXCEPT SELECT pg_catalog.unnest(pg_catalog.acldefault('t',spcowner))) as foo)" "AS spcacl," "(SELECT pg_catalog.array_agg(acl) FROM (SELECT pg_catalog.unnest(pg_catalog.acldefault('t',spcowner)) AS acl " "EXCEPT SELECT pg_catalog.unnest(coalesce(spcacl,pg_catalog.acldefault('t',spcowner)))) as foo)" "AS rspcacl," "array_to_string(spcoptions, ', ')," "pg_catalog.shobj_description(oid, 'pg_tablespace') " "FROM pg_catalog.pg_tablespace " "WHERE spcname !~ '^pg_' " "ORDER BY 1" ) ;
 else if ( server_version >= 90200 ) res = executeQuery ( conn , "SELECT oid, spcname, " "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, " "pg_catalog.pg_tablespace_location(oid), spcacl, '' as rspcacl, " "array_to_string(spcoptions, ', ')," "pg_catalog.shobj_description(oid, 'pg_tablespace') " "FROM pg_catalog.pg_tablespace " "WHERE spcname !~ '^pg_' " "ORDER BY 1" ) ;
 else if ( server_version >= 90000 ) res = executeQuery ( conn , "SELECT oid, spcname, " "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, " "spclocation, spcacl, '' as rspcacl, " "array_to_string(spcoptions, ', ')," "pg_catalog.shobj_description(oid, 'pg_tablespace') " "FROM pg_catalog.pg_tablespace " "WHERE spcname !~ '^pg_' " "ORDER BY 1" ) ;
 else if ( server_version >= 80200 ) res = executeQuery ( conn , "SELECT oid, spcname, " "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, " "spclocation, spcacl, '' as rspcacl, null, " "pg_catalog.shobj_description(oid, 'pg_tablespace') " "FROM pg_catalog.pg_tablespace " "WHERE spcname !~ '^pg_' " "ORDER BY 1" ) ;
 else res = executeQuery ( conn , "SELECT oid, spcname, " "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, " "spclocation, spcacl, '' as rspcacl, " "null, null " "FROM pg_catalog.pg_tablespace " "WHERE spcname !~ '^pg_' " "ORDER BY 1" ) ;
 if ( PQntuples ( res ) > 0 ) fprintf ( OPF , "--\n-- Tablespaces\n--\n\n" ) ;
 for ( i = 0 ;
 i < PQntuples ( res ) ;
 i ++ ) {
 PQExpBuffer buf = createPQExpBuffer ( ) ;
 uint32 spcoid = atooid ( PQgetvalue ( res , i , 0 ) ) ;
 char * spcname = PQgetvalue ( res , i , 1 ) ;
 char * spcowner = PQgetvalue ( res , i , 2 ) ;
 char * spclocation = PQgetvalue ( res , i , 3 ) ;
 char * spcacl = PQgetvalue ( res , i , 4 ) ;
 char * rspcacl = PQgetvalue ( res , i , 5 ) ;
 char * spcoptions = PQgetvalue ( res , i , 6 ) ;
 char * spccomment = PQgetvalue ( res , i , 7 ) ;
 char * fspcname ;
 fspcname = pg_strdup ( fmtId ( spcname ) ) ;
 appendPQExpBuffer ( buf , "CREATE TABLESPACE %s" , fspcname ) ;
 appendPQExpBuffer ( buf , " OWNER %s" , fmtId ( spcowner ) ) ;
 appendPQExpBufferStr ( buf , " LOCATION " ) ;
 appendStringLiteralConn ( buf , spclocation , conn ) ;
 appendPQExpBufferStr ( buf , ";
\n" ) ;
 if ( spcoptions && spcoptions [ 0 ] != '\0' ) appendPQExpBuffer ( buf , "ALTER TABLESPACE %s SET (%s);
\n" , fspcname , spcoptions ) ;
 if ( ! skip_acls && ! buildACLCommands ( fspcname , NULL , "TABLESPACE" , spcacl , rspcacl , spcowner , "" , server_version , buf ) ) {
 fprintf ( stderr , _ ( "%s: could not parse ACL list (%s) for tablespace \"%s\"\n" ) , progname , spcacl , fspcname ) ;
 PQfinish ( conn ) ;
 exit_nicely ( 1 ) ;
 }
 if ( spccomment && strlen ( spccomment ) ) {
 appendPQExpBuffer ( buf , "COMMENT ON TABLESPACE %s IS " , fspcname ) ;
 appendStringLiteralConn ( buf , spccomment , conn ) ;
 appendPQExpBufferStr ( buf , ";
\n" ) ;
 }
 if ( ! no_security_labels && server_version >= 90200 ) buildShSecLabels ( conn , "pg_tablespace" , spcoid , buf , "TABLESPACE" , fspcname ) ;
 fprintf ( OPF , "%s" , buf -> data ) ;
 free ( fspcname ) ;
 destroyPQExpBuffer ( buf ) ;
 }
 PQclear ( res ) ;
 fprintf ( OPF , "\n\n" ) ;
 }


int mainwindow_set_statusbar_lines ( MAIN_WINDOW_REC * window , int top , int bottom ) {
 int ret ;
 ret = - 1 ;
 if ( top != 0 ) {
 ret = window -> statusbar_lines_top ;
 window -> statusbar_lines_top += top ;
 window -> statusbar_lines += top ;
 }
 if ( bottom != 0 ) {
 ret = window -> statusbar_lines_bottom ;
 window -> statusbar_lines_bottom += bottom ;
 window -> statusbar_lines += bottom ;
 }
 if ( top + bottom != 0 ) window -> size_dirty = TRUE ;
 return ret ;
 }


inline bool operator ==(const MaskedIP& l, const MaskedIP& r) {
  auto shift = std::max((l.v6 ? 128 : 32) - l.prefix,
			(r.v6 ? 128 : 32) - r.prefix);
  ceph_assert(shift > 0);
  return (l.addr >> shift) == (r.addr >> shift);
}


rio_ioctl (struct net_device *dev, struct ifreq *rq, int cmd)
{
	int phy_addr;
	struct netdev_private *np = netdev_priv(dev);
	struct mii_data *miidata = (struct mii_data *) &rq->ifr_ifru;

	struct netdev_desc *desc;
	int i;

	phy_addr = np->phy_addr;
	switch (cmd) {
	case SIOCDEVPRIVATE:
		break;

	case SIOCDEVPRIVATE + 1:
		miidata->out_value = mii_read (dev, phy_addr, miidata->reg_num);
		break;
	case SIOCDEVPRIVATE + 2:
		mii_write (dev, phy_addr, miidata->reg_num, miidata->in_value);
		break;
	case SIOCDEVPRIVATE + 3:
		break;
	case SIOCDEVPRIVATE + 4:
		break;
	case SIOCDEVPRIVATE + 5:
		netif_stop_queue (dev);
		break;
	case SIOCDEVPRIVATE + 6:
		netif_wake_queue (dev);
		break;
	case SIOCDEVPRIVATE + 7:
		printk
		    ("tx_full=%x cur_tx=%lx old_tx=%lx cur_rx=%lx old_rx=%lx\n",
		     netif_queue_stopped(dev), np->cur_tx, np->old_tx, np->cur_rx,
		     np->old_rx);
		break;
	case SIOCDEVPRIVATE + 8:
		printk("TX ring:\n");
		for (i = 0; i < TX_RING_SIZE; i++) {
			desc = &np->tx_ring[i];
			printk
			    ("%02x:cur:%08x next:%08x status:%08x frag1:%08x frag0:%08x",
			     i,
			     (u32) (np->tx_ring_dma + i * sizeof (*desc)),
			     (u32)le64_to_cpu(desc->next_desc),
			     (u32)le64_to_cpu(desc->status),
			     (u32)(le64_to_cpu(desc->fraginfo) >> 32),
			     (u32)le64_to_cpu(desc->fraginfo));
			printk ("\n");
		}
		printk ("\n");
		break;

	default:
		return -EOPNOTSUPP;
	}
	return 0;
}


int CephxSessionHandler::_calc_signature(Message *m, uint64_t *psig)
{
  const ceph_msg_header& header = m->get_header();
  const ceph_msg_footer& footer = m->get_footer();

  if (!HAVE_FEATURE(features, CEPHX_V2)) {
    // legacy pre-mimic behavior for compatibility

    // optimized signature calculation
    // - avoid temporary allocated buffers from encode_encrypt[_enc_bl]
    // - skip the leading 4 byte wrapper from encode_encrypt
    struct {
      __u8 v;
      __le64 magic;
      __le32 len;
      __le32 header_crc;
      __le32 front_crc;
      __le32 middle_crc;
      __le32 data_crc;
    } __attribute__ ((packed)) sigblock = {
      1, mswab(AUTH_ENC_MAGIC), mswab<uint32_t>(4*4),
      mswab<uint32_t>(header.crc), mswab<uint32_t>(footer.front_crc),
      mswab<uint32_t>(footer.middle_crc), mswab<uint32_t>(footer.data_crc)
    };

    char exp_buf[CryptoKey::get_max_outbuf_size(sizeof(sigblock))];

    try {
      const CryptoKey::in_slice_t in {
	sizeof(sigblock),
	reinterpret_cast<const unsigned char*>(&sigblock)
      };
      const CryptoKey::out_slice_t out {
	sizeof(exp_buf),
	reinterpret_cast<unsigned char*>(&exp_buf)
      };
      key.encrypt(cct, in, out);
    } catch (std::exception& e) {
      lderr(cct) << __func__ << " failed to encrypt signature block" << dendl;
      return -1;
    }

    *psig = *reinterpret_cast<__le64*>(exp_buf);
  } else {
    // newer mimic+ signatures
    struct {
      __le32 header_crc;
      __le32 front_crc;
      __le32 front_len;
      __le32 middle_crc;
      __le32 middle_len;
      __le32 data_crc;
      __le32 data_len;
      __le32 seq_lower_word;
    } __attribute__ ((packed)) sigblock = {
      mswab<uint32_t>(header.crc),
      mswab<uint32_t>(footer.front_crc),
      mswab<uint32_t>(header.front_len),
      mswab<uint32_t>(footer.middle_crc),
      mswab<uint32_t>(header.middle_len),
      mswab<uint32_t>(footer.data_crc),
      mswab<uint32_t>(header.data_len),
      mswab<uint32_t>(header.seq)
    };

    char exp_buf[CryptoKey::get_max_outbuf_size(sizeof(sigblock))];

    try {
      const CryptoKey::in_slice_t in {
	sizeof(sigblock),
	reinterpret_cast<const unsigned char*>(&sigblock)
      };
      const CryptoKey::out_slice_t out {
	sizeof(exp_buf),
	reinterpret_cast<unsigned char*>(&exp_buf)
      };
      key.encrypt(cct, in, out);
    } catch (std::exception& e) {
      lderr(cct) << __func__ << " failed to encrypt signature block" << dendl;
      return -1;
    }

    struct enc {
      __le64 a, b, c, d;
    } *penc = reinterpret_cast<enc*>(exp_buf);
    *psig = penc->a ^ penc->b ^ penc->c ^ penc->d;
  }

  ldout(cct, 10) << __func__ << " seq " << m->get_seq()
		 << " front_crc_ = " << footer.front_crc
		 << " middle_crc = " << footer.middle_crc
		 << " data_crc = " << footer.data_crc
		 << " sig = " << *psig
		 << dendl;
  return 0;
}


static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
    gint64 *data_offset)
{
	gint64	offset;
	int	pkt_len;
	char	line[COSINE_LINE_LENGTH];

	/* Find the next packet */
	offset = cosine_seek_next_packet(wth, err, err_info, line);
	if (offset < 0)
		return FALSE;
	*data_offset = offset;

	/* Parse the header */
	pkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info);
	if (pkt_len == -1)
		return FALSE;

	/* Convert the ASCII hex dump to binary data */
	return parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len,
	    wth->frame_buffer, err, err_info);
}